// blink sketch
// anders haldin
// 16/03 2015
// licens CC

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


#define LED1_ON (PORTA |= (1<<PA0))
#define LED1_OFF (PORTA &= ~(1<<PA0))

#define LED2_ON (PORTA |= (1<<PA1))
#define LED2_OFF (PORTA &= ~(1<<PA1))

#define K1 ((PINA & (1<<PINA7)) == 0)
#define K2 ((PINB & (1<<PINB2)) == 0)


void delay(int ms)
{
	for(ms = ms/8; ms > 0 ; ms--)
		_delay_ms(1);
}

const int difficulty= 500; //the smaller the harder, but not lower than 63, cuz your eyes could not recognize the blinks then
const int buttonReactTime= 400; // the smaller, the faster you can input your answer. 

int arrange [100]={0};
int i, n, input = 0,count = 0;
unsigned long RandomSeed = 0;

void Blink(int t, int n);
int main()
{

	DDRA &= ~(1<<DDA7);  //K1, set as input
	DDRB &= ~(1<<DDB2);  //K2

	DDRA |= (1<<DDA0);  //LED1, set IO as output.
	DDRA |= (1<<DDA1);  //LED2


	LED1_ON;
	LED2_ON;
	while(!(K1&&K2))
	{
		RandomSeed++;
	}


	LED1_OFF;
	LED2_OFF;
	delay(1000);

	while(1)
	{
		arrange[count++] = (RandomSeed>>(count+1))%2+1;  // the result will be 1 or 2...
		
		//LEDs Display
		for(n = 0; arrange[n] != 0; n++)
		{
			if(arrange[n] == 1) //NOT ZERO.. 
			{
				LED2_OFF;
				LED1_ON;
			}
			else
			{
				LED1_OFF;
				LED2_ON;
			}

			delay(difficulty);

			LED1_OFF;
			LED2_OFF;
			delay(difficulty*0.8);
		}



		//Wait for answer by keys.
		n = 0;
		while(n < count)
		{

			while(!(K1||K2));  //Wait until one of the keys been pressed
			delay(5);
			
			if(K1)
				input = 2;
			else if(K2)
				input = 1;


			if( (arrange[n] == input) )//answer correct!
			{
				if(arrange[n]  == 1)
				{
					LED2_OFF;
					LED1_ON;		
				}
				else if(arrange[n]  == 2)
				{
					LED1_OFF;
					LED2_ON;
				}

				delay(difficulty*0.7);

				LED2_OFF;
				LED1_OFF;
				delay(difficulty*0.7);
			}

			else//faild
			{
				Blink(50,20);
				LED2_ON;
				LED1_ON;
				while(1);
			}

			n++;

		}

		delay(difficulty*1.5);

	}

	

}//closeing main


void Blink(int t, int n)
{
	while(n--)
	{
		LED2_ON;
		LED1_OFF;
		delay(t);
		LED1_ON;
		LED2_OFF;
		delay(t);

	}
	LED1_OFF;
	LED2_OFF;

}
