ခဏလေး ဒီလိုပဲ စဉ်းစားကြည့်
DHT22 library ရဲ့ read function ကို loop ထဲမှာ ထပ်ခါထပ်ခါ ခေါ်ပြီး (time.sleep ဖြင့် interval ချ), temperature/humidity value ကို print + log file ထဲ append (Linux tutorial ရဲ့ >> redirection concept ကို Python ကနေ implement) ရပါတယ် — sensor read က intermittent error ဖြစ်တတ်တာမို့ (checksum fail) try/except ဖြင့် error handle လုပ်ရပါမယ်, ဒါမှ script က crash မဖြစ်ဘဲ ဆက် run နိုင်ပါလိမ့်မယ်။
လက်တွေ့ scenario နဲ့ ချိတ်ကြည့်မယ်
CSV format ('timestamp,temperature,humidity\n') ဖြင့် log ဖိုင်ကို ရေးထားရင် Part 3 မှာ web dashboard က ဒီ data ကို ဖတ်ပြီး graph ပြသရာမှာ လွယ်ကူပါတယ် — Python ရဲ့ datetime module ဖြင့် timestamp ကို ထည့်ပြီး, open('log.csv', 'a') (append mode) ဖြင့် file ရဲ့ end မှာ line အသစ် ထပ်ဖြည့်ရပါတယ် (Linux tutorial ရဲ့ >> concept ရဲ့ Python version ပါ)။
အတူတူ ကြည့်မယ်
import adafruit_dht
import board
import time
import csv
from datetime import datetime
dht = adafruit_dht.DHT22(board.D4)
with open('temp_log.csv', 'a', newline='') as f:
writer = csv.writer(f)
while True:
try:
temp = dht.temperature
humidity = dht.humidity
timestamp = datetime.now().isoformat()
print(f"{timestamp}: {temp}°C, {humidity}%")
writer.writerow([timestamp, temp, humidity])
f.flush()
except RuntimeError as e:
print(f"Sensor read error: {e}") # DHT sensors fail intermittently — this is normal
time.sleep(5)Terminal ထဲမှာ ၅ စက္ကန့်တစ်ခါ temperature/humidity reading ကို print ထုတ်ပြီး, temp_log.csv ဖိုင်ထဲမှာ history ကို ဆက်ရေးသွားမည်။၅ မိနစ် စမ်းကြည့်
ဒီ script ကို ကိုယ်တိုင် run ကြည့်ပါ (DHT22 sensor ရှိရင်), minute အနည်းငယ် run ထားပြီး temp_log.csv ဖိုင်ထဲက data ကို ပြန်ကြည့်ပါ။
သတိလေးတစ်ချက်
Script ကို Ctrl+C ဖြင့် ရပ်ရင် file ကို properly close လုပ်ပေးရန် with open(...) as f: pattern ကို သုံးထားခြင်းက အရေးကြီးပါတယ် — manual open()/close() သုံးရင် Ctrl+C ဖြတ်ချိန် file ကို မပိတ်ဘဲ ကျန်ခဲ့နိုင်ပါတယ်။