Hi Jon,
I wrote up a bit of code for this, give it a go:
# Import all of the modules that we need
from machine import Pin, UART
from utime import sleep_ms
# Create an LED object that we can turn on and off
led = machine.Pin("LED",machine.Pin.OUT)
avg_pin = machine.Pin(2, machine.Pin.OUT, value=1) # tell sensor to average data in hardware by driving RX pin on sensor high
# Initialise UART
uart = UART(0, 9600)
uart.init(bits=8, parity=None, stop=1) # Defaults from DFrobot wiki page: https://wiki.dfrobot.com/A01NYUB%20Waterproof%20Ultrasonic%20Sensor%20SKU:%20SEN0313
def read_distance():
uart.read() # clear buffer (could contain many measurements)
while (uart.any() == 0): # wait for the sensor to send a packet
pass # pass and check again if you didn't get one
data_buff = uart.read(4) # read the 4 bytes it sent
checksum = (data_buff[0] + data_buff[1] + data_buff[2]) & 0xFF # checksum seems to be header + data H + data L, masked to a single byte
if (checksum == data_buff[3]):
measurement = ((data_buff[1] << 8) + data_buff[2]) # shift data H left 8 bits, and add with data low
if measurement == 250:
return(-1) # return -1 if "250" (invalid measurement) is recieved, consider adding 0 too, as it's usually not accurate
else:
return(measurement)
else:
return(-2) # if checksum fails (normally because minimum range has been exceeded, return -1)
while True:
print(str(read_distance()) + " mm") # convert to string (int can't concatenate) and append mm
This works on the bench for me, though you’ll have to do some work on your side to get WiFi working at the same time. Could be worth setting up serial receive as an interrupt that interrupts the loop used to send/serve data.
Let me know if you need anything explained, your understanding of everything is more important to me than having it “just work”
-James