/************************************************************************** 
ISR for rtos_ex3
There are two interrupt sources:
High Priority: Timer 0 for "clock tick", 
Low Priority: microswitch (Port B change)for collision

TJW 3.1.06
***************************************************************************/

#include <salvo.h>
#include <p18F242.h>
#include <timers.h>		//header file for timers
#include <delays.h>		//header file for delays

//function prototypes
void timer0_isr (void);
void uswitch_isr (void);

static unsigned int tick_counter = 0;

//These are values for messages
	char Rt_usw = 0x01;
	char Left_usw = 0x80;

//Carries messages from microswitch and ultrasound
#define Msg_to_Motor OSECBP(1) 

/**************************************************************************
Timer Interrupt (High Priority)
**************************************************************************/
//Define the high priority interrupt vector to be at 0008h
#pragma code high_vector=0x08
void interrupt_at_high (void)
{
  _asm GOTO timer0_isr _endasm  //jump to ISR
}

#pragma code	//Return to default code section

//Function timer0_isr specified as high-priority ISR
#pragma interrupt timer0_isr 

//timer0_isr function.
void timer0_isr (void)
{
	WriteTimer0 (64918);	//Timer reload value gives 625 cycles to overflow, 	
 								//less compensation for interrupt latency
 	OSTimer();
	tick_counter++;			//increment tick counter, (for simulation)
  	INTCONbits.TMR0IF = 0; //Clear TMR0 interrupt flag 
}
/**************************************************************************
Microswitch Interrupt (Low Priority)
**************************************************************************/
//Define the low priority interrupt vector to be at 0018h
#pragma code low_vector=0x18
void interrupt_at_low (void)
{
  _asm GOTO uswitch_isr _endasm  //jump to ISR
}
#pragma code	//Return to default code section

//Function uswitch_isr specified as low-priority ISR
#pragma interruptlow uswitch_isr 

//uswitch_isr function.
void uswitch_isr (void)
{
	Delay1KTCYx(8);			  //8ms delay to ensure debounce
	if (PORTBbits.RB4 == 0)   //Test right uswitch
	OSSignalMsg(Msg_to_Motor,(OStypeMsgP)&Rt_usw); //Send message 
	if (PORTBbits.RB5 == 0)  //Test left uswitch
	OSSignalMsg(Msg_to_Motor,(OStypeMsgP)&Left_usw); //Send message
//quite possible to land here with neither switch low any more, as interrupt will sense switch release
  	INTCONbits.RBIF = 0; 	//Clear Port B interrupt flag 
}
