SunFounder ESP32 Starter Kit
(continued from previous page)
const char* password = "<PASSWORD>";
5. Find the next line and modify your unique_identifier. Guarantee that your unique_identifier is truly
unique as any IDs that are identical trying to log in to the same MQTT Broker may result in a login failure.
// Add your MQTT Broker address, example:
const char* mqtt_server = "broker.hivemq.com";
const char* unique_identifier = "sunfounder-client-sdgvsda";
Topic Subscription
1. To avoid interference from messages sent by other participants, you can set it as an obscure or uncommon string.
Simply replace the current topic SF/LED with your desired topic name.
Note: You have the freedom to set the Topic as any character you desire. Any MQTT device that has
subscribed to the identical Topic will be able to receive the same message. You can also simultane-
ously subscribe to multiple Topics.
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect(unique_identifier)) {
Serial.println("connected");
// Subscribe
client.subscribe("SF/LED");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
2. Modify the functionality to respond to the subscribed topic. In the provided code, if a message is received on the
topic SF/LED, it checks whether the message is on or off. Depending on the received message, it changes the
output state to control the LED’s on or off status.
Note: You can modify it for any topic you are subscribed to, and you can write multiple if statements
to respond to multiple topics.
void callback(char* topic, byte* message, unsigned int length) {
Serial.print("Message arrived on topic: ");
Serial.print(topic);
Serial.print(". Message: ");
String messageTemp;
(continues on next page)
182 Chapter 1. For Arduino User