/* * Connects to a WiFi network and MQTT broker, then publishes analog sensor readings * */ #include <WiFi.h> #include <PubSubClient.h> const char* ssid = "your-ssid"; const char* password = "your-password"; const char* mqtt_server = "your_broker_ip"; WiFiClient wifiClient; PubSubClient client(wifiClient); long lastMsg = 0; void setup() { Serial.begin(115200); delay(10); // We start by connecting to a WiFi network 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()); // Set up MQTT client.setServer(mqtt_server, 1883); } void reconnect() { // Loop until we're reconnected while (!client.connected()) { Serial.print("Attempting MQTT connection..."); // Create a random client ID String clientId = "ESP8266Client-"; clientId += String(random(0xffff), HEX); // Attempt to connect if (client.connect(clientId.c_str())) { Serial.println("Connected"); // Connected - do something useful - subscribe to topics, publish messages, etc. } else { Serial.print("failed, rc="); Serial.print(client.state()); Serial.println(" try again in 5 seconds"); // Wait 5 seconds before retrying delay(5000); } } } int val = 0; void loop() { if (!client.connected()) { reconnect(); } client.loop(); // Read a value long now = millis(); if (now - lastMsg > 100) { lastMsg = now; val = analogRead(32); client.publish("foo", String(val).c_str()); Serial.println(val); } }