133 lines
2.9 KiB
C++
133 lines
2.9 KiB
C++
#include <Wire.h>
|
|
#include <EEPROM.h>
|
|
#include <Adafruit_NeoPixel.h>
|
|
|
|
#define DEFAULT_ADDRESS 0x08
|
|
#define DEFAULT_LED_COUNT 30
|
|
#define MAX_NAME_LENGTH 24
|
|
#define LED_PIN 6
|
|
|
|
struct Config {
|
|
uint8_t address;
|
|
char deviceName[MAX_NAME_LENGTH+1];
|
|
uint16_t ledCount;
|
|
uint8_t brightness;
|
|
};
|
|
|
|
Config config;
|
|
Adafruit_NeoPixel strip;
|
|
|
|
void handleCommand(int numBytes);
|
|
void saveConfig();
|
|
void loadConfig();
|
|
void updateStrip();
|
|
|
|
void setup() {
|
|
Serial.begin(115200);
|
|
EEPROM.begin(sizeof(Config));
|
|
loadConfig();
|
|
|
|
strip = Adafruit_NeoPixel(config.ledCount, LED_PIN, NEO_GRB + NEO_KHZ800);
|
|
strip.begin();
|
|
strip.setBrightness(config.brightness);
|
|
strip.show(); // Initialize all off
|
|
|
|
Wire.onReceive(handleCommand);
|
|
Wire.onRequest([]() {
|
|
String response = String(config.address) + ",LED-Strip," +
|
|
config.deviceName + "," +
|
|
String(config.ledCount) + "," +
|
|
String(config.brightness);
|
|
Wire.print(response);
|
|
});
|
|
|
|
Wire.begin(config.address);
|
|
}
|
|
|
|
void loop() { /* Empty */ }
|
|
|
|
void handleCommand(int numBytes) {
|
|
uint8_t cmd = Wire.read();
|
|
|
|
switch(cmd) {
|
|
case 0xA0: // Set individual pixel
|
|
if(numBytes >= 5) {
|
|
uint8_t pixel = Wire.read();
|
|
uint8_t r = Wire.read();
|
|
uint8_t g = Wire.read();
|
|
uint8_t b = Wire.read();
|
|
|
|
if(pixel < config.ledCount) {
|
|
strip.setPixelColor(pixel, strip.Color(r, g, b));
|
|
updateStrip();
|
|
}
|
|
}
|
|
break;
|
|
|
|
case 0xA1: // Set all pixels
|
|
if(numBytes >= 4) {
|
|
uint8_t r = Wire.read();
|
|
uint8_t g = Wire.read();
|
|
uint8_t b = Wire.read();
|
|
|
|
for(int i=0; i<config.ledCount; i++) {
|
|
strip.setPixelColor(i, strip.Color(r, g, b));
|
|
}
|
|
updateStrip();
|
|
}
|
|
break;
|
|
|
|
case 0xA2: // Set brightness
|
|
if(numBytes >= 2) {
|
|
config.brightness = Wire.read();
|
|
strip.setBrightness(config.brightness);
|
|
saveConfig();
|
|
updateStrip();
|
|
}
|
|
break;
|
|
|
|
case 0xB0: // Clear all
|
|
strip.clear();
|
|
updateStrip();
|
|
break;
|
|
|
|
case 0xC0: // Set address
|
|
if(numBytes >= 2) {
|
|
config.address = Wire.read();
|
|
saveConfig();
|
|
Wire.begin(config.address);
|
|
}
|
|
break;
|
|
|
|
case 0xD0: // Set LED count
|
|
if(numBytes >= 3) {
|
|
config.ledCount = Wire.read() << 8;
|
|
config.ledCount |= Wire.read();
|
|
saveConfig();
|
|
strip.updateLength(config.ledCount);
|
|
updateStrip();
|
|
}
|
|
break;
|
|
}
|
|
}
|
|
|
|
void updateStrip() {
|
|
strip.show();
|
|
}
|
|
|
|
void loadConfig() {
|
|
EEPROM.get(0, config);
|
|
if(config.address < 0x08 || config.address > 0x77) {
|
|
config.address = DEFAULT_ADDRESS;
|
|
config.ledCount = DEFAULT_LED_COUNT;
|
|
config.brightness = 255;
|
|
strcpy(config.deviceName, "LED Controller");
|
|
saveConfig();
|
|
}
|
|
}
|
|
|
|
void saveConfig() {
|
|
EEPROM.put(0, config);
|
|
EEPROM.commit();
|
|
}
|