Arduino and Ultrasonic sensor - ElectroEngineers

Destination to project makers.

Sunday, 20 August 2017

Arduino and Ultrasonic sensor

Ultrasonic sensor is a ranging sensor used to measure the distance of an object. It has a ping emitter and a receiver. Emitter radiates the sound waves. Receiver receives the same. Distance is calculated by measuring the time interval. The formula to find distance is
Distance = time interval * speed of sound waves/2.

Components Required:

Arduino board
Ultrasonic sensor
Connecting wires

Pin connection.

Vcc- 5v
Grnd - 0v
Dout - any digital pin

Step 1. Make the connection  as specified above.
Step 2: upload the below sketch

Arduino code

  1. #define trigPin 13
  2. #define echoPin 12
  3. #define led 11
  4. #define led2 10

  5. void setup() {
  6.   Serial.begin (9600);
  7.   pinMode(trigPin, OUTPUT);
  8.   pinMode(echoPin, INPUT);
  9.   pinMode(led, OUTPUT);
  10.   pinMode(led2, OUTPUT);
  11. }

  12. void loop() {
  13.   long duration, distance;
  14.   digitalWrite(trigPin, LOW);  // Added this line
  15.   delayMicroseconds(2); // Added this line
  16.   digitalWrite(trigPin, HIGH);
  17. //  delayMicroseconds(1000); - Removed this line
  18.   delayMicroseconds(10); // Added this line
  19.   digitalWrite(trigPin, LOW);
  20.   duration = pulseIn(echoPin, HIGH);
  21.   distance = (duration/2) / 29.1;
  22.   if (distance < 4) {  // This is where the LED On/Off happens
  23.     digitalWrite(led,HIGH); // When the Red condition is met, the Green LED should turn off
  24.   digitalWrite(led2,LOW);
  25. }
  26.   else {
  27.     digitalWrite(led,LOW);
  28.     digitalWrite(led2,HIGH);
  29.   }
  30.   if (distance >= 200 || distance <= 0){
  31.     Serial.println("Out of range");
  32.   }
  33.   else {
  34.     Serial.print(distance);
  35.     Serial.println(" cm");
  36.   }
  37.   delay(500);
  38. }


Step 3. Open the serial monitor to see the output.

No comments:

Post a Comment

Followers