#include WiFi.h #include PubSubClient.h const char* ssid = "YourSSID"; const char* password = "YourPassword"; const char* mqtt_server = "broker.emqx.io"; const char* topic = "week13/wifi"; // Topic const int switchPin = D2; // Switch Pin WiFiClient espClient; PubSubClient client(espClient); int lastSwitchState = HIGH; // Previous switch state void setup() { Serial.begin(115200); pinMode(switchPin, INPUT_PULLUP); setup_wifi(); client.setServer(mqtt_server, 1883); } void setup_wifi() { delay(10); Serial.println(); Serial.print("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected"); Serial.println("IP Address: "); Serial.println(WiFi.localIP()); } void reconnect() { while (!client.connected()) { Serial.print("Connecting to MQTT server..."); if (client.connect("switchClient")) { Serial.println("Connected"); } else { Serial.print("failed, rc="); Serial.print(client.state()); Serial.println(" trying again in 5 seconds"); delay(5000); } } } void loop() { if (!client.connected()) { reconnect(); } client.loop(); int switchState = digitalRead(switchPin); if (switchState != lastSwitchState) { // If there's a change in switch state if (switchState == LOW) { client.publish(topic, "a"); Serial.println("Switch pressed"); } else { client.publish(topic, "b"); Serial.println("Switch released"); } lastSwitchState = switchState; } delay(100); // Small delay to avoid switch bounce }