/* ESP32 MQTT Multiple LEDs
WIP
Steps:
- Go to the MQTT client of your choice
- In the Publish section replace the topic with the value of the mqttTopic variable
- In the message field enter the following:
{
r: 255,
g: 0,
b: 0,
brightness: 100
}
- Feel free to tweak the values here to get a different value
*/
#include <WiFi.h>
#include <FastLED.h>
#include <ArduinoJson.h>
#include <MQTT.h>
#define DATA_PIN 26
#define CLOCK_PIN 13
#define ledCount 20
CRGB leds[ledCount];
boolean refreshLED = false;
// Replace with your network credentials
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// Replace with your MQTT broker details
const char* mqttServer = "broker.emqx.io";
const int mqttPort = 1883;
const char* mqttTopic = "wokwi/jkan/lights/multiple-1";
char* clientId = "clientId-jk635-lights-multiple";
WiFiClient espClient;
MQTTClient client;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Serial.println("Hello, ESP32!");
FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, ledCount); // GRB ordering is assumed
// Connect to Wi-Fi
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.");
// Set up MQTT client
client.begin(mqttServer, mqttPort, espClient);
client.onMessage(messageReceived);
}
void loop() {
client.loop();
if (!client.connected()) reconnectMQTTClient();
if (refreshLED) {
Serial.println("Changing Color");
FastLED.show();
refreshLED = false;
}
}
void reconnectMQTTClient() {
Serial.println("Connecting to MQTT cluster");
while (!client.connected()) {
if (client.connect(clientId)) {
Serial.print(clientId);
Serial.println(" connected");
client.subscribe(mqttTopic);
} else {
Serial.print("failed, rc=");
Serial.print(client.lastError());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
void messageReceived(String &topic, String &payload) {
Serial.println("incoming: " + topic + " - " + payload);
DynamicJsonDocument doc(128);
deserializeJson(doc, payload);
uint8_t red = doc["r"].as<uint8_t>();
uint8_t green = doc["g"].as<uint8_t>();
uint8_t blue = doc["b"].as<uint8_t>();
uint8_t brightness = doc["brightness"].as<uint8_t>();
for (int j = 0; j < ledCount; j++) {
leds[j] = CRGB(red, green, blue);
leds[j].nscale8_video(brightness);
}
refreshLED = true;
// Note: Do not use the client in the callback to publish, subscribe or
// unsubscribe as it may cause deadlocks when other things arrive while
// sending and receiving acknowledgments. Instead, change a global variable,
// or push to a queue and handle it in the loop after calling `client.loop()`.
}