]> vault307.fbx.one Git - SensorLib.git/blob - us100.py
sensors
[SensorLib.git] / us100.py
1 import utime
2
3 class US100UART:
4 """Read the US-100 sonar sensor in UART mode."""
5
6 def __init__(self, uart):
7 self.uart = uart
8 uart.init(baudrate=9600, bits=8, parity=None, stop=1)
9 utime.sleep_ms(100)
10 self.buf = bytearray(2)
11 self.t = 0
12
13 def distance(self):
14 """Read the temperature compensated distance im millimeters."""
15 self.buf[0] = 0
16 self.buf[1] = 0
17 self.uart.write(b'\x55')
18 self.t = utime.ticks_ms()
19 while not self.uart.any():
20 if utime.ticks_diff(utime.ticks_ms(), self.t) > 100:
21 raise Exception('Timeout while reading from US100 sensor!')
22 utime.sleep_us(100)
23 self.uart.readinto(self.buf, 2)
24 return (self.buf[0] * 256) + self.buf[1]
25
26 def temperature(self):
27 """Read the temperature in degree celcius."""
28 self.buf[0] = 0
29 self.uart.write(b'\x50')
30 self.t = utime.ticks_ms()
31 while not self.uart.any():
32 if utime.ticks_diff(utime.ticks_ms(), self.t) > 100:
33 raise Exception('Timeout while reading from US100 sensor!')
34 utime.sleep_us(100)
35 self.uart.readinto(self.buf, 1)
36 return self.buf[0] - 45