/*
 * Matrice WS2812B : conversion (x, y) vers numéro de LED — Kaihatsu Lab
 * Fonctionne avec une matrice câblée en serpentin (le plus courant) ou en lignes parallèles.
 * Bibliothèque : FastLED.
 *
 * Origine (0, 0) : coin en haut à gauche, x vers la droite, y vers le bas.
 */
#include <FastLED.h>

#define LED_PIN     5
#define WIDTH       8
#define HEIGHT      8
#define NUM_LEDS    (WIDTH * HEIGHT)
#define SERPENTINE  true            // true : une ligne sur deux est parcourue à l'envers

CRGB leds[NUM_LEDS + 1];            // une LED de plus : « poubelle » pour les points hors matrice

uint16_t XY(int x, int y) {
  if (x < 0 || x >= WIDTH || y < 0 || y >= HEIGHT) return NUM_LEDS;   // hors matrice
  if (SERPENTINE && (y & 1)) x = WIDTH - 1 - x;                        // lignes impaires à l'envers
  return y * WIDTH + x;
}

void setup() {
  FastLED.addLeds<WS2812B, LED_PIN, GRB>(leds, NUM_LEDS);
  FastLED.setBrightness(40);
}

void loop() {
  static uint8_t hue = 0;
  for (int y = 0; y < HEIGHT; y++) {
    for (int x = 0; x < WIDTH; x++) {
      leds[XY(x, y)] = CHSV(hue + (x + y) * 16, 255, 255);            // arc-en-ciel en diagonale
    }
  }
  FastLED.show();
  hue += 2;
  delay(30);
}
