Last active
February 3, 2021 14:55
-
-
Save gresan-gits/4f483eb46f5c87a67975ece104b95a65 to your computer and use it in GitHub Desktop.
lwMQTT testing on ESP32 with Arduino
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <WiFi.h> | |
#include <MQTT.h> | |
const char ssid[] = "ssid"; | |
const char password[] = "pass"; | |
WiFiClient net; | |
MQTTClient client; | |
unsigned long lastMillis = 0; | |
void connect() { | |
Serial.print("checking wifi..."); | |
while (WiFi.status() != WL_CONNECTED) { | |
Serial.print("."); | |
delay(1000); | |
} | |
Serial.print("\nconnecting..."); | |
while (!client.connect("arduinoESP32")) { | |
Serial.print("."); | |
delay(1000); | |
} | |
Serial.println("\nconnected!"); | |
client.subscribe("/clientSub"); | |
// client.unsubscribe("/clientSub"); | |
} | |
void messageReceived(String &topic, String &payload) { | |
Serial.println("incoming: " + topic + " - " + payload); | |
} | |
void setup() { | |
Serial.begin(115200); | |
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()); | |
// Note: Local domain names (e.g. "Computer.local" on OSX) are not supported by Arduino. | |
// You need to set the IP address directly. | |
client.begin("mqtt.eclipse.org", net); | |
client.onMessage(messageReceived); | |
connect(); | |
} | |
void loop() { | |
client.loop(); | |
delay(10); // <- fixes some issues with WiFi stability | |
if (!client.connected()) { | |
connect(); | |
} | |
// publish a message roughly every second. | |
if (millis() - lastMillis > 1000) { | |
lastMillis = millis(); | |
client.publish("/clientPub", "Hello from ESP32"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment