#include <Arduino.h>
#include <Wire.h>
#include "LiquidCrystal_I2C.h"

#define BTN_PIN 5

// Function declaration
void handleInterrupt();

volatile bool interruptFlag = false;

const int analogPin = A0; // ADC pin for reading battery voltage
float V = 0; // Store battery percentage
const int NUMBER_MODE = 1;
const int SYMBOL_MODE = 2;

LiquidCrystal_I2C lcd(0x27, 16, 2);
int state;
float Battery;

byte blank[8] = {
  0b11111,
  0b11111,
  0b11111,
  0b11111,
  0b11111,
  0b11111,
  0b11111,
  0b11111
};

void setup() {
  Serial.begin(115200);
  lcd.init();
  lcd.clear();
  lcd.backlight();
  state = SYMBOL_MODE;
  pinMode(BTN_PIN, INPUT_PULLUP);
  lcd.createChar(0, blank);
  attachInterrupt(digitalPinToInterrupt(BTN_PIN), handleInterrupt, FALLING); // Interrupt on button press
}

// Interrupt service routine
void handleInterrupt() {
  interruptFlag = true;
}

void loop() {
  // Check interrupt flag
  if (interruptFlag) {
    interruptFlag = false;
    // Toggle between states
    state = (state == NUMBER_MODE) ? SYMBOL_MODE : NUMBER_MODE;
  }

  // Perform operations based on the state
  if (state == NUMBER_MODE) {
    Serial.print(state);
    int adcValue = 800; // Simulated ADC value
    Battery = (adcValue * 100) / 1023.0; // Calculate battery percentage
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Battery");
    Serial.print(Battery);
    lcd.setCursor(0, 1);
    lcd.print(Battery);
    lcd.setCursor(7, 1);
    lcd.print("%");
    Serial.println(" %");
    delay(3000);
  } else if (state == SYMBOL_MODE) {
    int adcValue = 512; // Simulated ADC value
    Battery = (adcValue * 100) / 1023.0; // Calculate battery percentage
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Bat :");
    
    // Display battery status text
    if (Battery > 80) {
      lcd.setCursor(6, 0);
      lcd.print("GOOD");
    } else if (Battery > 20 && Battery <= 80) {
      lcd.setCursor(6, 0);
      lcd.print("OK");
    } else if (Battery >= 0 && Battery <= 20) {
      lcd.setCursor(6, 0);
      lcd.print("LOW");
    }

    // Calculate the number of blocks to display based on battery level
    int blocks = (Battery * 16) / 100; // 16 blocks on the LCD line

    // Display the blocks
    for (int i = 0; i < blocks; i++) {
      lcd.setCursor(i, 1);
      lcd.write(0); // Display full block
    }
    
    delay(1000);
  }
}