You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
40 lines
972 B
40 lines
972 B
from machine import Pin
|
|
|
|
SENSOR_READ_PERIOD = const(1)
|
|
|
|
import onewire, ds18x20, time
|
|
|
|
class Sensor:
|
|
last_read_time: int
|
|
last_result: int
|
|
|
|
sensor: ds18x20.DS18X20
|
|
rom: Any
|
|
|
|
def __init__(self, sensor_data_pin: Pin) -> None:
|
|
self.last_read_time = time.time()
|
|
self.last_result = 28
|
|
self.sensor = ds18x20.DS18X20(onewire.OneWire(sensor_data_pin))
|
|
roms = self.sensor.scan()
|
|
assert len(roms) == 1, "Not (only) one sensor on the bus"
|
|
self.rom = roms[0]
|
|
|
|
def __should_read_data(self) -> bool:
|
|
return (time.time() - self.last_read_time) > SENSOR_READ_PERIOD
|
|
|
|
def read(self) -> int:
|
|
if not self.__should_read_data():
|
|
return self.last_result
|
|
|
|
sensor = self.sensor
|
|
|
|
try:
|
|
sensor.convert_temp()
|
|
result = sensor.read_temp(self.rom)
|
|
self.last_result = result
|
|
self.last_read_time = time.time()
|
|
except OSError as e:
|
|
print("err reading sensor", e)
|
|
return self.last_result
|
|
|
|
return result
|
|
|