This is how to use the HC-SR04 Ultrasonic Distance Sensor. This is the most ubiquitous ultrasonic sensor for Arduino.
It works by sending out Ultrasonic pulses (higher-frequency-than-sound) and timing how long it takes for the echo to return. Like a repetitive “ping”.
Wire the sensor as shown above.
Vcc -> 5V
Trig -> D12
Echo -> D11
Gnd -> Gnd
The code below triggers the HC-SR04 to send out Ultrasonic Pulses by pulsing D12 (Trig). It then measures the time until the response has been received onto D11 (Echo).
We’re going to use the NewPing library to do the timing behind the scenes.
You can get that from here. Add the library to the Arduino IDE (1.0.5) : Sketch -> Import Library -> Add Library…
Here’s some example code. Open the Serial Monitor to see the distance.
(You can get this code from File -> Examples -> NewPing -> NewPingExample)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
// --------------------------------------------------------------------------- // Example NewPing library sketch that does a ping about 20 times per second. // --------------------------------------------------------------------------- #include <NewPing.h> #define TRIGGER_PIN 12 // Arduino pin tied to trigger pin on the ultrasonic sensor. #define ECHO_PIN 11 // Arduino pin tied to echo pin on the ultrasonic sensor. #define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm. NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance. void setup() { Serial.begin(9600); // Open serial monitor at 115200 baud to see ping results. } void loop() { delay(50); // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings. unsigned int uS = sonar.ping(); // Send ping, get ping time in microseconds (uS). Serial.print( "Ping: " ); Serial.print(uS / US_ROUNDTRIP_CM); // Convert ping time to distance in cm and print result (0 = outside set distance range) Serial.println( "cm" ); } |