From a336c29cc5d9117bc56059c7f9dc13008fa9af4c Mon Sep 17 00:00:00 2001 From: Jim Mussared Date: Tue, 6 Sep 2022 13:20:26 +1000 Subject: [PATCH] micropython/drivers: Move "dx18x20" sensor driver from main repo. Signed-off-by: Jim Mussared --- micropython/drivers/sensor/ds18x20/ds18x20.py | 52 +++++++++++++++++++ .../drivers/sensor/ds18x20/manifest.py | 2 + 2 files changed, 54 insertions(+) create mode 100644 micropython/drivers/sensor/ds18x20/ds18x20.py create mode 100644 micropython/drivers/sensor/ds18x20/manifest.py diff --git a/micropython/drivers/sensor/ds18x20/ds18x20.py b/micropython/drivers/sensor/ds18x20/ds18x20.py new file mode 100644 index 00000000..ad2d9f52 --- /dev/null +++ b/micropython/drivers/sensor/ds18x20/ds18x20.py @@ -0,0 +1,52 @@ +# DS18x20 temperature sensor driver for MicroPython. +# MIT license; Copyright (c) 2016 Damien P. George + +from micropython import const + +_CONVERT = const(0x44) +_RD_SCRATCH = const(0xBE) +_WR_SCRATCH = const(0x4E) + + +class DS18X20: + def __init__(self, onewire): + self.ow = onewire + self.buf = bytearray(9) + + def scan(self): + return [rom for rom in self.ow.scan() if rom[0] in (0x10, 0x22, 0x28)] + + def convert_temp(self): + self.ow.reset(True) + self.ow.writebyte(self.ow.SKIP_ROM) + self.ow.writebyte(_CONVERT) + + def read_scratch(self, rom): + self.ow.reset(True) + self.ow.select_rom(rom) + self.ow.writebyte(_RD_SCRATCH) + self.ow.readinto(self.buf) + if self.ow.crc8(self.buf): + raise Exception("CRC error") + return self.buf + + def write_scratch(self, rom, buf): + self.ow.reset(True) + self.ow.select_rom(rom) + self.ow.writebyte(_WR_SCRATCH) + self.ow.write(buf) + + def read_temp(self, rom): + buf = self.read_scratch(rom) + if rom[0] == 0x10: + if buf[1]: + t = buf[0] >> 1 | 0x80 + t = -((~t + 1) & 0xFF) + else: + t = buf[0] >> 1 + return t - 0.25 + (buf[7] - buf[6]) / buf[7] + else: + t = buf[1] << 8 | buf[0] + if t & 0x8000: # sign bit set + t = -((t ^ 0xFFFF) + 1) + return t / 16 diff --git a/micropython/drivers/sensor/ds18x20/manifest.py b/micropython/drivers/sensor/ds18x20/manifest.py new file mode 100644 index 00000000..01f7ae03 --- /dev/null +++ b/micropython/drivers/sensor/ds18x20/manifest.py @@ -0,0 +1,2 @@ +require("onewire") +module("ds18x20.py", opt=3)