Ultrasonic Proximity Sensor with Arduino
Here is a simple example about how to use the Ultrasonic sensor to detect objects.
Parts List
- Arduino UNO R3 (I use the Adafruit mount)
- One (1) HC-SR04 Ultrasonic Sensor
- One (1) Red LED, One (1) Green LED
- Two (2) 560 ohm (Green, Blue, Brown, Gold) Resistors
- Half Breadboard
- Eight (8) Male/Male hookup wires
- A ruler that measures centimeters (or use the serial monitor)
See the demo video here:
Connect as the pictures shows, click to see large image:
And last step is put the code into your arduino!
[c]
/*
HC-SR04 Ping distance sensor]
VCC to arduino 5v GND to arduino GND
Echo to Arduino pin 13 Trig to Arduino pin 12
Red POS to Arduino pin 11
Green POS to Arduino pin 10
560 ohm resistor to both LED NEG and GRD power rail
*/
#define trigPin 13
#define echoPin 12
#define led 11
#define led2 10
void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(led, OUTPUT);
pinMode(led2, OUTPUT);
}
void loop() {
long duration, distance;
digitalWrite(trigPin, LOW); // Added this line
delayMicroseconds(2); // Added this line
digitalWrite(trigPin, HIGH);
// delayMicroseconds(1000); – Removed this line
delayMicroseconds(10); // Added this line
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
if (distance < 4) { // This is where the LED On/Off happens digitalWrite(led,HIGH); // When the Red condition is met, the Green LED should turn off digitalWrite(led2,LOW); } else { digitalWrite(led,LOW); digitalWrite(led2,HIGH); } if (distance >= 200 || distance <= 0){
Serial.println("Out of range");
}
else {
Serial.print(distance);
Serial.println(" cm");
}
delay(500);
}
[/c]
Comments (5)
Hi,
For the distance measurement you’ll need a temperature sensor.
Why? Because the distance is calculated based on the speed of sound that varies by the temperature.
The following calculation will be wrong, based on the above:
distance = (duration/2) / 29.1;
Please, could you just review this article? It would be good for everyone, to have correct codes for arduino & sensors!
Hello Csabee,
Just correct some mistakes in the code and complied successfully by myself again, please try it. And sorry for this problem!
Hi,
As again: this is not correct. You need to add a temperature sensor to this system, to get accurate measurment,
Yea the temperature is somewhat important, but for an indoor robot this thing is fine by itself.