#include <WiFi.h>
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"
// Adafruit IO credentials
#define IO_USERNAME "BenSmiling" // Your Adafruit IO username
#define IO_KEY "aio_ZdwN60vmbTT3QaYyHt6VRdxzuB5F" // Your Adafruit IO key
// Wi-Fi credentials
#define WLAN_SSID "Wokwi-GUEST" // Your Wi-Fi SSID
#define WLAN_PASS "" // Your Wi-Fi password
// Create a WiFiClient object for MQTT communication
WiFiClient client;
// Initialize MQTT client using Adafruit IO credentials
Adafruit_MQTT_Client mqtt(&client, "io.adafruit.com", 1883, IO_USERNAME, IO_KEY);
// Subscription feeds (to receive data from Adafruit IO)
Adafruit_MQTT_Subscribe relayStateControl = Adafruit_MQTT_Subscribe(&mqtt, IO_USERNAME "/feeds/RELAY_STATES");
// Publication feeds (to send data to Adafruit IO)
Adafruit_MQTT_Publish nepaStatusFeed = Adafruit_MQTT_Publish(&mqtt, IO_USERNAME "/feeds/NEPA_STATUS");
void setup() {
// Start serial communication for debugging
Serial.begin(115200);
// Connect to Wi-Fi
WiFi.begin(WLAN_SSID, WLAN_PASS); // Connect to Wi-Fi network
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print("."); // Print dots to indicate connection attempt
}
Serial.println("\nWiFi connected"); // Confirm Wi-Fi connection
// Subscribe to the relay state control feeds
mqtt.subscribe(&relayStateControl);
// Connect to Adafruit IO MQTT server
while (!mqtt.connected()) {
Serial.print("Connecting to Adafruit IO...");
if (mqtt.connect()) {
Serial.println("connected!"); // Confirm successful MQTT connection
} else {
Serial.println("failed, retrying...");
delay(5000); // Retry connection every 5 seconds if unsuccessful
}
}
}
void loop() {
// Process MQTT packets and check for any new messages or commands
mqtt.processPackets(1000);
// Get the current time
unsigned long currentMillis = millis();
if (mqtt.connected()) {
String message = "Hi";
if (!nepaStatusFeed.publish(message)) {
Serial.println("Failed to publish Hi"); // Error message
} else {
Serial.println("Published: " + message); // Success message
}
}
// Handle relay state control commands from Adafruit IO feed
if (relayStateControl.lastread != NULL) {
int relayCommand = atoi((char *)relayStateControl.lastread); // Convert command to integer
Serial.print("Received relay command: ");
Serial.println(relayCommand);
}
delay(3000);
}