2016-08-29 03:12:49 +01:00
|
|
|
# DS18x20 temperature sensor driver for MicroPython.
|
|
|
|
# MIT license; Copyright (c) 2016 Damien P. George
|
|
|
|
|
2016-11-03 01:41:11 +00:00
|
|
|
from micropython import const
|
|
|
|
|
2016-08-29 03:12:49 +01:00
|
|
|
_CONVERT = const(0x44)
|
|
|
|
_RD_SCRATCH = const(0xbe)
|
|
|
|
_WR_SCRATCH = const(0x4e)
|
|
|
|
|
|
|
|
class DS18X20:
|
|
|
|
def __init__(self, onewire):
|
|
|
|
self.ow = onewire
|
2016-08-29 03:27:21 +01:00
|
|
|
self.buf = bytearray(9)
|
2016-08-29 03:12:49 +01:00
|
|
|
|
|
|
|
def scan(self):
|
2016-08-29 03:45:07 +01:00
|
|
|
return [rom for rom in self.ow.scan() if rom[0] == 0x10 or rom[0] == 0x28]
|
2016-08-29 03:12:49 +01:00
|
|
|
|
|
|
|
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)
|
2016-08-29 03:27:21 +01:00
|
|
|
self.ow.readinto(self.buf)
|
|
|
|
if self.ow.crc8(self.buf):
|
2016-08-29 03:12:49 +01:00
|
|
|
raise Exception('CRC error')
|
2016-08-29 03:27:21 +01:00
|
|
|
return self.buf
|
2016-08-29 03:12:49 +01:00
|
|
|
|
|
|
|
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)
|
2016-08-29 03:45:07 +01:00
|
|
|
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:
|
2016-10-31 09:54:44 +00:00
|
|
|
t = buf[1] << 8 | buf[0]
|
|
|
|
if t & 0x8000: # sign bit set
|
|
|
|
t = -((t ^ 0xffff) + 1)
|
|
|
|
return t / 16
|