感測器簡介
DHT12 數位式溫濕度感測器是一款含有己校準數位信號輸出的溫濕度複合型感測器,為 DHT11 的升級產品。它應用專用的數位模組採集技術和半導體溫濕度感測器,確保產品具有較高的可靠性與卓越的長期穩定性。
DHT12 感測器I2C 通信協議
DHT12 支援 I2C 方式進行通訊,完全按照 I2C 標準協議編制,可直接掛在 I2C 匯流排上;感測器SDA 引腳作接I2C 資料匯流排,SCL 接I2C 時鐘匯流排,客戶使用時需給這兩個引腳接一個 1kΩ~10kΩ的上拉電阻。I2C地址為 0xB8(DEV SEL); I2C 通訊速率不能高於 400kHz。
I2C 介面特性
必須嚴格遵照以下通訊規格,否則感測器無法正常工作。
通訊協定:
I2C 通信協議
讀取時序:
I2C 讀取時序圖
參考時序:
參考時序圖
電路圖
程式列表
Python - DHT12.py
"""
MicroPython Aosong DHT12 I2C driver
https://github.com/mcauser/micropython-dht12
MIT License
Copyright (c) 2016 Mike Causer
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
class DHTBaseI2C:
def __init__(self, i2c, addr=0x5c):
self.i2c = i2c
self.addr = addr
self.buf = bytearray(5)
def measure(self):
buf = self.buf
temp = 0x00
self.i2c.send(temp,self.addr) # i2c_error: i2c write fail!input buffer length is not correct !
self.i2c.recv(buf,self.addr) # Ū¨ú5Ó¦r¸`
if ((buf[0] + buf[1] + buf[2] + buf[3]) & 0xff) != buf[4]:
print("checksum error")
print("%x,%x,%x,%x,%x"%(buf[0],buf[1],buf[2],buf[3],buf[4]))
#raise Exception("checksum error")
class DHT12(DHTBaseI2C):
def humidity(self):
return self.buf[0] + self.buf[1] * 0.1
def temperature(self):
t = self.buf[2] + (self.buf[3] & 0x7f) * 0.1
if self.buf[3] & 0x80:
t = -t
return t
Python - ePy-Lite_DHT12.py
from machine import I2C, Pin
from machine import Switch #Get button KEY library
import utime
import dht12
i2c_0 = None
# Start Function
if __name__=="__main__":
KeyA = Switch('keya') #Create button A
# Declaration I2C
i2c_0 = I2C(0,I2C.MASTER,baudrate=10000) #Create I2C0 Master Mode, Baudrate=10kHz
sensor = dht12.DHT12(i2c_0)
print("Start humidity measurement.")
while True:
sensor.measure()
print("Temperature:%.1f"%(sensor.temperature()))
print("Humidity:%.1f"%(sensor.humidity()))
if (KeyA.value()) == True: #Press A Key
break
utime.sleep(1)
i2c_0.deinit()
# KeyA.deinit()
print("Exit humidity measurement.")
執行結果