Skip to content

测量温度

18B20

DS18B20 是美国 DALLAS 半导体公司推出的第一片支持“一线总线”接口的温度传感器,它具有微型化,低功耗,高性能,抗干扰能力强,易配微处理器等优点,可直接将温度转化成数字信号处理器处理。

测量的温度范围是 -55~125℃,测温误差 0.5℃。可编程分辨率 9~12 位,对应的可分辨温度分别为 0.5℃,0.25℃,0.125℃ 和 0.0625℃。

MicroPython有现成的API:http://docs.micropython.org/en/latest/esp32/quickref.html#onewire-driver

python
from machine import Pin
import onewire, ds18x20
import time

ow = onewire.OneWire(Pin(4))  # create a OneWire bus on GPIO04
ds = ds18x20.DS18X20(ow)


def read_temp():
    roms = ds.scan()
    ds.convert_temp()
    time.sleep_ms(750)
    for rom in roms:
        print(ds.read_temp(rom))


while True:
    read_temp()
    time.sleep(1)

DTH

扫描温度传感器的 ROM

python
from machine import Pin, I2C
from ds18x20 import DS18X20
from onewire import OneWire

import time

i2c = I2C(1, freq=400_000, scl=22, sda=21)

ds = DS18X20(OneWire(Pin(33)))


def ds18b20_read_rom():
    """需要先扫描 rom 口"""
    rom = ds.scan()
    for i in range(len(rom)):
        print("rom%d = %s" % (i, rom[i]))


def main():
    ds18b20_read_rom()
    while True:
        pass

读取温度数据

python
from machine import Pin, I2C
from ds18x20 import DS18X20
from onewire import OneWire
import time

i2c = I2C(1, freq=400_000, scl=22, sda=21)

ds = DS18X20(OneWire(Pin(33)))

rom0 = bytearray(b'(2\x83b\x00\x00\x00\x8f')


def ds18b20_read_rom():
    rom = ds.scan()

    for i in range(len(rom)):
        print("rom%d = %s" % (i, rom[i]))


def ds18b20_temp(x, y, rom):
    ds.convert_temp()
    time.sleep_ms(750)

    try:
        temp = ds.read_temp(rom)
        print("%.2f" % (temp))

    except:

        print("error!")


def main():
    ds18b20_read_rom()

    while True:
        ds18b20_temp(9, 0, rom0)
        # ds18b20_temp(9,1,rom1)
        pass