import network
import time
import machine # เรียกใช้โมดูล machine สำหรับคำสั่ง reset
from machine import Pin, I2C
import ssd1306
import dht
# 1. ตั้งค่า Pin สำหรับหลอด LED (GP18)
led = Pin(18, Pin.OUT)
led.value(0)
# 2. ตั้งค่า I2C สำหรับจอ OLED (SDA=GP16, SCL=GP17)
i2c = I2C(0, sda=Pin(16), scl=Pin(17))
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
# 3. ตั้งค่าเซ็นเซอร์ DHT22 ที่ขา GP20
sensor = dht.DHT22(Pin(20))
# 4. ตั้งค่าปุ่มกดทั้ง 3 ตัว (ตั้งเป็นแบบ Input)
sw_yellow = Pin(27, Pin.IN)
sw_red = Pin(22, Pin.IN) # ปุ่มสำหรับรีเซ็ต
sw_green = Pin(28, Pin.IN)
# --- ฟังก์ชันการทำงานเมื่อกดปุ่ม (Interrupt Handlers) ---
def reset_board(pin):
print("\n[System] ปุ่มสีแดงถูกกด -> กำลังรีเซ็ตการทำงานของบอร์ด...")
machine.reset() # คำสั่งรีสตาร์ทบอร์ด
def yellow_pressed(pin):
print("ปุ่มสีเหลือง (GP21) ถูกกด!")
def green_pressed(pin):
print("ปุ่มสีเขียว (GP26) ถูกกด!")
# ตั้งค่า Interrupt ให้ทำงานเมื่อมีการกดปุ่ม (IRQ_RISING คือตรวจจับจังหวะที่มีไฟเข้า)
sw_red.irq(trigger=Pin.IRQ_RISING, handler=reset_board)
sw_yellow.irq(trigger=Pin.IRQ_RISING, handler=yellow_pressed)
sw_green.irq(trigger=Pin.IRQ_RISING, handler=green_pressed)
# ---------------------------------------------------
# ข้อมูล Wi-Fi ของระบบจำลอง Wokwi
ssid = "Wokwi-GUEST"
password = ""
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)
oled.fill(0)
oled.text("Connecting to", 0, 0)
oled.text("WiFi...", 0, 15)
oled.show()
print("กำลังเชื่อมต่อ Wi-Fi...")
while not wlan.isconnected():
led.value(0)
time.sleep(0.5)
ip_address = wlan.ifconfig()[0]
print("เชื่อมต่อสำเร็จ! IP:", ip_address)
led.value(1) # LED ติดค้างเมื่อเชื่อมต่อสำเร็จ
return ip_address
# เริ่มทำงาน
ip = connect_wifi()
# ลูปการทำงานหลัก (แสดงผล DHT22)
while True:
try:
sensor.measure()
temp = sensor.temperature()
hum = sensor.humidity()
oled.fill(0)
oled.text("WiFi Connected", 0, 0)
oled.text(ip, 0, 12)
oled.text("Temp: {:.1f} C".format(temp), 0, 30)
oled.text("Hum: {:.1f} %".format(hum), 0, 45)
oled.show()
print("Temp: {:.1f} C, Hum: {:.1f} %".format(temp, hum))
except OSError as e:
print("ไม่สามารถอ่านค่าจากเซ็นเซอร์ได้")
# หน่วงเวลา 2 วินาที (หากกดปุ่มในช่วงเวลานี้ Interrupt จะแทรกการทำงานทันที)
time.sleep(2)