1
$\begingroup$

On my Bit:Bot from 4Tronix ([see here])1

I have an HC-SR04 ultrasound sensor attached. It uses solely pin15, for both trig and echo. I am able to use Microsoft MakeCode 'block editor' to get a reading (see attachment) but am unable to find a working solution for MicroPython.

The closest I've found is this one on GitHub (below), but I just keep getting error message of '-11' scrolling across the Microbit's LED Matrix. I've checked for error code -11 but nothing exists.

from microbit import *
class HCSR04:

def __init__(self, tpin=pin15, epin=pin15, spin=pin13):
    self.trigger_pin = tpin
    self.echo_pin = epin
    self.sclk_pin = spin

def distance_mm(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:
            i = -1
    dist= -1 if i < 0 else round((pre + (k - i) * 8. + post) * 8 * 0.172)
    return dist

    sonar = HCSR04()
    while True:
        test = sonar.distance_mm()
        display.scroll(str(test))
        sleep(1000)

Please help if you can.

Thanks

$\endgroup$

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Browse other questions tagged or ask your own question.