#include <LiquidCrystal.h>

// Define the pins for the IR sensor and LCD display
const int irPin = 2;
const int rsPin = 12;
const int enPin = 11;
const int d4Pin = 5;
const int d5Pin = 4;
const int d6Pin = 3;
const int d7Pin = 2;

// Define variables for storing RPM, battery voltage, and battery percentage
volatile int rpm;
float voltage;
int percentage;

// Define objects for the LCD display and timer
LiquidCrystal lcd(rsPin, enPin, d4Pin, d5Pin, d6Pin, d7Pin);
unsigned long previousMillis = 0;
const long interval = 1000;

void setup() {
  // Set up the IR sensor pin as an input
  pinMode(irPin, INPUT);

  // Set up the LCD display
  lcd.begin(16, 2);

  // Initialize the variables
  rpm = 0;
  voltage = 0.0;
  percentage = 0;

  // Set up the timer for updating the LCD display
  previousMillis = millis();
}

void loop() {
  // Measure the RPM using the IR sensor
  int sensorValue = digitalRead(irPin);
  if (sensorValue == HIGH) {
    rpm++;
  }

  // Calculate the battery voltage and percentage
  voltage = (analogRead(A0) * 5.0) / 1024.0;
  percentage = (int)((voltage - 3.5) * 100.0 / 1.5);

  // Update the LCD display once per second
  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;

    // Display the RPM, battery voltage, and battery percentage on the LCD
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("RPM:");
    lcd.print(rpm);
    lcd.setCursor(0, 1);
    lcd.print("V:");
    lcd.print(voltage);
    lcd.print("   %:");
    lcd.print(percentage);
    lcd.print("%");
    
    // Reset the RPM counter
    rpm = 0;
  }
}