/*
Doku für Tiny: https://ww1.microchip.com/downloads/en/devicedoc/atmel-2586-avr-8-bit-microcontroller-attiny25-attiny45-attiny85_datasheet.pdf

  1  PB5(PCINT5/ADC0/dW)
	PCINT5: Pin Change Interrupt 0, Source5
  RESET: Reset Pin
  ADC0: ADC Input Channel 0
  dW: debug WIRE I/O

  2 PB3(PCINT3/XTAL1/CLKI/ADC3)
  PCINT3: Pin Change Interrupt 0, Source3
  XTAL1: Crystal Oscillator Pin1
  CLKI: External Clock Input
  ADC3: ADC Input Channel 3

  3 PB4 (PCINT4/XTAL2/CLKO/OC1B/ADC2)
  PCINT4: Pin Change Interrupt 0, Source 4
  XTAL2: Crystal Oscillator Pin 2
  CLKO: System Clock Output
  OC1B: Timer/Counter1 Compare Match B Output
  ADC2: ADC Input Channel 2

  4 GND
	Ground Pin

  5 PB0(MOSI/DI/SDA/AIN0/OC0A/AREF/ PCINT0)
  MOSI: SPI Master Data Output / Slave Data Input
  DI: USI Data Input (Three Wire Mode)
  SDA: USI Data Input (Two Wire Mode)
  AIN0: Analog Comparator, Positive Input
  OC0A: Timer/Counter0 Compare Match A output
  AREF: External Analog Reference
  PCINT0: Pin Change Interrupt 0, Source 0

  6 PB1(MISO/D0/AIN1/OC0B/OC1A/ PCINT1)
  MISO: SPI Master Data Input / Slave Data Output
  DO: USI Data Output (Three Wire Mode)
  AIN1: Analog Comparator, Negative Input
  OC0B: Timer/Counter0 Compare Match B Output
  OC1A: Timer/Counter1 Compare Match A Output
  PCINT1: Pin Change Interrupt 0, Source 1

  7 PB2(SCK/USCK/SCL/ADC1/T0/INT0/ PCINT2)
  SCK: Serial Clock Input
  USCK: USI Clock (Three Wire Mode)
  SCL: USI Clock (Two Wire Mode)
  ADC1: ADC Input Channel 1
  T0: Timer/Counter0 Clock Source
  INT0: External Interrupt 0 Input
  PCINT2: Pin Change Interrupt 0, Source 2

  8 VCC
	Supply Voltage Pin
*/

