MicroPython ESP32 读取DS18B20温度数据
-
DS18B20
-
接线图
-
本示例基于
Thonny
平台开发
引入的模块
from ds18x20 import DS18X20
import time, onewire
from machine import Pin
示例代码
DS18B20接在ESP32 的22号引脚上
from ds18x20 import DS18X20
import time, onewire
from machine import Pin
OneWirePin = 22
def readDS18x20():
# the device is on GPIO22
dat = Pin(OneWirePin)
# create the onewire object
ds = DS18X20(onewire.OneWire(dat))
# scan for devices on the bus
roms = ds.scan()# 扫描挂载在单总线上的ds18B20设备
ds.convert_temp() # 数据转换
time.sleep_ms(750)
values = []
for rom in roms:
values.append(ds.read_temp(rom))
# values.append(u"℃")
print(values,r"℃")
return values
while True:
readDS18x20()
time.sleep(5)
示例二
from ds18x20 import DS18X20
import machine,onewire,time
def read_temp():
# the device is on GPIO22
dat = machine.Pin(22)
# create the onewire object
ds = DS18X20(onewire.OneWire(dat))
# scan for devices on the bus
roms = ds.scan()
# print('found devices:', roms)
print('temperature:', end=' ')
ds.convert_temp()
time.sleep_ms(750)
temp = ds.read_temp(roms[0])
print(temp,end='℃\n ')
return temp
while True:
read_temp()
time.sleep(3)
- Shell调试窗口输出
示例三
读取单总线上的温度传感器10次温度数据,取平均值。注意这里的10次温度数据并不一定指来自一个温度传感器的数据,可能是挂载在单总线上多个温度传感器的数据。
from ds18x20 import DS18X20
from onewire import OneWire
from machine import Pin
import time
def status():
dat = OneWire(Pin(22))
ds = DS18X20(dat)
roms = ds.scan()
if not len(roms):
print("Nao encontrei um dispositivo onewire.")
return None
ds.convert_temp()
time.sleep_ms(750)
temp = 0
for i in range(10):
for rom in roms:
temp += ds.read_temp(rom)
return temp / 10
while True:
print(status(),end='℃\n ')
time.sleep(3)
- Shell调试窗口输出