#include <LiquidCrystal_I2C.h>
#include <avr/interrupt.h>
LiquidCrystal_I2C lcd(0x27, 16, 2); // Adjust address to your LCD
volatile uint16_t adcValue = 0; //uint16_t – 16-bit unsigned integer Initialized at 0;
volatile bool conversionComplete = false; //bool – initialize as false
volatile float lastVoltage = -1.0; //Stores the last measured voltage value.
volatile float voltage = 0.0; //Initializes voltage variable at 0.0V
void print_voltage(){ //Function to print Voltage
lcd.clear(); //Clear the lcd
lcd.print(voltage); //Print value held in voltage
lcd.print(" V"); //Print " V" after voltage value
}
void setup() { //void setup() - function to Initialize the LCD, configure the ADC, and starts first ADC conversion
// Initialize LCD
lcd.init();
lcd.backlight();
lcd.setCursor(0, 0);
// Initialize ADC
ADCSRA = 0xCF; //This line does the same thing as the above lines
sei(); // Enable global interrupts
}
ISR(ADC_vect) {
adcValue = ADC; // Read the ADC value
conversionComplete = true; // Set the conversion complete flag
}
void startConversion() {
ADCSRA |= 0x40;
}
void loop() {
if (conversionComplete) {
voltage = adcValue * (5.0 / 1023.0); // Convert ADC value to voltage
if (voltage != lastVoltage) { // Update the display only if the voltage has changed
lastVoltage = voltage;
print_voltage();
}
startConversion(); // Start a new conversion
}
}