#include <Adafruit_NeoPixel.h>
#define PIN 8
#define WIDTH 16
#define HEIGHT 16
#define NUMPIXELS (WIDTH * HEIGHT)
Adafruit_NeoPixel strip(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);
void setup() {
Serial.begin(115200);
strip.begin();
strip.show();
// Executa padrão de teste
testPattern();
}
// Função para converter coordenadas XY em índice real na matriz zig-zag
int XYtoIndex(int x, int y) {
if (y % 2 == 0) {
return y * WIDTH + x; // linhas pares: esquerda → direita
} else {
return y * WIDTH + (WIDTH - 1 - x); // linhas ímpares: direita → esquerda
}
}
// Função de teste: percorre cores básicas
void testPattern() {
// vermelho
for (int i = 0; i < NUMPIXELS; i++) {
strip.setPixelColor(i, strip.Color(255, 0, 0));
}
strip.show();
delay(1000);
// verde
for (int i = 0; i < NUMPIXELS; i++) {
strip.setPixelColor(i, strip.Color(0, 255, 0));
}
strip.show();
delay(1000);
// azul
for (int i = 0; i < NUMPIXELS; i++) {
strip.setPixelColor(i, strip.Color(0, 0, 255));
}
strip.show();
delay(1000);
// branco
for (int i = 0; i < NUMPIXELS; i++) {
strip.setPixelColor(i, strip.Color(255, 255, 255));
}
strip.show();
delay(1000);
// apagar
strip.clear();
strip.show();
}
void loop() {
if (Serial.available()) {
String frame = Serial.readStringUntil('\n'); // lê quadro completo
int startIdx = frame.indexOf("<START>");
int endIdx = frame.indexOf("<END>");
if (startIdx == -1 || endIdx == -1) return;
String data = frame.substring(startIdx + 7, endIdx);
int pixelIndex = 0;
char *token = strtok((char*)data.c_str(), ";");
while (token != NULL && pixelIndex < NUMPIXELS) {
int r, g, b;
if (sscanf(token, "%d,%d,%d", &r, &g, &b) == 3) {
int x = pixelIndex % WIDTH;
int y = pixelIndex / WIDTH;
int realIndex = XYtoIndex(x, y);
strip.setPixelColor(realIndex, strip.Color(r, g, b));
}
pixelIndex++;
token = strtok(NULL, ";");
}
strip.show();
}
}
X Coordinate -->
Y Coordinate -->