/*
  Star
  Created by Hartvik Line, December 20, 2020.
  Released into the public domain.
*/

#include <WS2812FX.h>
#include <CapacitiveSensor.h>


#define LED_COUNT 62  //Nr of LED-s in strip
#define LED_PIN 2     //Din on LED strip connecting pin.

CapacitiveSensor sensor = CapacitiveSensor(10, 12); // 10 megohm resistor between pins, 12 is sensor pin
WS2812FX ws2812fx = WS2812FX(LED_COUNT, LED_PIN, NEO_RGB + NEO_KHZ800);


int modeInc = 0;
int modeIndex = 0;
long TouchValue = 0;
//Best fit modes for lamp
int list[18] =      {44,   44,  12,   14,   14,   17,  16,   38,   31,   32,   33,   20,   21,   22,  23,  19,  45,   55};
int Speedlist[18] = {1000, 200, 3000, 4000, 700,  150, 4000, 1300, 1000, 1300, 1300, 4000, 300,  300, 400, 400, 1000, 500};
int mode;
int speed;

//Varliables for touch sensing (Sens when signal processed with two different low pass filters intersect)
const float alpha = 0.05;
double data_filtered[] = {0, 0};
double derivate;
const float alpha2 = 0.005;
double data_filtered2[] = {0, 0};
const int n = 1;

//Flip flop to only switch one mode while touch sensor is activated.
bool FlipFlop = 0;

void setup() {
  Serial.begin(9600);
  ws2812fx.init();
  ws2812fx.setBrightness(255);
  ws2812fx.setSpeed(4000);
  ws2812fx.setColor(0xFFFFFF);
  ws2812fx.setMode(list[2]);
  ws2812fx.start();
  sensor.set_CS_AutocaL_Millis(0xFFFFFFFF); // turn off autocalibrate on channel 1 - just as an example

  //Init filters
  data_filtered[n] = sensor.capacitiveSensor(30);
  data_filtered[n - 1] = data_filtered[n];

  data_filtered2[n] = sensor.capacitiveSensor(30);
  data_filtered2[n - 1] = data_filtered[n];
}


void loop() {
  ws2812fx.service();
  TouchValue = sensor.capacitiveSensor(30);
  // Low Pass Filters
  data_filtered[n] = alpha * TouchValue + (1 - alpha) * data_filtered[n - 1];
  data_filtered[n - 1] = data_filtered[n];

  data_filtered2[n] = alpha2 * TouchValue + (1 - alpha2) * data_filtered2[n - 1];
  data_filtered2[n - 1] = data_filtered2[n];




  // Print to debug and adjust touch sens triggers (I use SerialPlot software to plot these values in a real time graph)
  ///Serial.print(data_filtered2[n]); // print LP medium filtered
  //Serial.print("\t"); // tab character for debug window spacing
  //Serial.println(data_filtered[n]); // print LP high filtered

  delay(10);

  //Change mode if touch detected
  if (FlipFlop == 0 && data_filtered[n] > data_filtered2[n] + 500) {

    modeIndex += 1;
    mode = list [modeIndex % 18];
    speed = Speedlist [modeIndex % 18];
    ws2812fx.setMode(mode);
    ws2812fx.setSpeed(speed);
    Serial.print("Mode: ");
    Serial.println(ws2812fx.getMode());
    Serial.print("Speed: ");
    Serial.println(ws2812fx.getSpeed());
    modeInc = 0;
    Serial.println("Tik");
    FlipFlop = 1;
  }
  if (FlipFlop == 1 && data_filtered[n] < data_filtered2[n] + 300) {
    Serial.println("Tok");
    FlipFlop = 0;
  }
}
