What is Ultrasonic sensors?
An ultrasonic sensor is a device that can measure the distance to an object by using sound waves. It measures distance by sending out a sound wave at a specific frequency and listening for that sound wave to bounce back. By recording the elapsed time between the sound wave being generated and the sound wave bouncing back, it is possible to calculate the disctance between the sonar sensor and the object.
What Will I Learn?
- How to use ultrasonic sensors for detecting an obstacle
- How to program Ultrasonic sensors in Arduino IDE
- How to connect the pinout for ultrasonic sensors to Arduino
Requirements/Materials Needed
- Arduino IDE
- Ultrasonic Sensors
- Wires
- (2) LED's(Yellow & Green)
- (2) 220ohms Resistors
- Breadboard
Difficulty
- Intermediate
Obstacle avoiding using Ultrasonic sensors
Tutorial Contents
Let's Start
Step 1: Physical Connection of the Components to the Arduino Board
Connect the following:
- Ultrasonic Sensor (VCC/+5v) to Arduino(+5)
- Ultrasonic Sensor (GND) to Arduino(GND)
- Ultrasonic Sensor (TRIG) to Arduino Digital Pin(3)
- Ultrasonic Sensor (ECHO) to Arduino Digital Pin(4)
- Arduino Digital Pin (2) to Resistor to LED Green to GND
- Arduino Digital Pin (5) to Resistor to LED Yellow to GND
Step 2: Software Connection for Arduino to Ultrasonic Sensor
- Open your Arduino IDE. Go to Tools and change your board Arduino Nano. Paste the given code below in the Arduino IDE and wait for it to be done uploading.
|Code for Obstacle Avoidnace|
int _ABVAR_1_ultrasonic = 0 ;
int ardublockUltrasonicSensorCodeAutoGeneratedReturnCM(int trigPin, int echoPin)
{
long duration;
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(20);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
duration = duration / 59;
if ((duration < 2) || (duration > 300)) return false;
return duration;
}
void setup()
{
digitalWrite( 3 , LOW );
Serial.begin(9600);
pinMode( 2 , OUTPUT);
pinMode( 5 , OUTPUT);
}
void loop()
{
_ABVAR_1_ultrasonic = ardublockUltrasonicSensorCodeAutoGeneratedReturnCM( 3 , 4 ) ;
Serial.print("distane:");
Serial.print(" ");
Serial.print(_ABVAR_1_ultrasonic);
Serial.print(" ");
Serial.println();
if (( ( _ABVAR_1_ultrasonic ) < ( 15 ) ))
{
digitalWrite(2 , HIGH);
digitalWrite(5 , LOW);
}
else
{
digitalWrite(5 , HIGH);
digitalWrite(2 , LOW);
}
}
- Click on the Upload button to upload the program in your Arduino board. And wait for it to finish uploading.
- Check the result of the program and it must be running.
You can test the distance when clicking the Serial Monitor on your Arduino IDE.
The yellow LED indicates there is no obstacle detected.
The green LED indicates there is an obstacle detected.
Curriculum
Other Arduino projects/contribution:
That's all, hope you learn something with this
Thank You!
Posted on Utopian.io - Rewarding Open Source Contributors