/*
Vorschub Simulator für eine LED Leiste mit 30 Leds pro Meter  = 3,33 mm pro LED
Es soll eine LED mit einer bestimmten Geschwindigkeit durchlaufen 
0 mm/s bis 9999 mm/s
*/
#include <FastLED.h>
#include <TM1637.h>
int CLK = 2;
int DIO = 3;
TM1637 tm(CLK, DIO);
// FASTLED
#define NUM_LEDS             256
#define DATA_PIN             13  
#define MAX_BRIGHTNESS      200
#define MIN_BRIGHTNESS       50
#define FRAMES_PER_SECOND    60
#define  PIN_POTI            A0
#define LEDS_PRO_M          30.00
CRGB leds[NUM_LEDS];  
uint8_t hue = 0;
//  144          1000mm / Leds [mm/LED]   6,944 mm/LED
//  Bei einer Sekunde
//  6,944 mm/LED / 1000000 us =  0,006944 s  -> 6,944 us
float faktor = 1000000000/(float)LEDS_PRO_M;   // Einheit us
//----------------------------------------------------------------
void setup() {
  Serial.begin(9600);
  Serial.println(faktor,3); 
  tm.init();
  tm.set(2);
  
  FastLED.addLeds<WS2812B, DATA_PIN, GRB>(leds, NUM_LEDS);
  FastLED.setBrightness(MAX_BRIGHTNESS);
  /*
  LEDS.showColor(CRGB(100, 000, 0)); delay(1000);
  LEDS.showColor(CRGB(0, 100, 0)); delay(1000);
  LEDS.showColor(CRGB(0, 0, 100)); delay(1000);
  */
  //laserSchwert();
}
void displayValue(int zahl) {
  byte e = zahl % 10;
  byte z = (zahl / 10) % 10;
  byte h = (zahl / 100) % 10;
  byte t = (zahl / 1000) % 10;
  tm.display(0, t);
  tm.display(1, h);
  // tm.point(1);
  tm.display(2, z);
  tm.display(3, e);
}
int pos=0;
void laserSchwert() {
  LEDS.showColor(CRGB(0, 0, 0));
  // Ausfahren
  for (int pos=0; pos < NUM_LEDS; pos++ ) {
     leds[pos]=CRGB(255, 0, 0);
     FastLED.show();
     delay(1);
  }
  // Einfahren
  for (int pos=NUM_LEDS; pos > 0; pos-- ) {
     leds[pos]=CRGB(0, 0, 0);
     FastLED.show();
     delay(1);
  }
}
long x,y;
int potiValue, oldPotiValue;
void loop() {
  x = millis();
  potiValue = analogRead(PIN_POTI);
  if (potiValue != oldPotiValue) {
    oldPotiValue = potiValue;
    potiValue = map(potiValue,0,1023,0,999);
    displayValue(map(potiValue,0,999,0,1000));
  }
  
  if (potiValue > 0)
  {
    // Led anzeigen
    leds[pos]=CRGB(242, 10, 10);
    FastLED.show();
    // Delay berechnen:
    // bei 144 Led pro Meter entspricht 1000mm/s ->   6,944 ms/LED
    // bei 100 Led pro Meter entspricht 1000mm/s ->  10,000 ms/LED
    // bei  60 Led pro Meter entspricht 1000mm/s ->  16,666 ms/LED
    // bei  30 Led pro Meter entspricht 1000mm/s ->  33,333 ms/LED  Achtung int zu groß
    //Serial.println(delayTime); 
    //delay(6);  delayMicroseconds(944);
    //delay(10); 
    //delay(16); delayMicroseconds(666);
    //delay(33); delayMicroseconds(333);
    // Led wieder löschen
    leds[pos]=CRGB(0, 0, 0); 
    //FastLED.show();
  
    pos++;
    if (pos==NUM_LEDS) pos=0;
  } 
  else  
  { 
    delay(200);
    LEDS.showColor(CRGB(50, 0, 0));  
  }
  y = millis()-x;
  Serial.println(y); 
  
}