import machine
import dht
import time
import network
from umqtt.simple import MQTTClient
# --- การตั้งค่าพื้นฐาน ---
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASS = ""
MQTT_BROKER = "broker.hivemq.com"
MQTT_PORT = 1883
CLIENT_ID = "ESP32_Control_System_99"
# กำหนดขา Pin (ตามรูปวงจรของคุณ)
RELAY_PIN = 13
LED_PIN = 15
DHT_PIN = 19
# เริ่มต้นการทำงานของ Hardware
relay = machine.Pin(RELAY_PIN, machine.Pin.OUT)
led = machine.Pin(LED_PIN, machine.Pin.OUT)
sensor = dht.DHT22(machine.Pin(DHT_PIN))
# --- ฟังก์ชันเชื่อมต่อ WiFi ---
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print('กำลังเชื่อมต่อ WiFi...')
wlan.connect(WIFI_SSID, WIFI_PASS)
while not wlan.isconnected():
time.sleep(0.5)
print('เชื่อมต่อ WiFi สำเร็จ:', wlan.ifconfig())
# --- ฟังก์ชันเมื่อได้รับข้อความจาก MQTT (Control Relay) ---
def sub_cb(topic, msg):
command = msg.decode('utf-8').upper()
print("คำสั่งที่ได้รับ: ", command)
if command == "ON":
relay.value(1)
led.value(1)
print("สถานะ: เปิดอุปกรณ์")
elif command == "OFF":
relay.value(0)
led.value(0)
print("สถานะ: ปิดอุปกรณ์")
# --- เริ่มการทำงาน ---
connect_wifi()
client = MQTTClient(CLIENT_ID, MQTT_BROKER, port=MQTT_PORT)
client.set_callback(sub_cb)
client.connect()
client.subscribe("home/office/control") # Topic สำหรับรับคำสั่ง On/Off
print("เชื่อมต่อ HiveMQ สำเร็จ!")
last_sensor_read = 0
while True:
try:
# ตรวจสอบว่ามีข้อความสั่งการ (On/Off) เข้ามาหรือไม่
client.check_msg()
# อ่านค่าเซนเซอร์ทุกๆ 5 วินาที
if (time.time() - last_sensor_read) > 5:
sensor.measure()
temp = sensor.temperature()
hum = sensor.humidity()
# ส่งค่าไปยัง HiveMQ Dashboard
client.publish("home/office/temp", str(temp))
client.publish("home/office/hum", str(hum))
print("อุณหภูมิ: {}°C, ความชื้น: {}%".format(temp, hum))
# ระบบ Auto (ตัวอย่าง: ร้อนเกินไปให้เปิดพัดลม)
if temp > 30:
relay.value(1)
led.value(1)
last_sensor_read = time.time()
except Exception as e:
print("Error:", e)
# กรณีหลุด ให้พยายามเชื่อมต่อใหม่
time.sleep(5)
machine.reset()DHT22 PIN 19
LED PIN 15
RELAY PIN 13