Sunday, 8 February 2015

Get distance reading on command in arduino

As you might already know how to get distance reading from an ultrasonic sensor in Arduino, but in this post I want to show you a special way to get the distance reading not like you usually see the serial monitor keeps printing the distances, perhaps you will get the reading only when you ask the arduino board to show you the distance.

Ok, the code you going to see here is basically does two thing at once.
(a) it turns on a LED when the distance is more then 30cm, and
(b) it prints the distance when you send a command via serial monitor or bluetooth.

Let's see the code:
int ledPin = 4;
int trigPin = 2;
int echoPin = 3;
void setup() {
  Serial.begin (9600);
  pinMode(ledPin, OUTPUT);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}
String str;

void loop() {
 
  if(Serial.available())
{
str = Serial.readStringUntil('\n');

if(str == "d")
{

  int duration, distance;
  digitalWrite (trigPin, HIGH);
  delayMicroseconds (10);
  digitalWrite (trigPin, LOW);
  duration = pulseIn (echoPin, HIGH);
  distance = (duration/2) / 29.1;

      Serial.print(distance);  
      Serial.print("cm");
      Serial.println();


  }   
 }

 int duration, distance;
  digitalWrite (trigPin, HIGH);
  delayMicroseconds (10);
  digitalWrite (trigPin, LOW);
  duration = pulseIn (echoPin, HIGH);
  distance = (duration/2) / 29.1;
  delay(100);
        
 if (distance > 30) {  // Change the number for long or short distances.
    digitalWrite (ledPin, HIGH);
  } else {
    digitalWrite (ledPin, LOW);
  
  }
}

What is the command code?
Well, the red letter "d" you can see in the "if(str == "d")" statement that is the code, you can change that code to what ever you want and the yellow highlighted code below does the measuring and printing job.

int duration, distance;
  digitalWrite (trigPin, HIGH);
  delayMicroseconds (10);
  digitalWrite (trigPin, LOW);
  duration = pulseIn (echoPin, HIGH);
  distance = (duration/2) / 29.1;

      Serial.print(distance);  
      Serial.print("cm");
      Serial.println();


Note: After uploading this sketch on your arduino > open your serial monitor and type the letter d and send it and the board will send you the distance measurement.
That's it, hopefully this might help you and if you want to know more about this please comment below I'll try my by best to help you. Thanks

No comments:

Post a Comment