SAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD

Control different things at different distance with Arduino



In this post I'm going share a sketch with you which (sketch) can turn on and off as many things you want at different distance as you wish. This means you can turn something at a specific distance. For example you want to turn on a motor after 10cm and turn it off at 50cm, you can do this easily with the sketch below.

Note: I've used three leds here if you replace them with relay, motor and other stuff it will still work fine.

Things to change:

Change the pins as you wish.
int trigPin = 2;
int echoPin = 3;
int led1 = 4;
---
Make sure you write OUTPUT to every led.
 pinMode(led1, OUTPUT);
---
if (distance >=1 && distance <=10){
 Remember >= means from and <=  means under.
 And the number you seeing after >= and <= is centimetre/s.
 ---

 Here is the sketch.
//define the pins for ultrasonic sensor and leds here
int trigPin = 2;
int echoPin = 3;
int led1 = 4;
int led2 = 5;
int led3 = 6;


void setup() {
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(led3, OUTPUT);

}

void loop() {
   int duration, distance;
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(1000);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;

if (distance >=1 && distance <=10){
   Serial.print(distance);
    Serial.println(" cm");
    digitalWrite(led1, HIGH);
    digitalWrite(led2, LOW);
    digitalWrite(led3, LOW);

  }

  else if (distance >=11 && distance <=20){
   Serial.print(distance);
    Serial.println(" cm");
    digitalWrite(led2, HIGH);
    digitalWrite(led1, LOW);
    digitalWrite(led3, LOW);

  }

  else if (distance >=21 && distance <=30){
   Serial.print(distance);
    Serial.println(" cm");
    digitalWrite(led3, HIGH);
    digitalWrite(led1, LOW);
    digitalWrite(led2, LOW);

  }
 
else {
    Serial.print(distance);
    Serial.println(" cm");
    digitalWrite(led1, LOW);
    digitalWrite(led2, LOW);
    digitalWrite(led3, LOW);
    delay(30);
  }
}

Watch the video to see the sketch in action.



No comments:

Post a Comment



Newly posted:
Reason why rich getting richer and poor getting poorer