#include <inttypes.h> 
#include <io.h> 
#include <sig-avr.h> 
#include <interrupt.h> 
#include <stdlib.h> 

// назначение определений для удобства работы с периферией 
#define OUT PORTA 
#define MOTOR_F  PA1 
#define MOTOR_B  PA2 
#define TURN_R   PA3  
#define TURN_L   PA4 

#define IN PIND 
#define LIGHT_R  PD0 
#define LIGHT_L  PD1 
#define BUMPER_F PD2 
#define BUMPER_B PD3 


#define F_CPU 8000000
#define K_DELAY_10ms	F_CPU/600
void Delay_10ms(unsigned char t) {
  unsigned int i;
  if (t==0) return;
  while (t--) for(i=0;i<K_DELAY_10ms; i++);
}

unsigned char p[7][7] = { 
{14,   43,   57,   71,   86,   93,   100}, 
{7,   43,   71,   100,   100,   100,   100}, 
{7,   50,   93,   100,   100,   100,   100}, 
{7,   50,   57,   100,   100,   100,   100}, 
{29,   29,   29,   29,   57,   79,   100}, 
{36,   36,   36,   36,   71,   93,   100}, 
{36,   36,   36,   36,   71,   79,   100}, 
}; 

// текущее направление движения 
unsigned char this_move; 

void go(unsigned char direction){
switch (direction) { 
case '0'://STOP
PORTA |= ~_BV(PA1); 
PORTA &= ~_BV(PA2); 
PORTA |= ~_BV(PA3); 
PORTA &= ~_BV(PA4); 
break;

case '1'://F
PORTA |= _BV(PA1); 
PORTA &= ~_BV(PA2); 
PORTA |= ~_BV(PA3); 
PORTA &= ~_BV(PA4); 
break;

case '2'://FR
PORTA |= _BV(PA1); 
PORTA &= ~_BV(PA2); 
PORTA |= _BV(PA3); 
PORTA &= ~_BV(PA4); 
break;

case '3'://FL
PORTA |= _BV(PA1); 
PORTA &= ~_BV(PA2); 
PORTA |= ~_BV(PA3); 
PORTA &= _BV(PA4); 
break;

case '4'://B
PORTA |= ~_BV(PA1); 
PORTA &= _BV(PA2); 
PORTA |= ~_BV(PA3); 
PORTA &= ~_BV(PA4); 
break;

case '5'://BR
PORTA |= ~_BV(PA1); 
PORTA &= _BV(PA2); 
PORTA |= _BV(PA3); 
PORTA &= ~_BV(PA4); 
break;

case '6'://BL
PORTA |= ~_BV(PA1); 
PORTA &= _BV(PA2); 
PORTA |= ~_BV(PA3); 
PORTA &= _BV(PA4); 
break;
}
 }
//------------------------------------------------------------------------------
// Выбор направления движения в следующем шаге по таблице вероятностей
//------------------------------------------------------------------------------
unsigned char next_move(void){
unsigned char pp, i;
pp = rand(); // получаем случайное число 0..98
for (i=0;i<7;i++){ // ищем соответствие в таблице вероятностей
if (p[this_move][i] > pp) break;
}
this_move = i; // записываем новое полученное направление как текущее
return(i);
}

SIGNAL(SIG_INTERRUPT0)
{
   if(this_move=='2') go('6');
   if(this_move=='3') go('5');
   else go('4');
   Delay_10ms(250);    
   Delay_10ms(250);
   this_move='4';
}

SIGNAL(SIG_INTERRUPT1)
{
if(this_move=='5') go('3');
if(this_move=='6') go('2');
else go('1');
Delay_10ms(250);   
Delay_10ms(250);
this_move='1';
}

int main(void)
{
DDRA  = 0xff;
PORTA = 0x00;  
DDRD  = 0x00;  
PORTD = 0xff;  
outb(GIMSK, (1<<INT0)|(1<<INT1)); 
outb(MCUCR, (1<<ISC01)|(1<<ISC11));

sei();          
while(1);
}








