In this lesson we explore using the HC-SR04 from our Arduino Kit to measure distance. The sensor sends out a ping, and then waits to hear the echo. It measures the time between when the ping is sent and when the echo is heard. Knowing pingTravelTime, allows you to calculate distance from the sensor. In this lesson we will show you how to connect the sensor, and program it to read pingTravelTime. In future lessons we will show you how to change this into distance.
Notice we used an Arduino Nano, which allows the entire project to be build on a single breadboard. This allows a neater, smaller build, and one less likely to have problems from poor or loose connections. The build neatness is also facilitated by using small straight jumper wires, which you can get HERE.
Connecting up the HC-SR04 sensor is simple, as illustrated in this diagram:
This video will take you through our build and initial work step-by-step.
The simple code below is what we used in the video to begin making measurements with the sensor.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | int trigPin=12; int echoPin=11; int pingTravelTime; void setup() { // put your setup code here, to run once: pinMode(trigPin,OUTPUT); pinMode(echoPin,INPUT); Serial.begin(9600); } void loop() { // put your main code here, to run repeatedly: digitalWrite(trigPin,LOW); delayMicroseconds(10); digitalWrite(trigPin,HIGH); delayMicroseconds(10); digitalWrite(trigPin,LOW); pingTravelTime=pulseIn(echoPin,HIGH); delay(25); Serial.println(pingTravelTime); } |