#include <LiquidCrystal.h>

// initialize the library by associating any needed LCD interface pin
// with the arduino pin number it is connected to

LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

unsigned long previousMicros;
unsigned long duration = 200; 
unsigned long previousStep;

int state;
int samples;
int cresc = 0;
int descresc = 0;
float minVolt;
float maxVolt;
float RMS;
float maxPeak;
float minPeak;


float averSum;
float averCnt;


float volt[200];
float analogVolt;
float prevVolt;
int pos = 0;

int cycleCnt = 0;

int timer = 1;

void setup() {
  // put your setup code here, to run once:

  pinMode (A2, INPUT);

  Serial.begin(115200);


  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);


  
  delay (1000);

}

void loop()
{
  
  maxVolt = 0;
  maxPeak = 0;
  minPeak = 500;
  
  previousMicros = micros();
  previousStep = micros();
  
  while (micros() - previousStep < 1000000)
  {
     
    if (micros() - previousMicros >= duration)
    {
      analogVolt = (analogRead (A2)*5.0/1024.0 - 2.485) * 480.0;

      //adaugare sample la calcul RMS
      averSum += analogVolt * analogVolt;
      averCnt ++;

      // detectie min si max
      // if (analogVolt < minVolt)
      // {
      //   minVolt = analogVolt;
      // }

      if (abs(analogVolt) > maxVolt)
      {
        maxVolt = abs(analogVolt);
      }

      // detectie peak absolut
      if ((abs(analogVolt) - prevVolt < 0) && (cresc == 1))
      {
        
        // detectie max si min de peak
        if (abs(prevVolt) > maxPeak)
        {
          maxPeak = abs(prevVolt);
        }

        if (abs(prevVolt) < minPeak)
        {
          minPeak = abs(prevVolt);
        }

        cresc = 0;

      }

      if (abs(analogVolt) - prevVolt > 0)
      {
        cresc = 1;
      }

      previousMicros = micros();
      prevVolt = abs(analogVolt);

    }
  }

  // calcul RMS
  RMS = sqrt(averSum/averCnt);
  averSum = 0;
  averCnt = 0;
  
  // (note: line 1 is the second row, since counting begins with 0):
  lcd.setCursor(0, 0);
  // print the number of seconds since reset:
  lcd.print(maxVolt);
  lcd.setCursor(0, 1);
  lcd.print((micros() - previousStep)/1000000.0);

  // Serial.print(RMS);
  // Serial.print(", ");
  // Serial.print(maxVolt);
  // Serial.print(", ");
  // Serial.print(minPeak);
  // Serial.print(", ");
  // Serial.print(maxPeak);
  // Serial.print(", ");
  // Serial.println(micros() - previousStep);



  

}