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

// 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 led1();
void led2();
void led3();
void led4();
void led5();
void offled1();
void offled2();
void offled3();
void offled4();
void offled5();
void delays(volatile long i){
    i*=1000;
    while(i--){}
}
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 adc_init(){
    Adcsra |= (1<<Aden)|(1<<Adps0)|(1<<Adps1)|(1<<Adps2);
    Admux |= (1<<Adsc);
}

int main(){
  setup_watchdog();
  Serial.begin(115200);
  adc_init();
  uint8_t step = 0;
  uint8_t mode = 1;
  while(1){
    uint8_t channel = 0;

    Admux = (Admux & 0xF0)|(channel & 0x0F); 
    Adcsra |= (1<<6);
    while (Adcsra & (1 << 6));
    uint16_t value = ADC;
    Serial.println(value);

    if(value>100 && value<200){
      step = 0;
      mode = 0;
    }else if(value>200 && value<400){
      step = 1;
    }else if(value>400 && value<600){
      step = 2;
    }else if(value>600 && value<800){
      step = 3;
    }else if(value>800 && value<900){
      step = 4;
    }else if(value > 900){
      mode = 1;
    }
    if(mode == 0){
      PORTB |= (1<<step);
    }else if(mode == 1){
      PORTB &= ~(1<<step);
    }
    reset_wtd();
  }
}