/*
WDTCR – Watchdog Timer Control Register

WDIF  WDIE  WDP3  WDCE  WDE   WDP2  WDP1  WDP0    //WDTCR
7     6     5     4     3     2     1     0

Bit 7 – WDIF: Watchdog Timeout Interrupt Flag
This bit is set when a time-out occurs in the Watchdog Timer and the Watchdog Timer is configured for interrupt.
WDIF is cleared by hardware when executing the corresponding interrupt handling vector. Alternatively, WDIF is
cleared by writing a logic one to the flag. When the I-bit in SREG and WDIE are set, the Watchdog Time-out Inter-
rupt is executed

Bit 6 – WDIE: Watchdog Timeout Interrupt Enable
When this bit is written to one, WDE is cleared, and the I-bit in the Status Register is set, the Watchdog Time-out
Interrupt is enabled. In this mode the corresponding interrupt is executed instead of a reset if a timeout in the
Watchdog Timer occurs.
If WDE is set, WDIE is automatically cleared by hardware when a time-out occurs. This is useful for keeping the
Watchdog Reset security while using the interrupt. After the WDIE bit is cleared, the next time-out will generate a
reset. To avoid the Watchdog Reset, WDIE must be set after each interrupt

WDE WDIE        Watchdog Timer State Action on Time-out
0   0           Stopped None
0   1           Running Interrupt
1   0           Running Reset
1   1           Running Interrup

Bit 4 – WDCE: Watchdog Change Enable
This bit must be set when the WDE bit is written to logic zero. Otherwise, the Watchdog will not be disabled. Once
written to one, hardware will clear this bit after four clock cycles. Refer to the description of the WDE bit for a
Watchdog disable procedure. This bit must also be set when changing the prescaler bits. 

Bit 3 – WDE: Watchdog Enable
When the WDE is written to logic one, the Watchdog Timer is enabled, and if the WDE is written to logic zero, the
Watchdog Timer function is disabled. WDE can only be cleared if the WDCE bit has logic level one. To disable an
enabled Watchdog Timer, the following procedure must be followed:
1. In the same operation, write a logic one to WDCE and WDE. A logic one must be written to WDE even
though it is set to one before the disable operation starts.
2. Within the next four clock cycles, write a logic 0 to WDE. This disables the Watchdog.
In safety level 2, it is not possible to disable the Watchdog Timer, even with the algorithm described above.


Bits 5, 2:0 – WDP[3:0]: Watchdog Timer Prescaler 3, 2, 1, and 0
The WDP[3:0] bits determine the Watchdog Timer prescaling when the Watchdog Timer is enabled. The different
prescaling values and their corresponding Timeout Periods are shown in Table

Watchdog Timer Prescale Select
WDP3 | WDP2 | WDP1 | WDP0 | Number of WDT OscillatorCycles | Typical Time-out at VCC = 5.0V
0      0      0      0      2K (2048) cycles                 16 ms
0      0      0      1      4K (4096) cycles                 32 ms
0      0      1      0      8K (8192) cycles                 64 ms
0      0      1      1      16K (16384) cycles               0.125 s
0      1      0      0      32K (32764) cycles               0.25 s
0      1      0      1      64K (65536) cycles               0.5 s
0      1      1      0      128K (131072) cycles             1.0 s
0      1      1      1      256K (262144) cycles             2.0 s
1      0      0      0      512K (524288) cycles             4.0 s
1      0      0      1      1024K (1048576) cycles           8.0 s




Active Clock Domains and Wake-up Sources in the Different Sleep Modes
                     |    Active Clock Domains                          | Oscillators               | Wake-up Sources
Sleep Mode           | clk CPU | clk FLASH | clk IO | clk ADC | clk PCK | Main Clock Source Enabled | INT0 and Pin Change | SPM/EEPROM Ready | USI Start Condition | ADC | Other I/O | Watchdog Interrupt
Idle                 |         |           |  X     |  X      |  X      |  X                        |  X                  |  X               |  X                  | X   |  X        |  X
ADC Noise Reduction  |         |           |        |  X      |         |  X                        |  X(1)               |  X               |  X                  | X   |  X
Power-down           |         |           |        |         |         |                           |  X(1)               |                  |  X                  |     |  X


To enter any of the three sleep modes, the SE bit in MCUCR must be written to logic one and a SLEEP instruction
must be executed. The SM[1:0] bits in the MCUCR Register select which sleep mode (Idle, ADC Noise Reduction
or Power-down) will be activated by the SLEEP instruction. See Table 7-2 for a summary.
If an enabled interrupt occurs while the MCU is in a sleep mode, the MCU wakes up. The MCU is then halted for
four cycles in addition to the start-up time, executes the interrupt routine, and resumes execution from the instruc-
tion following SLEEP. The contents of the Register File and SRAM are unaltered when the device wakes up from
sleep. If a reset occurs during sleep mode, the MCU wakes up and executes from the Reset Vector.
Note that if a level triggered interrupt is used for wake-up the changed level must be held for some time to wake up
the MCU (and for the MCU to enter the interrupt service routine). See “External Interrupts” on page 49 for details.

Idle Mode
When the SM[1:0] bits are written to 00, the SLEEP instruction makes the MCU enter Idle mode, stopping the CPU
but allowing Analog Comparator, ADC, USI, Timer/Counter, Watchdog, and the interrupt system to continue oper-
ating. This sleep mode basically halts clk CPU and clk FLASH , while allowing the other clocks to run.
Idle mode enables the MCU to wake up from external triggered interrupts as well as internal ones like the Timer
Overflow. If wake-up from the Analog Comparator interrupt is not required, the Analog Comparator can be powered
down by setting the ACD bit in “ACSR – Analog Comparator Control and Status Register” on page 120. This will
reduce power consumption in Idle mode. If the ADC is enabled, a conversion starts automatically when this mode
is entered.

ADC Noise Reduction Mode
When the SM[1:0] bits are written to 01, the SLEEP instruction makes the MCU enter ADC Noise Reduction mode,
stopping the CPU but allowing the ADC, the external interrupts, and the Watchdog to continue operating (if
enabled). This sleep mode halts clk I/O, clk CPU , and clk FLASH , while allowing the other clocks to run.
This improves the noise environment for the ADC, enabling higher resolution measurements. If the ADC is
enabled, a conversion starts automatically when this mode is entered. Apart form the ADC Conversion Complete
interrupt, only an External Reset, a Watchdog Reset, a Brown-out Reset, an SPM/EEPROM ready interrupt, an
external level interrupt on INT0 or a pin change interrupt can wake up the MCU from ADC Noise Reduction mode.

Power-down Mode
When the SM[1:0] bits are written to 10, the SLEEP instruction makes the MCU enter Power-down mode. In this
mode, the Oscillator is stopped, while the external interrupts, the USI start condition detection and the Watchdog
continue operating (if enabled). Only an External Reset, a Watchdog Reset, a Brown-out Reset, USI start condition
interupt, an external level interrupt on INT0 or a pin change interrupt can wake up the MCU. This sleep mode halts
all generated clocks, allowing operation of asynchronous modules only.

Software BOD Disable
When the Brown-out Detector (BOD) is enabled by BODLEVEL fuses (see Table 20-4 on page 148), the BOD is
actively monitoring the supply voltage during a sleep period. In some devices it is possible to save power by dis-
abling the BOD by software in Power-Down sleep mode. The sleep mode power consumption will then be at the
same level as when BOD is globally disabled by fuses.
If BOD is disabled by software, the BOD function is turned off immediately after entering the sleep mode. Upon
wake-up from sleep, BOD is automatically enabled again. This ensures safe operation in case the V CC level has
dropped during the sleep period.
When the BOD has been disabled, the wake-up time from sleep mode will be the same as that for wakeing up from
RESET. The user must manually configure the wake up times such that the bandgap reference has time to start
and the BOD is working correctly before the MCU continues executing code. See SUT[1:0] and CKSEL[3:0] fuse
bits in table “Fuse Low Byte” on page 149
BOD disable is controlled by the BODS (BOD Sleep) bit of MCU Control Register, see “MCUCR – MCU Control
Register” on page 37. Writing this bit to one turns off BOD in Power-Down, while writing a zero keeps the BOD
active. The default setting is zero, i.e. BOD active.
Writing to the BODS bit is controlled by a timed sequence and an enable bit, see “MCUCR – MCU Control Regis-
ter” on page 37.


Minimizing Power Consumption
There are several issues to consider when trying to minimize the power consumption in an AVR controlled system.
In general, sleep modes should be used as much as possible, and the sleep mode should be selected so that as
few as possible of the device’s functions are operating. All functions not needed should be disabled. In particular,
the following modules may need special consideration when trying to achieve the lowest possible power
consumption


Analog to Digital Converter
If enabled, the ADC will be enabled in all sleep modes. To save power, the ADC should be disabled before entering
any sleep mode. When the ADC is turned off and on again, the next conversion will be an extended conversion.
Refer to “Analog to Digital Converter” on page 122 for details on ADC operation.


Analog Comparator
When entering Idle mode, the Analog Comparator should be disabled if not used. When entering ADC Noise
Reduction mode, the Analog Comparator should be disabled. In the other sleep modes, the Analog Comparator is
automatically disabled. However, if the Analog Comparator is set up to use the Internal Voltage Reference as
input, the Analog Comparator should be disabled in all sleep modes. Otherwise, the Internal Voltage Reference will
be enabled, independent of sleep mode. Refer to “Analog Comparator” on page 119 for details on how to configure
the Analog Comparator.


Brown-out Detector
If the Brown-out Detector is not needed in the application, this module should be turned off. If the Brown-out Detec-
tor is enabled by the BODLEVEL Fuses, it will be enabled in all sleep modes, and hence, always consume power.
In the deeper sleep modes, this will contribute significantly to the total current consumption. See “Brown-out Detec-
tion” on page 41 and “Software BOD Disable” on page 35 for details on how to configure the Brown-out Detector.

Internal Voltage Reference
The Internal Voltage Reference will be enabled when needed by the Brown-out Detection, the Analog Comparator
or the ADC. If these modules are disabled as described in the sections above, the internal voltage reference will be
disabled and it will not be consuming power. When turned on again, the user must allow the reference to start up
before the output is used. If the reference is kept on in sleep mode, the output can be used immediately. Refer to
“Internal Voltage Reference” on page 42 for details on the start-up time.

Watchdog Timer
If the Watchdog Timer is not needed in the application, this module should be turned off. If the Watchdog Timer is
enabled, it will be enabled in all sleep modes, and hence, always consume power. In the deeper sleep modes, this
will contribute significantly to the total current consumption. Refer to “Watchdog Timer” on page 42 for details on
how to configure the Watchdog Timer.

Port Pins
When entering a sleep mode, all port pins should be configured to use minimum power. The most important thing
is then to ensure that no pins drive resistive loads. In sleep modes where both the I/O clock (clkI/O) and the ADC
clock (clkADC) are stopped, the input buffers of the device will be disabled. This ensures that no power is consumed
by the input logic when not needed. In some cases, the input logic is needed for detecting wake-up conditions, and
it will then be enabled. Refer to the section “Digital Input Enable and Sleep Modes” on page 57 for details on which
pins are enabled. If the input buffer is enabled and the input signal is left floating or has an analog signal level close
to V CC /2, the input buffer will use excessive power.
For analog input pins, the digital input buffer should be disabled at all times. An analog signal level close to VCC /2
on an input pin can cause significant current even in active mode. Digital input buffers can be disabled by writing to
the Digital Input Disable Register (DIDR0). Refer to “DIDR0 – Digital Input Disable Register 0” on page 121 for
details.
*/
//--------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------


