因为busio只有基本功能,还无法直接读写传感器,因此还需要自己编写子程序。下面是一个简化版本的DS18X20程序,只能读取一个传感器(没有进行ROM搜索)。
from time import sleep
from busio import OneWire
from microcontroller import pin
onewire = OneWire(pin.PA07)
onewire.reset()
def ow_writebyte(ow, dat):
for i in range(8):
ow.write_bit(dat % 2 == 1)
dat >>= 1
def ow_readbyte(ow):
d = 0
for i in range(8):
d >>= 1
if ow.read_bit():
d |= 0x80
return d
def DS18X20Lite(ow):
ow.reset()
ow_writebyte(ow, 0xCC)
ow_writebyte(ow, 0x44)
ow.reset()
ow_writebyte(ow, 0xCC)
ow_writebyte(ow, 0xBE)
d1 = ow_readbyte(ow)
d2 = ow_readbyte(ow)
t = d1 | d2 << 8
if t & 0x8000:
t = -((t ^ 0xffff) + 1)
return t / 16
while 1:
sleep(1)
DS18X20Lite(onewire)
|