Micropython加速物联网开发5 - 定时刷新环境温度

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
可以看到定时器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秒。

主程序

主程序功能是每隔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





  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值