#include <FastLED.h>
#define DATA_PIN 26
#define NUM_LEDS 16
CRGB leds[NUM_LEDS];

int pin_r = 27, pin_g = 14, pin_b = 12, pin_s = 25;
int r, g, b, s;
int pin_schakelaar = 19;

void read_sliders_and_potmeter() {
  analogReadResolution(8);
  r = analogRead(pin_r); // 0..4095
  g = analogRead(pin_g);
  b = analogRead(pin_b);
  s = analogRead(pin_s);

  Serial.print(r);  Serial.print("/");  Serial.print(g);  Serial.print("/");  Serial.print(b);
  Serial.print("/");  Serial.println(s);

}

void stuur_rgb_led() {
  static int r_before = 0, g_before = 0, b_before = 0;
  if (r != r_before or g != g_before or b != b_before) {
    r_before = r; g_before = g ; b_before = b;
    analogWrite( 16, r);
    analogWrite( 4, g);
    analogWrite( 0, b);
  }
}

void move_leds() {

  static int next_led = 0;
  int previous_led = 0;

  bool schakelaar = digitalRead(pin_schakelaar);

  if (schakelaar) {
    previous_led = next_led;
    next_led++;
    if (next_led > 15) {
      next_led = 0;
    }

  } else {
    previous_led = next_led;
    next_led--;
    if (next_led < 0) {
      next_led = 15;
    }

  }

  leds[previous_led] = CRGB(0, 0, 0);
  leds[next_led] = CRGB(r, g, b);
  FastLED.show();

}

void setup() {
  Serial.begin(115200);
  FastLED.addLeds<WS2812, DATA_PIN, GRB>(leds, NUM_LEDS);
  pinMode(pin_schakelaar, INPUT_PULLUP);
}

void loop() {
  static unsigned long timestamp;

  read_sliders_and_potmeter();
  stuur_rgb_led();

  if ((millis() - timestamp) > (256 - s)) {
    timestamp = millis();
    move_leds();
  }
  delay(10);
}