ds18x20.py 1.4 KB

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