In this lesson we explain the concept of echolocation, and how the HC-SR04 ultrasonic sensor can be used to measure the time it takes a ping to go out, bounce off a target and come back. From this ping travel time, it is possible to precisely calculate the distance to the target. For your convenience, the code we developed is included below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | int Trig=A5; int Echo=A4; int pingT; void setup() { // put your setup code here, to run once: pinMode(Trig,OUTPUT); pinMode(Echo,INPUT); Serial.begin(9600); } void loop() { // put your main code here, to run repeatedly: pingT=pingTime(); Serial.println(pingT); delay(500); } int pingTime(){ int pingTravelTime; digitalWrite(Trig, LOW); delayMicroseconds(2); digitalWrite(Trig, HIGH); delayMicroseconds(20); digitalWrite(Trig, LOW); pingTravelTime = pulseIn(Echo, HIGH); return pingTravelTime; } |