#define Adcsra (*((volatile uint8_t*)0x7A))
#define Admux  (*((volatile uint8_t*)0x7C))
#define Aden  7
#define Adps0 0
#define Adps1 1
#define Adps2 2
#define Adsc  6
#define Refs0 6
#define WDTCSR  (*(volatile uint8_t*)0x60)  // Watchdog Timer Control Register
#define MCUSR   (*(volatile uint8_t*)0x54)  // MCU Status Register

// WDTCSR Bits
#define WDE     3     // Watchdog Enable
#define WDIE    6     // Watchdog Interrupt Enable
#define WDP0    0     // Watchdog Prescaler bit 0
#define WDP1    1     // Watchdog Prescaler bit 1
#define WDP2    2     // Watchdog Prescaler bit 2
#define WDP3    5     // Watchdog Prescaler bit 3

void setup_watchdog() {
    // Clear WDRF in MCUSR (Watchdog Reset Flag)
    MCUSR &= ~(1 << 3);

    // Write logical one to WDE and WDCE to enable changes to WDTCSR
    WDTCSR |= (1 << WDE) | (1 << 4);
    WDTCSR = (1 << WDE) | (1 << WDP3) | (1 << WDP0);  // Set timeout to 8s
}
void reset_wtd() {
    // Reset the watchdog timer (WDR)
    asm volatile("wdr");
}

void timer1_init() {
    // Set Timer1 for 1-second intervals
    TCCR1B |= (1 << WGM12);          // Configure timer in CTC mode
    OCR1A = 15624;                    // Set compare value for 1Hz (1 sec) with 8MHz clock and 1024 prescaler
    TCCR1B |= (1 << CS12) | (1 << CS10); // Set prescaler to 1024
    TIMSK1 |= (1 << OCIE1A);          // Enable Timer1 Compare A interrupt
    sei();
}

ISR(TIMER1_COMPA_vect) {
    Adcsra |= (1 << Adsc);
}

void adc_init(){
  uint8_t channel = 1;
  Admux |= (1<<Refs0)|(Admux & 0xF0)|(channel & 0x0F);
  Adcsra |= (1<<Aden)|(1<<Adps0)|(1<<Adps1)|(1<<ADIE);
  sei();
}


ISR(ADC_vect){
  float value = ADC;
  Serial.println(value);
  //Adcsra |= (1 << Adsc);
}

int main(){
  timer1_init();
  adc_init();
  setup_watchdog();
  Serial.begin(9600);
  while(1){
    reset_wtd();
  }
}