Skip to content

Commit a336c29

Browse files
committed
micropython/drivers: Move "dx18x20" sensor driver from main repo.
Signed-off-by: Jim Mussared <[email protected]>
1 parent 0382c9c commit a336c29

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
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
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
require("onewire")
2+
module("ds18x20.py", opt=3)

0 commit comments

Comments
 (0)