Skip to content

Instantly share code, notes, and snippets.

@fizban99
Created March 16, 2017 21:45
Show Gist options
  • Save fizban99/974f5f4633ce45392ed8c30941c474ce to your computer and use it in GitHub Desktop.
Save fizban99/974f5f4633ce45392ed8c30941c474ce to your computer and use it in GitHub Desktop.
micro:bit micropython library for the HC-SR04 ultrasonic sensor
from microbit import spi
from microbit import pin13, pin14, pin15
class HCSR04:
def __init__(self, tpin=pin15, epin=pin14, spin=pin13):
self.trigger_pin = tpin
self.echo_pin = epin
self.sclk_pin = spin
def distance_cm(self):
spi.init(baudrate=125000, sclk=self.sclk_pin,
mosi=self.trigger_pin, miso=self.echo_pin)
pre = 0
post = 0
k = -1
length = 500
resp = bytearray(length)
resp[0] = 0xFF
spi.write_readinto(resp, resp)
# find first non zero value
try:
i, value = next((ind, v) for ind, v in enumerate(resp) if v)
except StopIteration:
i = -1
if i > 0:
pre = bin(value).count("1")
# find first non full high value afterwards
try:
k, value = next((ind, v)
for ind, v in enumerate(resp[i:length - 2]) if resp[i + ind + 1] == 0)
post = bin(value).count("1") if k else 0
k = k + i
except StopIteration:
k = -1
if i < 0 or k < 0:
return -1
else:
return round((pre + (k - i) * 8. + post) * 8 * 0.0172, 1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment