Hi guys, I'm making an Arduino car that uses an ultrasonic sensor to dodge obstacles. The problem is that suddenly the sensor starts showing false data, marking 0 when it should not. I am using the HC-SR04 sensor (i´m using an arduino UNO), this is my code:
It is the pulse that Trig sends and that Echo will later read and so the distance can be measured (Trig is connected to pin 4 and Echo is connected to pin 6)
This might be your problem. If you delay too long, pulseIn() could miss the rising edge of the echo pulse and result in a timeout (0). The typical delay is:
The Arduino is not a power supply, and the 5V output cannot be used to power motors or servos. Neither can a computer USB socket. The electrical noise from the motors creates all sorts of havoc, including interfering with sensor operation.
A 4xAA battery pack will work for the motors and save the Arduino and/or the USB port from damage.