#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <avr/interrupt.h>
LiquidCrystal_I2C lcd(0x27, 16, 2); // Adjust address to your LCD
volatile uint16_t adcValue = 0;
volatile bool conversionComplete = false;
volatile float lastVoltage = -1.0;
volatile float voltage = 0.0;
void print_voltage(){
lcd.clear();
lcd.print(voltage);
lcd.print(" V");
}
void setup() {
// Initialize LCD
lcd.init();
lcd.backlight();
lcd.setCursor(0, 0);
// lcd.print("Voltage: ");
// Initialize ADC
ADMUX = (1 << REFS0); // Reference Voltage: AVcc, Input Channel: ADC0
ADCSRA = (1 << ADEN) | (1 << ADIE) | (1 << ADPS2) | (1 << ADPS1) | (1 << ADPS0); // Enable ADC, Enable Interrupt, Prescaler: 128
sei(); // Enable global interrupts
startConversion(); // Start the first conversion
voltage = adcValue * (5.0 / 1023.0); // Convert ADC value to voltage
print_voltage();
}
ISR(ADC_vect) {
adcValue = ADC; // Read the ADC value
conversionComplete = true; // Set the conversion complete flag
}
void startConversion() {
ADCSRA |= (1 << ADSC); // Start the ADC conversion
}
void loop() {
if (conversionComplete) {
conversionComplete = false; // Reset the flag
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
}
}