|
| 1 | +# DS18x20 temperature sensor driver for MicroPython. |
| 2 | +# MIT license; Copyright (c) 2016 Damien P. George |
| 3 | + |
| 4 | +from micropython import const |
| 5 | + |
| 6 | +_CONVERT = const(0x44) |
| 7 | +_RD_SCRATCH = const(0xBE) |
| 8 | +_WR_SCRATCH = const(0x4E) |
| 9 | + |
| 10 | + |
| 11 | +class DS18X20: |
| 12 | + def __init__(self, onewire): |
| 13 | + self.ow = onewire |
| 14 | + self.buf = bytearray(9) |
| 15 | + |
| 16 | + def scan(self): |
| 17 | + return [rom for rom in self.ow.scan() if rom[0] in (0x10, 0x22, 0x28)] |
| 18 | + |
| 19 | + def convert_temp(self): |
| 20 | + self.ow.reset(True) |
| 21 | + self.ow.writebyte(self.ow.SKIP_ROM) |
| 22 | + self.ow.writebyte(_CONVERT) |
| 23 | + |
| 24 | + def read_scratch(self, rom): |
| 25 | + self.ow.reset(True) |
| 26 | + self.ow.select_rom(rom) |
| 27 | + self.ow.writebyte(_RD_SCRATCH) |
| 28 | + self.ow.readinto(self.buf) |
| 29 | + if self.ow.crc8(self.buf): |
| 30 | + raise Exception("CRC error") |
| 31 | + return self.buf |
| 32 | + |
| 33 | + def write_scratch(self, rom, buf): |
| 34 | + self.ow.reset(True) |
| 35 | + self.ow.select_rom(rom) |
| 36 | + self.ow.writebyte(_WR_SCRATCH) |
| 37 | + self.ow.write(buf) |
| 38 | + |
| 39 | + def read_temp(self, rom): |
| 40 | + buf = self.read_scratch(rom) |
| 41 | + if rom[0] == 0x10: |
| 42 | + if buf[1]: |
| 43 | + t = buf[0] >> 1 | 0x80 |
| 44 | + t = -((~t + 1) & 0xFF) |
| 45 | + else: |
| 46 | + t = buf[0] >> 1 |
| 47 | + return t - 0.25 + (buf[7] - buf[6]) / buf[7] |
| 48 | + else: |
| 49 | + t = buf[1] << 8 | buf[0] |
| 50 | + if t & 0x8000: # sign bit set |
| 51 | + t = -((t ^ 0xFFFF) + 1) |
| 52 | + return t / 16 |
0 commit comments