/* RAK 8/1/2004 SIGNAL.C

INPUT   - binary i/p on bit 0 of port B
PROCESS - emulation of a railway signal, with bouncing
OUTPUT  - PWM output on bit 0 of port A

*/

#include <pic.h>
#include "delay.h"
#include "delay.c"

#define BYTE unsigned char
#define TRUE 1
#define FALSE 0

BYTE i, PulseWidth;
BYTE signal, GoingUp, GoingDown;  // actually Boolean, normally ints in C

signed char diff(BYTE down, BYTE ptr)
{
    signed char result;

    if (ptr<=8)	result=ptr;
	else if (ptr<=31) result=8;
	    else if (ptr<=46) result=39-ptr;
		else result=52-ptr;

    if (down==TRUE && ptr<=31)
	return(-result);
    else
	return(result);
}
	
main()
{
    TRISA = 0xFE;
    TRISB = 0xFF;

    GoingUp=FALSE;
    GoingDown=FALSE;
    signal=PORTB&1;
    if (signal==TRUE) PulseWidth=220; else PulseWidth=0;

    for (;;)
    {
	if (GoingUp==TRUE)
	{
	    PulseWidth+=diff(FALSE,i);
	    if (i==57) GoingUp=FALSE; else i++;
	}
	
	else if (GoingDown==TRUE)
	{
	    PulseWidth+=diff(TRUE,i);
	    if (i==57) GoingDown=FALSE; else i++;
	}

	else if (((PORTB&1)==TRUE) && (signal==FALSE)) // i.e. was down, now to go up
	{
	    signal=TRUE;
	    GoingUp=TRUE;
	    i=1;
	}

	else if (((PORTB&1)==FALSE) && (signal==TRUE)) // i.e. was up, now to go down
	{
	    signal=FALSE;
	    GoingDown=TRUE;
	    i=1;
	}

	/* Pulse servo */

	RA0=1;	// take output high

	OPTION=0b0001;		// TMR0 prescaler=4
	TMR0=-250;		// size of delay = 250*4usec
	T0IF=0;			// start timer
	while (T0IF==0);	// wait for timer to time out

	TMR0=255-PulseWidth;	// get rest of delay from switches
	T0IF=0;			// start timer
	while (T0IF==0);	// wait for timer to time out

	RA0=0;		// take output low

	OPTION=0b0110;	// TMR0 prescaler=128
	TMR0=-144;	// size of delay = 144*128usec = 18.5msec
	T0IF=0;		// start timer
	while (T0IF==0);// wait for timer to time out
	}
}     