#include <avr/sleep.h>
#include <avr/wdt.h>

#define LED 4

volatile boolean on = true;

//--------------------------------------------------------------------------------------------
//      InternetServciceRoutine
//--------------------------------------------------------------------------------------------

ISR(WDT_vect){
  on = !on;   //An-/Aus
  wdt_disable();
}

//--------------------------------------------------------------------------------------------
//      Watchdog enable
//--------------------------------------------------------------------------------------------
void myWatchdogEnable(const byte interval){

  noInterrupts();

  wdt_reset();

  MCUSR = 0;                        // reset various flags
  WDTCR |= 0b00011000;              // see docs, set WDCE, WDE
  WDTCR =  0b11000000  | interval;  // set WDIE, and appropriate delay
    // sleep bit patterns:
    //  1 second:  0b000110
    //  2 seconds: 0b000111
    //  4 seconds: 0b100000
    //  8 seconds: 0b100001

  ADCSRA &= ~_BV(ADEN);

  set_sleep_mode (SLEEP_MODE_IDLE);
  sleep_bod_disable();
  interrupts();
  sleep_mode();

}
//--------------------------------------------------------------------------------------------
//      Setup
//--------------------------------------------------------------------------------------------
void setup(){
  pinMode (LED, OUTPUT);
}

//--------------------------------------------------------------------------------------------
//      Main
//--------------------------------------------------------------------------------------------

void loop() {

  digitalWrite (LED, on);
  if (WDTCR & (1 << WDIE)) { //still waiting for WDT interrupts, simply go sleep
    sleep_bod_disable();
    sleep_mode();
  }
  else { //WDT interrupt is disabled (from WDT ISR)
    myWatchdogEnable (0b100000);   //  second
    // sleep bit patterns:
    //  1 second:  0b000110
    //  2 seconds: 0b000111
    //  4 seconds: 0b100000
    //  8 seconds: 0b100001
  }
}



ATTINY8520PU