// ADC interrupt
// https://wokwi.com/arduino/projects/305937248748044864
#define led1 13
#define led2 5
const byte adcPin = 0;
volatile int adcReading;
volatile boolean adcDone;
boolean adcStarted;
void setup(void) {
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
Serial.begin(115200);
ADCSRA = bit (ADEN); // turn ADC on
ADCSRA |= bit (ADPS0) | bit (ADPS1) | bit (ADPS2); // Prescaler of 128
ADMUX = bit (REFS0) | (adcPin & 0x07); // AVcc and select input port
// initialize timer1
noInterrupts(); // disable all interrupts
TCCR1A = 0;
TCCR1B = 0;
TCNT1 = 3036; // preload timer 65536-16MHz/256/1Hz
TCCR1B |= (1 << CS12); // 256 prescaler
TIMSK1 |= (1 << TOIE1); // enable timer overflow interrupt
interrupts(); // enable all interrupts
}
ISR(TIMER1_OVF_vect)
{
digitalWrite(led1, digitalRead(led1)^1);
}
// ADC complete ISR
ISR (ADC_vect)
{
adcReading = ADC;
adcDone = true;
} // end of ADC_vect
void loop() {
// if last reading finished, process it
if (adcDone)
{
adcStarted = false;
// do something with the reading, for example, print it
Serial.println (adcReading);
delay (500);
adcDone = false;
}
// if we aren't taking a reading, start a new one
if (!adcStarted)
{
adcStarted = true;
// start the conversion
ADCSRA |= bit (ADSC) | bit (ADIE);
}
}