MicroPython DHT22 Temperature and Humidity Sensor

Sittipong Jansorn
Jul 21, 2017 · 2 min read

ใน MicroPython จะมี buildin sensor driver มาให้เราพร้อมใช้งานแล้วอยู่สองอย่างคือ DS18x20 กับ DHTxx ซึ่งทั้งสองอันนี้เราสามารถเรียกใช้งานได้เลยโดยที่ไม่ต้องทำอะไรเพิ่มเติม สำหรับ DHTxx นั้นจะมี module ที่เข้ามาเกี่ยวข้องอยู่ 2 อันคือ ซึ่งทั้งสองจะอยู่ใน package dht

DHT11
DHT22

ก่อนที่เราจะใช้งาน DHT22 ต้องทำการ import package dhtเข้ามาก่อน

import dht

กำหนด Pin ที่ใช้ในการติดต่อกับ DHT22

from machine import Pin

สร้าง object Pin โดยใช้ GPIO5

pinDht = Pin(5)

สร้าง object DHT22

d = dht.DHT22(pinDht)

เรียก function measure() เพื่ออ่านค่า temperature กับ humidity

d.measure()

measure

แสดงค่า Temperature

d.temperature()

temperature

แสดงค่า Humidity

d.humidity()

humidity

ทุกครั้งที่จะแสดงผลค่า temperature กับ humidity เราต้องเรียก function measure เพื่อให้อ่านค่าจาก sensor ใหม่

ทดสอบรัน code แบบ loop

code loop

อธิบายเพิ่มเติม

print(‘Temp: {0:.2f}, Humi: {1:.2f}’.format(d.temperature(), d.humidity()))

เรียกใช้งาน function print และทำการสร้าง object string ในรูปแบบของการใช้งาน string format

{0:.2f} ให้แสดงผลทศนิยม 2 ตำแหน่ง ตามลำดับ argument index 0
{1:.2f} ให้แสดงผลทศนิยม 2 ตำแหน่ง ตามลำดับ argument index 1

)

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade