#include <WiFi.h> #include "Adafruit_MQTT.h" #include "Adafruit_MQTT_Client.h" #define WLAN_SSID "Your_WiFi_SSID" #define WLAN_PASS "Your_WiFi_Password" #define AIO_SERVER "io.adafruit.com" #define AIO_SERVERPORT 1883 #define AIO_USERNAME "Your_AdafruitIO_Username" #define AIO_KEY "Your_AdafruitIO_Key" WiFiClient client; Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY); Adafruit_MQTT_Publish data = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/your_feed_name"); // Change "your_feed_name" to your Adafruit IO feed name void connectWiFi() { WiFi.begin(WLAN_SSID, WLAN_PASS); while (WiFi.status() != WL_CONNECTED) { delay(1000); Serial.println("Connecting to WiFi..."); } Serial.println("Connected to WiFi"); } void MQTT_connect() { int8_t ret; if (mqtt.connected()) { return; } Serial.print("Connecting to Adafruit IO... "); while ((ret = mqtt.connect()) != 0) { Serial.println(mqtt.connectErrorString(ret)); Serial.println("Retrying MQTT connection in 5 seconds..."); mqtt.disconnect(); delay(5000); } Serial.println("MQTT Connected!"); } void setup() { Serial.begin(115200); delay(100); connectWiFi(); } void loop() { MQTT_connect(); // Your logic to obtain sensor data or any variable float yourData = 25.5; // Replace this with your actual data source Serial.print("Sending data: "); Serial.println(yourData); if (!data.publish(yourData)) { Serial.println("Failed to publish data!"); } delay(5000); // Adjust delay as needed }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter