/*
 * RGBDuino test code - hope to implement a "true" RGBDuino board on the future.
 *
 * https://www.aliexpress.com/item/4000907154401.html
 * https://github.com/RGBduino/RGBDuino/blob/master/RGBDuino%20Manual%20V1.1.pdf
 * (use https://www.w3schools.com/colors/colors_groups.asp for wire colors)
 *
 * https://github.com/arduino12 11/12/2021
 */

#include <FastLED.h>
#include "notes.h"
#include "melody.h"

#define BUTTON_PIN          (2)
#define SPEAKER_PIN         (8)
#define RGB_LED_1_PIN       (12)
#define RGB_LED_0_PIN       (13)
#define RGB_LED_BRIGHTNESS  (32) // 255 is very bright

const uint8_t LED_BAR_PINS[] = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11};

CRGB rgb_led_0;
CRGB rgb_led_1;

void play_melody(const uint16_t *melody)
{
  uint16_t note, note_ms, note_1_32_ms = 7500 / *melody++;

  while (1) {
    note = *melody++;
    if (note == NOTE_END)
      break;
    note_ms = note_1_32_ms * NOTE_BEAT_1_32[note >> NOTE_BEAT_BIT]; // duration
    note &= NOTE_BEAT_MASK; // frequency

    tone(SPEAKER_PIN, note);
    delay(note_ms);
    noTone(SPEAKER_PIN);
    delay(note_1_32_ms * 2); // short note pause
    if (!digitalRead(BUTTON_PIN))
      break;
  }
  while (!digitalRead(BUTTON_PIN));
}

void setup()
{ 
  pinMode(SPEAKER_PIN, OUTPUT);
  for (uint8_t i = 0; i < sizeof(LED_BAR_PINS); i++)
    pinMode(LED_BAR_PINS[i], OUTPUT);
  pinMode(BUTTON_PIN, INPUT_PULLUP);

  FastLED.addLeds<NEOPIXEL, RGB_LED_0_PIN>(&rgb_led_0, 1);
  FastLED.addLeds<NEOPIXEL, RGB_LED_1_PIN>(&rgb_led_1, 1);
  FastLED.setBrightness(RGB_LED_BRIGHTNESS);
  rgb_led_0 = CRGB::Red;
  rgb_led_1 = CRGB::Blue;
  FastLED.show();

  // delay(1000); // needed for simulation only because the first call to tone takes time to start
}

void loop()
{
  // play_melody(MELODY_JINGLE_BELLS);
  // play_melody(MELODY_HANUKKAH);
  // play_melody(MELODY_HATIKVA);
  // play_melody(MELODY_360_START);
  play_melody(MELODY_360_GOOD);
  play_melody(MELODY_360_BAD);
  delay(1000);
}