Vivotech Hc-sr04 Arduino Ultrasonic Distance Measuring Sensor

and the data sheet.
With a bit of wiring and coding, I've been able to hook this up to my Raspberry Pi. A couple gotchas in case yours isn't working for you:
- Make sure you're powering it with 5V. Turns out that running off the 5V GPIO pin, it was actually only supplying ~4.8V! When I switched to a voltage converter that exactly supplied 5V I was at least getting a signal back in the echo pin.
- The RPi is not a real time system. It can miss the echo edge rises and falls! This is why my python code uses while loops (below) instead of GPIO.wait_for_edge(...).
- Make sure you have a logic analyzer. I would have saved hours of debugging had I had a logic analyzer to tell me that I was getting the right waveform in the echo pin.
- Since this is a sensor, start with having it point faraway, this will give your RPi as much time as necessary to catch the echo signal. As mentioned above, if the waveform is too short, the RPi will miss the falling edge when using GPIO.wait_for_edge(...) !
Here's the code (also here: https://github.com/gfxblit/mylatestmoneysink/blob/master/HCSR04.py)
#!/usr/bin/python import RPi.GPIO as GPIO import time class HCSR04: def __init__(self, triggerPin, echoPin): GPIO.setmode(GPIO.BCM) self._triggerPin = triggerPin; self._echoPin = echoPin GPIO.setup(self._triggerPin, GPIO.OUT) GPIO.setup(self._echoPin, GPIO.IN) GPIO.output(self._triggerPin, GPIO.LOW) def getRangeInCentimeters(self): # issue a 10uS pulse GPIO.output(self._triggerPin, GPIO.HIGH) time.sleep(0.00001) GPIO.output(self._triggerPin, GPIO.LOW) # wait for the echo while GPIO.input(self._echoPin) == 0: start = time.time() while GPIO.input(self._echoPin) == 1: stop = time.time() return (stop - start) * 1000000.0 / 58.0; def __del__(self): GPIO.cleanup() if __name__ == "__main__": hcsr04 = HCSR04(17, 4) raw_input("waiting to start") while 1: print "range: " + str(hcsr04.getRangeInCentimeters()) time.sleep(1)