SR04 is a module that can detect distance between 2cm to 400cm by sending out ultrasonic waves and calculating the time between the sent signal and echo received.
Steps:
Steps:
- Send the trigger signal - a TTL 10us signal
- Wait for the echo pin to get high.
- Calculate the time for which the echo pin is high using a timer.
- Calculate the distance using
Distance = high level time * velocity (340M/S) / 2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | const int echo = 11; const int trig = 10; long duration; long dist; void setup() { pinMode(echo,INPUT); pinMode(trig,OUTPUT); Serial.begin(9600); } void loop() { digitalWrite(trig,HIGH); delayMicroseconds(10); digitalWrite(trig,LOW); duration=pulseIn(echo,HIGH); dist = duration / 58; Serial.println(dist); Serial.println(duration); delay(1000); } |
The above code is very basic and does not have the out of range or too close feature. Hopefully I will update it in the next post.
No comments :
Post a Comment