//!  LiquidCrystal_PCF8574 library by Matthias Hertel
// # https://wokwi.com/projects/418239231786728449

// # 와이파이 연결은 추후에 하니 나중에 코드 만지기로 할것

// This example shows various featues of the library for LCD with 16 chars and 2 lines.

#include <Arduino.h>
#include <Wire.h>
#include <LiquidCrystal_PCF8574.h>

const int I2C_ADDR = 0x27;
const int LCD_COLUNMS = 20;
const int LCD_ROWS = 4;
LiquidCrystal_PCF8574 lcd(I2C_ADDR); // set the LCD address to 0x27 for a 16(20) chars and 2(4) line display

int analogCurrentValue = 0;
int analogMaxValue = 0;
int analogMinValue = 0;
int analogAvgValue = 0;
int analogResolution = 0;
long analogPeakGapTime = 0;
int currentAnalogValue = 0;
int wifiSignal = 0;

const int limitArrayCount = 500;
static int rawData[limitArrayCount];
static unsigned long rawTimes[limitArrayCount];
static int readIndex = 0;

void setup_20x4_LCD()
{
    int error;
    Serial.println("LCD...");

    Serial.println("Probing for PCF8574 on address 0x27...");

    // See http://playground.arduino.cc/Main/I2cScanner how to test for a I2C device.
    Wire.begin();
    Wire.beginTransmission(I2C_ADDR);
    error = Wire.endTransmission();
    Serial.print("Error: ");
    Serial.print(error);

    if (error == 0)
    {
        Serial.println(": LCD found.");
        lcd.begin(LCD_COLUNMS, LCD_ROWS); // initialize the lcd
    }
    else
    {
        Serial.println(": LCD not found.");
    }
}

void loop_mainPage_LCD()
{
    int cValue = 9999;
    int maxValue = 9999;
    int minValue = 9999;
    int avgValue = 9999;
    int resolutino = 9999;
    long peakGapTime = 999999999;

    const int backLightness = 150;

    // 현재값을 0,0에 출력
    lcd.setBacklight(150);
    lcd.setCursor(0, 0);
    lcd.print("C.V: ");
    lcd.print(cValue);

    // 최대값을 11,0에 출력
    lcd.setCursor(11, 0);
    lcd.print("MAX: ");
    lcd.print(maxValue);

    // 최소값을 11,1에 출력
    lcd.setCursor(11, 1);
    lcd.print("MIN: ");
    lcd.print(minValue);

    // 평균값을 0,1에 출력
    lcd.setCursor(0, 1);
    lcd.print("AVG: ");
    lcd.print(avgValue);

    // 해상도를 0,3에 출력
    lcd.setCursor(0, 3);
    lcd.print("RES: ");
    lcd.print(resolutino);

    // 피크 갭 타임을 0,2에 출력
    lcd.setCursor(0, 2);
    lcd.print("PeakGap: ");
    lcd.print(peakGapTime);

    // 와이파이 수신상태 출력
    lcd.setCursor(13, 3);
    lcd.print("WIFI:");
    lcd.setCursor(19, 3);
    lcd.print(wifiSignal);
}

void readRawAnalogValue() // 받은 값을 평균값으로 계산해서 값을 계산
{
    if (readIndex < limitArrayCount)
    {
        int val = analogRead(A0);
        rawData[readIndex] = val;
        rawTimes[readIndex] = millis();
        readIndex++;
    }
    currentAnalogValue = analogRead(A0);
}

void averageAnalogValue() // 10회 측정한 값의 평균값 계산
{
    unsigned long previousMillis = 0;
    const long interval = 10;

    if (millis() - previousMillis >= interval)
    {
        previousMillis = millis();

        int rawAnalogValue = analogRead(A0);
        int sum = 0;
        for (int i = 0; i < 10; i++)
        {
            sum += analogRead(A0);
        }
        currentAnalogValue = sum / 10;
    }
}

void printIntervals()
{
    Serial.println("Printing intervals");
    int lastHighIndex = -1;
    for (int i = 0; i < readIndex; i++)
    {
        if (rawData[i] >= 500)
        {
            if (lastHighIndex != -1)
            {
                unsigned long interval = rawTimes[i] - rawTimes[lastHighIndex];
                Serial.print("Interval: ");
                Serial.println(interval);
            }
            lastHighIndex = i;
            Serial.print("High at: ");
            Serial.println(i);
        }
    }
}

// void readWifiRSSI() // 와이파이 신호세기 측정 , 테스트 완료
// {
//     if (WiFi.status() == WL_CONNECTED)
//     {
//         wifiSignal = WiFi.RSSI();
//     }
//     else
//     {
//         wifiSignal = 0;
//     }
// }

// # setup
void setup()
{

    Serial.begin(9600);

    // wait on Serial to be available on Leonardo , R4 MINIMA , WIFI
    while (!Serial)
        ;

    setup_20x4_LCD();

} // end of setup()

// # loop
void loop()
{
    loop_mainPage_LCD();
    // readWifiRSSI();
    readRawAnalogValue();
    printIntervals();
} // end of loop()

/*

if (show == 0)
    {
        lcd.setBacklight(255);
        lcd.home();
        lcd.clear();
        lcd.print("Hello LCD");
        delay(1000);

        lcd.setBacklight(0);
        delay(400);
        lcd.setBacklight(255);
    }
    else if (show == 1)
    {
        lcd.clear();
        lcd.print("Cursor On");
        lcd.cursor();
    }
    else if (show == 2)
    {
        lcd.clear();
        lcd.print("Cursor Blink");
        lcd.blink();
    }
    else if (show == 3)
    {
        lcd.clear();
        lcd.print("Cursor OFF");
        lcd.noBlink();
        lcd.noCursor();
    }
    else if (show == 4)
    {
        lcd.clear();
        lcd.print("Display Off");
        lcd.noDisplay();
    }
    else if (show == 5)
    {
        lcd.clear();
        lcd.print("Display On");
        lcd.display();
    }
    else if (show == 7)
    {
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("*** first line.");
        lcd.setCursor(0, 1);
        lcd.print("*** second line.");
    }
    else if (show == 8)
    {
        lcd.scrollDisplayLeft();
    }
    else if (show == 9)
    {
        lcd.scrollDisplayLeft();
    }
    else if (show == 10)
    {
        lcd.scrollDisplayLeft();
    }
    else if (show == 11)
    {
        lcd.scrollDisplayRight();
    }
    else if (show == 12)
    {
        lcd.clear();
        lcd.print("write-");
    }
    else if (show == 13)
    {
        lcd.clear();
        lcd.print("custom 1:<\01>");
        lcd.setCursor(0, 1);
        lcd.print("custom 2:<\02>");
    }
    else
    {
        lcd.print(show - 13);
    } // if

    delay(1400);
    show = (show + 1) % 16;
    */