1. Hardware
- DHT22 / AM2302 Module x 1
- Raspberry Pi 4 x 1
- Female to Female 2.54mm 0.1 in Jumper Wires x 3
2. Circuit diagram
3. Software (การเขียน อ่านค่า DTH22 Module)
3.1 Install Package Adafruit-DHT ด้วย pip3 ด้วยคำสั่ง (ลิงค์การ Install pip3)
sudo pip3 install Adafruit-DHT
3.2 Create Folder "dht22" ด้วยคำสั่ง
sudo mkdir /home/pi/dht22
3.3 Create File Class "DHT22.py" in Folder "dht22" ด้วยคำสั่ง
sudo nano /home/pi/dht22/DHT22.py
ไฟล์ "DHT22.py"
#!/usr/bin/python import Adafruit_DHT as DHT #class for read dht22 class DHT22(object): def __init__(self,out=None, units = "c"): self.sensor = None self.units = units self.out = out self.sensor = DHT.DHT22 def get_value(self): humidity, temp = self.read() temperature = getattr(self, "pass_" + self.units)(temp) return humidity, temperature def read(self): return DHT.read_retry(self.sensor, self.out) def pass_c(self, celsius): return celsius def pass_k(self, celsius): return celsius + 273.15 def pass_f(self, celsius): return celsius * 9.0/5.0 + 32
3.4 Create File Main "main.py" in Folder "dht22" ด้วยคำสั่ง
sudo nano /home/pi/dht22/main.py
ไฟล์ "main.py"
#!/usr/local/bin/python3 # -*- coding: utf-8 -*- import DHT22 as DHT22 import time #GPIO 21 out = 21 #c = celsius #f = Fahrenheit #k = kelvin units = 'c' sensor = DHT22.DHT22(out,units) time.sleep(1) running = True while(running): try: humidity, temperature = sensor.get_value() if humidity is not None and temperature is not None: print ('Temp={0:0.1f}*C Humidity={1:0.1f}%'.format(temperature, humidity)) time.sleep(2) except KeyboardInterrupt: running = False4.ผลลัพธ์
* หมายเหตุ -สามารถสั่ง run python 3 บน raspbian ด้วยคำสั่ง "sudo python3 ชื่อไฟล์.py"
No comments:
Post a Comment