﻿#include <avr/io.h>
#define F_CPU 12000000UL 

#include <util/delay.h>
#include <util/atomic.h>
#include <avr/builtins.h>

#define Btn_Down 1
#define Btn_Up 2
#define Btn_Neytral 3
#define Btn_Rear 4
#define Off 0
#define On 1
// Декларация глобальных переменных
uint8_t tiks;
uint8_t Cur_btn;
uint8_t Pressed;
uint8_t _Gear;
uint8_t _Button;
unsigned char read_key (void);
const unsigned char Gears[7] ={0x00,//Нейтраль
							 0x15,//Первая
							 0x16,//Вторая
							 0x18,//Третья
							 0x27,//Четвёртая
							 0x1f,/*Пятая*/
							 0x23/*Задняя*/};
// Timer 0 overflow interrupt service routine
ISR(SIG_OVERFLOW0){
	tiks++;
	if ((_Button==Off)&&(tiks>50)){
		tiks=0;
		_Button=On;
		TCCR0=0x00;	
	}
}
unsigned char read_key (void){
	Pressed=0;
	Cur_btn = 0;			
	Pressed =(PINB & 0b00011101);
	if (~Pressed & 0b00000001)	Cur_btn =	Btn_Rear;		
	if (~Pressed & 0b00010000)	Cur_btn=	Btn_Down;	
	if (~Pressed & 0b00001000)	Cur_btn =	Btn_Up;				
	if (~Pressed & 0b00000100)	Cur_btn =	Btn_Neytral;				
//--------------------------------------------------------	
	if (Cur_btn>0)
	{	_Button=Off;
		TCNT0=0x00;
		TCCR0=0x05;
		if ((Cur_btn == Btn_Down)&&(_Gear>0)&&(_Gear<6))					_Gear--;
		if ((Cur_btn ==	Btn_Up) && (_Gear<5))								_Gear++;
		if (Cur_btn == Btn_Neytral && ( _Gear==2 || _Gear==1 || _Gear==6))	_Gear=0;
		if ((Cur_btn == Btn_Rear) && ( _Gear==0))							_Gear=6;
	}
	return 0;
}	



int main(void){//Begin
// Timer(s)/Counter(s) Interrupt(s) initialization
	TIMSK=0x01;
// Timer/Counter 0 initialization
// Clock source: System Clock
// Clock value: 11.719 kHz
	TCCR0=0x00;
	TCNT0=0x00; 
//Ports_______________________________________________
	DDRD = 0xFF;
	DDRB = 0x00;
	PINB= 0x1D; //для симулятора подтяжка к плюсу
//Enable buttons__
	_Button=On;
	tiks=0;
//Global interrupts enable
	sei ();


//Основной цикл****************************************	
	while(1){//Begin while
		if (_Button== On) read_key();
		if (Cur_btn>0){
			PORTD = Gears[_Gear];
			if ((_Gear>0)&&(_Gear<6)){
				PORTD |=0x80;
				//_delay_ms(5);
				PORTD &=(0x7F);
			}
		}				
	}//end while
}//END 