#include<WiFi.h>
#include<PubSubClient.h>
// ---------------------------------------------------------
int LED_PIN = 5; // กำหนดพอร์ตของ LED
int VR = 35; // ขาที่ต่อกับตัวต้านทานปรับค่าได้ Potentiometer
int VR_Value = 0; // ค่าเริ่มต้นของ Potentiometer
const char *ssid = " Wokwi-GUEST "; // ชื่อ ssid wifi
const char *password = " "; // ใส่รหัสไวไฟ
const char *mqtt_broker = " broker.hivemq.com "; // Broker ผู้ให้บริการ
const char *topic1 = " RailTest-001 "; // Topic1
const char *topic2 = " RailTest-002 "; // Topic2
const char mqtt_port = 1883;
WiFiClient espClient;
PubSubClient client(espClient);
// --------------------------------------------------------
void setup()
{
Serial.begin(115200);
WiFi.begin(ssid, password);
pinMode(LED_PIN, OUTPUT); //กำหนด led_pin เป็น output
while(WiFi.status()!= WL_CONNECTED)
{
delay(500);
Serial.println(" Connecting to wifi...");
}
Serial.println(" Connected to the wifi network");
client.setServer(mqtt_broker, mqtt_port);
client.setCallback(Callback);
while(!client.connected())
{
String client_id = " esp32-client- ";
client_id += String(WiFi.macAddress());
Serial.printf(" The client %s connects to mosquitto mqtt broker\n ",
client_id.c_str());
if(client.connect(client_id.c_str()))
{
Serial.println(" Public emqx mqtt broker connected ");
}
else
{
Serial.print(" failed with state ");
Serial.print(client.state());
delay(2000);
}
}
client.publish(topic1, " อุปกรณ์เชื่อมต่อแล้ว ");
client.subscribe(topic1);
client.publish(topic2, " อุปกรณ์เชื่อมต่อแล้ว ");
client.subscribe(topic2);
}
void callback(char *topic, byte *payload, unsigned, unsigned int length)
{
Serial.print(" Message arrived in topic: ");
Serial.println(topic);
Serial.print(" Message ");
// แปลง payload ให้เป็น string
String message = "";
for(int i = 0; i < length; i++)
{
message += (char)payload[i];
}
Serial.println(message);
// ตรวจสอบข้อควรมที่รับมาจาก Topicใด ๆ
if(message == "on")
{
digitalWrite(LED_PIN, HIGH); // เปิด LED
Serial.println(" LED เปิด ");
}
else if(message == " off ")
{
digitalWrite(LED_PIN, LOW); // ปิด LED
Serial.println(" LED ปิด ");
}
}
//----------------------------------------------------------------------
void loop()
{
// put your main code here, to run repeatedly:
client.loop();
VR_Value = analogRead(VR);
client.publish(topic1, String(VR_Value).c_str());
delay(1000); // this speeds up the simulation
}