
#include <90s8515.h>
#include <Stdio.h>
#include <Stdlib.h>
#include <delay.h>

#define prescale0 3
#define begin {
#define end }
#define t0 25 
#define maxstep 50
#define coeff 20
#define length 4
#define D 300
       
void initialize(void);

unsigned int time0;
unsigned char reload, stepR, stepL, stepcountR, stepcountL, rightflag;                                                                            

interrupt [TIM0_OVF] void timer0_overflow(void)
begin   
    
  //reload to force 1 mSec overflow
  TCNT0=reload;
  
  //Decrement the times if they are not already zero
  if (time0>0)	--time0;
  
end  

//********************************************************** 
//Set it all up
void initialize(void)
begin
  
  //set up the port
  DDRA=0xFF; 	//make port B output
  PORTA = 0;    
  
  DDRD=0x00;
  
  //set up timer 0     
  //62.5 x (64x.25) microSec = 1.0 mSec, so prescale 64, and count 62 times.
  reload=256-62; 		//value for 1 Msec  
  TCNT0=reload;	 		//preload timer 1 so that is interrupts after 1 mSec.
  TCCR0=prescale0;		//prescalar to 64
  TIMSK=2;	   		//turn on timer 0 overflow ISR  
  
  //init the task timer
  time0=t0;
  stepR=0;  
  stepL=0;
  stepcountR=0;
  stepcountL=0;
  rightflag=0;  
      
  //crank up the ISRs
  #asm
  	sei
  #endasm 
end

void main(void)
begin
  initialize();
  while(1)
  begin
    if(time0 == 0)
    begin
    	time0 = t0;

  			if ((~PIND&0xF0) == 16)
  			begin
  				if (stepR > 0)
  		 			stepR--;
  				else stepR = 3;
  				stepcountR++;	
  			end
  	 		else if ((~PIND&0xF0) == 32)
  	 		begin
  		 		if (stepR < 3)
				 		stepR++;
		 	 		else stepR = 0;  
		 	 		stepcountR++;
		 	 	end	
	 		
	   		if (stepR == 0) PORTA = 1+2+(PORTA&0xF0);
	 	 		if (stepR == 1) PORTA = 2+4+(PORTA&0xF0);
	 	 		if (stepR == 2) PORTA = 4+8+(PORTA&0xF0);
				if (stepR == 3) PORTA = 8+1+(PORTA&0xF0);

		
  			if ((~PIND&0x0F) == 1)
  			begin
  				if (stepL > 0)
  		 			stepL--;
  				else stepL = 3;
	 				stepcountL++;	     				
  			end
  	 		else if ((~PIND&0x0F) == 2)
  	 		begin
  		 		if (stepL < 3)
				 		stepL++;
		 	 		else stepL = 0; 
		 	 		stepcountL++;	   
	 			end
	 
	   		if (stepL == 0) PORTA = 16+32+(PORTA&0x0F);
		 		if (stepL == 1) PORTA = 32+64+(PORTA&0x0F);
	 	 		if (stepL == 2) PORTA = 64+128+(PORTA&0x0F);
		 		if (stepL == 3) PORTA = 128+16+(PORTA&0x0F);
	end
  end
end 
