#include <WiFi.h>
#include <PubSubClient.h>
int sw1 = 12;int sw2 = 13;int pot = 34;
const char *ssid = "Wokwi-GUEST";
const char *password = "";
const char *mqtt_broker = "broker.hivemq.com";
const char *topic = "Testpun";
const int mqtt_port = 1883;
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
Serial.begin(115200);
pinMode(sw1, INPUT_PULLUP);
pinMode(sw2, INPUT_PULLUP);
pinMode(pot, INPUT);
WiFi.begin(ssid, password);
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 = "esp8266-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(topic, "อุปกรณ์เชื่อมต่อเเล้ว");
client.subscribe(topic);
}
void callback(char *topic, byte *payload, unsigned int length) {
Serial.print("Message arrived in topic: ");
Serial.println(topic);
Serial.print("Message:");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
Serial.println(" - - - - - - - - - - - -");
}
void loop() {
client.loop();
delay(200);
int x = digitalRead(sw1);
int y = digitalRead(sw2);
Serial.println(x);
Serial.println(y);
Serial.println();
int VR_Value = analogRead(pot);
client.publish(topic, String(VR_Value).c_str());
delay(1000);
if (x == 1) {
client.publish(topic, "HELLO");
}
if (y == 1) {
client.publish(topic, "JUPITER");
}}