#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
       
void initialize(void);

unsigned int time0;
unsigned char reload, step, stepcount;                                                                            

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
  //make port B and D output
  DDRB=0xFF; 	
  PORTB = 0;    
  DDRD=0x00;
  PORTD = 0;
  
  //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;
  step=0;
  stepcount=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 == 0x02) || (~PIND == 0x01))
    		stepcount=0; 
    		
    	if(stepcount < (length*coeff))
   		begin
  			if (~PIND == 0x01)
  			begin
  				if (step > 0)
  		 			step--;
  				else step = 3;
  			end
  	 		else
  	 		begin
  		 		if (step < 3)
					step++;
		 	 	else step = 0;
	 		end
	 			
	 		stepcount++;
	 			
	   		if (step == 0) PORTB = 1+2;
	 	 	if (step == 1) PORTB = 2+4;
	 	 	if (step == 2) PORTB = 4+8;
			if (step == 3) PORTB = 8+1;	
		end
	end
   end
end 
