#include <Adafruit_AS7341.h>
Adafruit_AS7341 as7341;

String WLLabel[8] = { "415 ", "445 ", "480 ", "515 ", "555 ", "590 ", "630 ", "680 " };
int IndRead[8] = { 0, 1, 2, 3, 6, 7, 8, 9 };  // Numéro des index dans la table des valeurs lues
uint16_t Son[12];
uint16_t Soff[12];
float Smesure[8];  // Smesure= Son-Soff pour s'affranchir du fond parasite
float S0[8];
float A[8];  // Absorbance=-log10(Smesure/S0)

boolean bavard = false;
boolean UVon = false;
String ToBePrinted="Abs";

int PinLED = 13;
int PinUV = 8;
String Aafficher;

void setup() {
  pinMode(PinLED, OUTPUT);
  digitalWrite(PinLED, HIGH);
  pinMode(PinUV, OUTPUT);

  Serial.begin(9600);

  if (!as7341.begin()) {
    Serial.println("Could not find AS7341");
    while (1) { delay(10); }
  }
  as7341.setATIME(99);
  as7341.setASTEP(399);
  as7341.setGain(AS7341_GAIN_256X);
  as7341.enableLED(false);
}




void loop() {

  digitalWrite(PinLED, HIGH);
  delay(50);
  if (!as7341.readAllChannels(Son)) {
    Serial.println("Error reading all channels!");
    return;
  }

  digitalWrite(PinLED, LOW);
  delay(20);
  if (!as7341.readAllChannels(Soff)) {
    Serial.println("Error reading all channels!");
    return;
  }

  Aafficher = "";

  for (int i = 0; i < 8; i++) {
    int index = IndRead[i];
    Smesure[i] = Son[index] - Soff[index];
    A[i] = log10(1.0 * S0[i] / Smesure[i]);

    if (bavard) {
      //Serial.print(" nm : ");
      Serial.print(Son[index]);
      Serial.print("  -  ");
      Serial.print(Soff[index]);
      Serial.print("  =  ");
      Serial.print(Smesure[i]);
      Serial.print("  //  ");
      Serial.print(S0[i]);
      Serial.print("  >  ");
    }

    if (ToBePrinted == "Abs") {  Aafficher = Aafficher + String(A[i], 3);  }
    if (ToBePrinted == "S") { Aafficher = Aafficher + String(Smesure[i]); }
    if (ToBePrinted == "Son") { Aafficher = Aafficher + String(Son[index]); }
    if (ToBePrinted == "Soff") { Aafficher = Aafficher + String(Soff[index]); }

    if (i < 8 - 1) { Aafficher = Aafficher + ","; }
  }



  if (millis() < 3000) {
    for (int i = 0; i < 8; i++) {
      S0[i] = Smesure[i];
    }
  }

  if (Serial.available()) {
    String chaineSaisie = String(Serial.readString());

    if (chaineSaisie == "0") {  //teste si le caractère est 0
      //Serial.println("            Memorisation des valeurs de S0");
      for (int i = 0; i < 8; i++) {
        S0[i] = Smesure[i];
      }
    }  // fin de stockage S0

    if (chaineSaisie == "B") {
      bavard = !bavard;
    }

    if (chaineSaisie == "U") {
      UVon = !UVon;
      digitalWrite(PinUV, UVon);
    }


    if ((chaineSaisie == "Abs") || (chaineSaisie == "S") || (chaineSaisie == "Son") || (chaineSaisie == "Soff")) {
      ToBePrinted = chaineSaisie;
    }
  }

  Serial.println(Aafficher);
}