/* ESP32 MQTT Single LED
Change a single LED on a MQTT event, note there is no error
handling here
Steps:
- Go to: https://www.hivemq.com/demos/websocket-client/ and
connect
- In the Publish section replace the topic with:
wokwi/jkan/light/single
- In the message field enter the following:
{
"r": 0,
"g": 100,
"b": 200,
"brightness": 100
}
- Feel free to tweak the values here to get a different value
*/
#include <FastLED.h>
#include <WiFiNINA.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
// Replace with your network credentials
const char* ssid = "Wokwi-GUEST";
//15 | P a g e
const char* password = "";
// Replace with your MQTT broker details
const char* mqttServer = "broker.hivemq.com";
const int mqttPort = 1883;
const char* mqttTopic = "wokwi/jkan/light/single";
char* clientId = "clientId-jk635-light-single";
WiFiClient espClient;
PubSubClient client(espClient);
// LEDs
#define RED_PIN 13
#define GREEN_PIN 16
#define BLUE_PIN 14
void setup() {
Serial.begin(115200);
// Set pins as output
pinMode(RED_PIN, OUTPUT);
pinMode(GREEN_PIN, OUTPUT);
pinMode(BLUE_PIN, OUTPUT);
// 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.setServer(mqttServer, mqttPort);
client.setCallback(callback);
reconnectMQTTClient();
}
void loop() {
if (!client.connected()) reconnectMQTTClient();
client.loop();
}
void reconnectMQTTClient() {
Serial.println("Connecting to MQTT broker...");
while (!client.connected()) {
if (client.connect(clientId)) {
Serial.println("MQTT connected!");
client.subscribe(mqttTopic);
Serial.print("Subscribed to topic: ");
//17 | P a g e
Serial.println(mqttTopic);
} else {
Serial.print("MQTT connection failed, rc=");
Serial.print(client.state());
Serial.println(". Retrying in 5 seconds...");
delay(5000);
}
}
}
void callback(char* topic, byte* message, unsigned int length) {
Serial.print("Message arrived on topic: ");
Serial.println(topic);
// Convert message to string
String msgString;
for (int i = 0; i < length; i++) {
msgString += (char)message[i];
}
Serial.print("Message: ");
Serial.println(msgString);
// Parse JSON message
DynamicJsonDocument doc(128);
DeserializationError error = deserializeJson(doc, msgString);
if (error) {
//
Serial.print("JSON Deserialization failed: ");
Serial.println(error.c_str());
return;
}
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>();
// Scale brightness
red = map(brightness, 0, 100, 0, red);
green = map(brightness, 0, 100, 0, green);
blue = map(brightness, 0, 100, 0, blue);
// Write to pins
analogWrite(RED_PIN, red);
analogWrite(GREEN_PIN, green);
analogWrite(BLUE_PIN, blue);
Serial.println("LED color changed.");
}