In this video lesson we show how to use the HC-SR04 ultrasonic sensor to detect the distance to obstacles in a robotic application. We use the sensor to measure the time it takes for a ping to travel from the sensor, to the target, and then back. We use this measured time, and the known speed of sound to calculate the distance to the target. This will be used in future lessons to keep the robot from running into an obstacle.
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 29 30 31 32 33 34 35 36 37 |
int Trig=A5; int Echo=A4; int pingT; float targetDistance; 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: targetDistance=measDist(); Serial.println(targetDistance); 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; } float measDist(){ int pingTravelTime; float Dist; pingTravelTime=pingTime(); Dist=(pingTravelTime*761.*5280.*12.)/(1000000.*3600.); Dist=Dist/2; return Dist; } |