/ DYP_ultrasonics / me007ys.py
me007ys.py
1 # SPDX-FileCopyrightText: 2020 Limor Fried for Adafruit Industries 2 # 3 # SPDX-License-Identifier: MIT 4 5 import time 6 import serial 7 8 SERIAL_PORT = "/dev/ttyS15" # or "COM4" or whatever 9 10 serialport = serial.Serial(SERIAL_PORT, 9600) 11 12 13 def read_me007ys(ser, timeout = 1.0): 14 ts = time.monotonic() 15 buf = bytearray(3) 16 idx = 0 17 18 while True: 19 # Option 1, we time out while waiting to get valid data 20 if time.monotonic() - ts > timeout: 21 raise RuntimeError("Timed out waiting for data") 22 23 c = ser.read(1)[0] 24 #print(c) 25 if idx == 0 and c == 0xFF: 26 buf[0] = c 27 idx = idx + 1 28 elif 0 < idx < 3: 29 buf[idx] = c 30 idx = idx + 1 31 else: 32 chksum = sum(buf) & 0xFF 33 if chksum == c: 34 return (buf[1] << 8) + buf[2] 35 idx = 0 36 return None 37 38 while True: 39 dist = read_me007ys(serialport) 40 print("Distance = %d mm" % dist)