Skip to content

Instantly share code, notes, and snippets.

@klattimer
Created December 14, 2020 15:59
Show Gist options
  • Save klattimer/d504b6c7c884c3a7132e99f71cf117c7 to your computer and use it in GitHub Desktop.
Save klattimer/d504b6c7c884c3a7132e99f71cf117c7 to your computer and use it in GitHub Desktop.
ESP01S FASTLED over MQTT
/* ESP01S lighting controllers are pretty cheap, you can get them on aliexpress/ebay/amazon etc...
* https://www.amazon.co.uk/ESP8266-ESP-01-ESP-01S-Controller-Electronic/dp/B0819VRPXX
*
* A bit thin on decent software though, so I've cobbled together this MQTT client that lets you
* use MQTT to change the LED colours. With LED0 reserved for status of the device itself.
*/
#include "EspMQTTClient.h"
#include <FastLED.h>
#define MQTT_MAX_PACKET_SIZE 1024
#define COLOR_ERROR 163, 21, 8
#define COLOR_WARNING 140, 143, 11
#define COLOR_OK 80, 180, 9
#define NUM_LEDS 16
CRGB leds[NUM_LEDS];
#define DATA_PIN 2
EspMQTTClient client(
"wifi",
"secret",
"192.168.1.1",
"ESP01S-WS2811",
1883
);
void setup() {
Serial.begin(115200);
FastLED.addLeds<WS2811, DATA_PIN, GRB>(leds, NUM_LEDS);
leds[0] = CRGB::White;
int i;
for (i = 1; i < NUM_LEDS; i++) {
leds[i] = CRGB::Black;
}
FastLED.show();
// Optionnal functionnalities of EspMQTTClient :
// Enable debugging messages sent to serial output
client.enableDebuggingMessages();
// Enable the web updater. User and password default to values of MQTTUsername and MQTTPassword. These can be overrited with enableHTTPWebUpdater("user", "password").
client.enableHTTPWebUpdater();
// You can activate the retain flag by setting the third parameter to true
client.enableLastWillMessage("ESP01S-WS2811/lastwill", "I am going offline");
}
void onConnectionEstablished() {
leds[0] = CRGB(COLOR_OK);
int i;
for (i = 1; i < NUM_LEDS; i++) {
leds[i] = CRGB::Black;
char buf[128];
sprintf(buf, "ESP01S-WS2811/LED/%d", i);
client.publish(buf, "000000");
}
FastLED.show();
// Subscribe to "mytopic/wildcardtest/#" and display received message to Serial
client.subscribe("ESP01S-WS2811/LED/#", [](const String & topic, const String & payload) {
// Extract the LED ID from the topic
char buf[1024];
int index = 0;
topic.toCharArray(buf, topic.length() + 1);
sscanf(buf, "ESP01S-WS2811/LED/%d", &index);
int r,g,b;
payload.toCharArray(buf, payload.length() + 1);
sscanf(buf, "%02x%02x%02x", &r, &g, &b);
leds[index] = CRGB(r, g, b);
FastLED.show();
});
}
void loop()
{
if (!client.isConnected()) {
bool isOn = (millis() / 500) % 2;
if (!client.isWifiConnected() && isOn) {
leds[0] = CRGB(COLOR_ERROR);
} else if (!client.isMqttConnected() && isOn) {
leds[0] = CRGB(COLOR_WARNING);
}
if (!isOn) {
leds[0] = CRGB::Black;
}
FastLED.show();
}
client.loop();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment