18B20驱动
DS18B20是一款非常强大的测温芯片,其体积小、精度高、硬件开销低、抗干扰能力强。引脚示意图如下:
通讯指令表:
Micropython源码已经实现了18B20的驱动,源码地址为/micropython/drivers/onewire/
驱动程序文件为ds18x20.py、onewire.py。
ds18x20.py代码片段:
#ds18x20.py
from onewire import OneWire
class DS18X20(object):
def read_temp(self, rom=None):
"""
Read and return the temperature of one DS18x20 device.
Pass the 8-byte bytes object with the ROM of the specific device you want to read.
If only one DS18x20 device is attached to the bus you may omit the rom parameter.
"""
rom = rom or self.roms[0]
ow = self.ow
ow.reset()
ow.select_rom(rom)
ow.write_byte(0x44) # Convert Temp
while True:
if ow.read_bit():
break
ow.reset()
ow.select_rom(rom)
ow.write_byte(0xbe) # Read scratch
data = ow.read_bytes(9)
return self.convert_temp(rom[0], data)
DS18B20芯片启动之后进入低功耗等待状态,当MCU发起[44H]指令时,D18B20执行温度测量以及AD转换并将转换后的温度数据以2字节的形式存储在暂存器的温度寄存器中。MCU继续发起[BEH]指令从寄存器中读取温度值。
定时器
TPYBoard有14个定时器,编号 1-14,其中3号定时器保留内部使用,5、6号分别用于伺服系统和ADC/DAC控制。
创建定时器:
>>> tim1 = pyb.Timer(1)
初始化定时器:
>>> tim1.init(freq=1/5)
定义回调:
>>> tim1.callback(lambda t:pyb.LED(1).toggle())
查看定时器的最高频率:
>>> pyb.Timer(1).source_freq()
168000000
>>> pyb.Timer(5).source_freq()
84000000
168000000
>>> pyb.Timer(5).source_freq()
84000000
可以看到定时器1和5的最高频率不一样,实际上,2-7、12-14号定时器的最高频率为84MHz,1、8-11为168MHz。
查看tim1:
>>> tim1
Timer(1, freq=0, prescaler=31249, period=26879, mode=UP, div=1, deadtime=0)
可以看到频率值为168000000/(prescaler+1)/(period+1) = 0.2,即延时5秒。
Timer(1, freq=0, prescaler=31249, period=26879, mode=UP, div=1, deadtime=0)
主程序
主程序功能是每隔5秒显示一次环境温度值,代码如下:
import pyb
from pyb import Pin
from ds18x20 import DS18X20
from pyb import Timer
import micropython
micropython.alloc_emergency_exception_buf(100)
tempValue = 0
print('pin init')
Pin('Y11',Pin.OUT_PP).low() #GND
Pin('Y9',Pin.OUT_PP).high() #VCC
def displayTemp(t):
print('Current Temperature:')
print(tempValue)
tim1 = Timer(1)
tim1.callback(displayTemp)
tim1.init(freq=1/5)
if __name__=='__main__':
DQ=DS18X20(Pin('Y10')) #DQ
while True:
tempValue = DQ.read_temp()
运行效果:
源码地址:https://github.com/IOT-er/MicroPython-Display-Temperature