#include <avr/io.h>
#include <avr/sleep.h>    
#include <avr/interrupt.h>


#define MaxLVL 127
#define MaxDLY 200
#define MinDLY 50
#define StartDLY 80
#define PWM_Mode 0b11000011;                        // Яркость != 0, включить ШИМ

volatile uint8_t _counter, _delay, _light_lvl;
volatile uint8_t Key;
volatile int8_t  _step;
volatile uint8_t _mode;
volatile uint16_t _cnt16;

#ifndef cbi
  #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= -_BV(bit))
#endif
#ifndef sbi                                
  #define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif


void setup() {
  cbi(ADCSRA, ADEN); // ADC off
  sbi(ACSR,    ACD); // Disable analog comparator
  pinMode(0, OUTPUT);
  pinMode(1, OUTPUT);
  pinMode(2, INPUT);
  digitalWrite(2, HIGH);

  cli();

  OCR0A  =  0;                 // Стартовое значение скважности                                  //
  TCCR0A = PWM_Mode;           // Выбор режима ШИМ - 1 канала (PB0 )                             //
  TCCR0B = 0b00000010;         // установка делителя (выбор на частоту CLK/8)                    //
  TIMSK |= (1 << OCIE0B);                                                                        //
  OCR0B  = 255;                                                                                  //

  Key         = 0;
  _step       = 2;
  _counter    = 0;
  _delay      = StartDLY;
  _light_lvl  = MaxLVL;
  _cnt16      = 0;
  sei();
}

ISR (TIM0_COMPB_vect)   // обработчик прерывания таймера
{
  if ( ++_counter >= _delay ){                         //  
      digitalWrite(1, HIGH);
      digitalWrite(1, LOW);
      if      ( OCR0A > _light_lvl ) OCR0A--;
      else if ( OCR0A < _light_lvl ) OCR0A++;          //  Коррекция ШИМ относительно уровня яркости
      _counter=0;
      if  ( OCR0A != _light_lvl ) return;
      Key=!digitalRead(2);
      if (!Key){
        if ((_light_lvl>0)&&(_light_lvl<=MaxLVL)) _cnt16=0;
        _step=abs(_step);
      }
      if ((Key)&&(_light_lvl==0)&&(_cnt16<200)) {
        Key=0;
        TCCR0A = 0b00000000;                          // Яркость  = 0, отключить ШИМ
        PORTB |=1;
      }
      if ((!Key)&&(_light_lvl>MaxLVL)&&(_cnt16>10000)) {
        _light_lvl = MaxLVL;
        _delay     = MaxDLY;
      } else _delay= MinDLY;
      if (Key) {
        TCCR0A = PWM_Mode;                            // Яркость != 0, включить ШИМ
        _light_lvl += _step;
        if (_light_lvl < -_step)      {_step=-_step;_light_lvl=0;_cnt16=0;}
        if (_light_lvl > (255-_step)) {_step=-_step;_light_lvl=255+_step;}
      }
      _cnt16++;
      
  }
}

void loop() {
}
