#include <xc.h>
#include <avr/io.h>
#include <util/delay.h>

#include <avr/interrupt.h>
#include <avr/sleep.h>
#include <util/atomic.h>
#include <avr/wdt.h>

//reference: https://www.avrfreaks.net/forum/sample-project-attiny10


// Wake up by WDT interrupt.
// Don't need to do anything here but (auto-) clearing the interrupt flag.
EMPTY_INTERRUPT(WDT_vect);

/*
  Delay in powerdown mode. Wake up by watchdog interrupt.
 */
void delay_power_down_wdt(uint8_t wdto)
{
    wdt_reset();
    wdt_enable(wdto);
    WDTCSR |= (1<<WDIE);
    //so far (with 128Khz clk) this sleep will be about 30-40 seconds.
    
    //(however, I'll add the below to)
    //adjust sleep speed here:
    
    // 0110 is 1hz at 128KHz
    //WDTCSR |= (0<< WDP3);
    //WDTCSR |= (1<< WDP2);
    //WDTCSR |= (1<< WDP1);
    //WDTCSR |= (0<< WDP0);
    
    set_sleep_mode(SLEEP_MODE_PWR_DOWN);
    sleep_enable();
    // Make sure interrups are enabled and the I flag is restored
    NONATOMIC_BLOCK(NONATOMIC_RESTORESTATE)
    {
	sleep_cpu();
	wdt_disable();
    }
    sleep_disable();
}


int main(void)
{
    
    sei();
    
    //Write CCP (to enable changing clock)
    CCP = 0xD8;
    //change CLK to 128KHz
    CLKMSR = 0b01;
    
    //In order to use the lowest sleep mode, we must either
    //use watchdog or pin change interrupt to wake ic.
    //here i will use watchdog
    
   
    
    // PB2 change to output
    DDRB = 1<<2;

    while(1)
    {
	// Toggle PB2 Hi/Low
	PINB = 1<<2;
	//_delay_ms(500);
    delay_power_down_wdt(WDTO_1S);
    }
}

