Created
May 6, 2024 03:02
-
-
Save ChrisCrossCrash/1ec837ca95ee5d290b073d5f8664271b to your computer and use it in GitHub Desktop.
Connects a wifi-enabled Arduino to an MQTT broker without TLS
This file contains 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
/* | |
* This sketch connects to a WiFi network and sends a message to an MQTT broker. | |
*/ | |
#include <WiFi.h> | |
#include <ArduinoMqttClient.h> | |
// TODO: Replace these with your WiFi credentials | |
const char ssid[] = "myWifiSsid"; | |
const char pass[] = "myWifiPassword"; | |
WiFiClient wifiClient; | |
MqttClient mqttClient(wifiClient); | |
const char broker[] = "test.mosquitto.org"; | |
int port = 1883; | |
const char topic[] = "arduino/simple"; | |
void setup() { | |
Serial.begin(115200); | |
delay(10); | |
// Connect to WiFi network | |
Serial.println(); | |
Serial.println("Connecting to WiFi..."); | |
WiFi.begin(ssid, pass); | |
while (WiFi.status() != WL_CONNECTED) { | |
delay(500); | |
Serial.print("."); | |
} | |
Serial.println(""); | |
Serial.println("WiFi connected"); | |
Serial.println("IP address: "); | |
Serial.println(WiFi.localIP()); | |
// Connecting to MQTT Broker | |
Serial.print("Connecting to MQTT Broker: "); | |
Serial.println(broker); | |
if (!mqttClient.connect(broker, port)) { | |
Serial.print("MQTT connection failed! Error code = "); | |
Serial.println(mqttClient.connectError()); | |
while (1); | |
} | |
Serial.println("Connected to MQTT Broker!"); | |
} | |
void loop() { | |
// Ensure the connection to the broker is alive | |
if (!mqttClient.connected()) { | |
Serial.println("MQTT disconnected. Reconnecting..."); | |
if (!mqttClient.connect(broker, port)) { | |
Serial.print("Reconnect failed. Error code = "); | |
Serial.println(mqttClient.connectError()); | |
delay(5000); // Wait 5 seconds before retrying | |
return; | |
} | |
} | |
mqttClient.poll(); | |
// Send a message to the broker | |
Serial.print("Sending message to topic: "); | |
Serial.println(topic); | |
mqttClient.beginMessage(topic); | |
mqttClient.print("Hello from Arduino!"); | |
mqttClient.endMessage(); | |
Serial.println("Message sent. Waiting 5 seconds before sending another..."); | |
delay(5000); // wait 5 seconds before sending another message | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment