# A01NYUB Waterproof Ultrasonic Sensor - Micropython?

**URL:** <https://forum.core-electronics.com.au/t/a01nyub-waterproof-ultrasonic-sensor-micropython/15263>\
**Category:** Uncategorized\
**Created:** [3 October 2022 23:40 UTC](https://forum.core-electronics.com.au/t/a01nyub-waterproof-ultrasonic-sensor-micropython/15263 "2022-10-03T23:40:02Z")\
**Posts on this page:** 1\
**Showing post:** 6

<div class="post-metadata">

**Author:** ![James](https://yyz2.discourse-cdn.com/flex028/user_avatar/forum.core-electronics.com.au/james/32/4400_2.png) [@James](https://forum.core-electronics.com.au/u/James)\
**Post date:** [20 October 2022 04:59 UTC](https://forum.core-electronics.com.au/t/a01nyub-waterproof-ultrasonic-sensor-micropython/15263/6 "2022-10-20T04:59:32Z")

</div>

Hi Jon,

I wrote up a bit of code for this, give it a go:

```auto
# 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](https://docs.micropython.org/en/latest/library/machine.UART.html#machine-uart) 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

---

_[View the full topic](https://forum.core-electronics.com.au/t/a01nyub-waterproof-ultrasonic-sensor-micropython/15263)._
