fbpx

Procedure

Schematic:

Steps to perform the experiment:

  • Take a breadboard, connect 5V and ground from Arduino to the power rails of the breadboard.

  • Connect Ultrasonic Sensor on the breadboard, Vcc and Gnd to the power rail as shown in figure.

  • Connect Trig and Echo of ultrasonic sensor to the Arduino as mentioned in the code.

  • Connect two LEDs on the breadboard. Positive Legs of LEDs to the Arduino Pin as mentioned in the code. Negative Legs of LEDs through 330 Ohm resistor to the ground.

Programming:

int sensorvalue = 0;
long readUltrasonicDistance(int triggerPin, int echoPin)
{
pinMode(triggerPin, OUTPUT);
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
digitalWrite(triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(triggerPin, LOW);
pinMode(echoPin, INPUT);
return pulseIn(echoPin, HIGH);
}
void setup()
{
Serial.begin(9600);
pinMode(5, OUTPUT);
pinMode(2, OUTPUT);
}
void loop()
{
sensorvalue = 0.01723 * readUltrasonicDistance(10, 9);
Serial.println(sensorvalue);
delay(500);
if (sensorvalue <= 50)
{
digitalWrite(5, HIGH);
}
if (sensorvalue > 51) {
digitalWrite(2, HIGH);
}
}

After uploading the code, open the Arduino IDE Serial Monitor at a 9600 baud rate. You should get the distance displayed.