//                          PDABOT.C
//
// Software for the PIC16f876 used with PDA Robot
//
// Author: Douglas H Williams
// PDA Robotics: McGraw-Hill 2003
//

#include <16f876.h>

//
// We are using a 20 MHz oscillator
//

#use delay(clock=20000000)

//
// Set pins B0 & B1 as our RS232 port which connects to the
// MCP2150 IrDA Protocol Stack Controller
//

#use rs232(baud=115200, xmit=PIN_B1, rcv=PIN_B0, stream=PDA)

main() {

	//
	// The value from the range finder
	//
	
	int value;

	//
	// The command sent from the PDA 
	//

	char cmd; 

	//
	// Set up port A as analog, pin A0 is connected 
	// to the sharp GP2D12 infrared range finder 
	//

   	setup_port_a( ALL_ANALOG );
   	setup_adc( ADC_CLOCK_INTERNAL );
   	set_adc_channel( 0 );
	
	//
	// Set the B port pins that interface to the
	// L298 motor controller low to ensure no 
	// motor movement on startup. Pins B2 & B3
	// control Motor 1 and B4 & B5 control Motor 2.
	//

	output_low(PIN_B2);
	delay_cycles(3);
	output_low(PIN_B3);
	delay_cycles(3);
	output_low(PIN_B4);	
	delay_cycles(3);
	output_low(PIN_B5);
	delay_cycles(3);
	output_low(PIN_B6);
	delay_cycles(3);
	output_low(PIN_B7);
	delay_cycles(3);

	fprintf(PDA, " ");

	while (1){

		//
		// Get the command sent from the PDA
		//

		cmd = fgetc(PDA);

		if( cmd == 'a')
		{
			output_high(PIN_B2);
			delay_cycles(1);
			output_low(PIN_B3);
			delay_cycles(1);
		}

		if( cmd == 'b')
		{
			output_low(PIN_B2);
			delay_cycles(3);
			output_high(PIN_B3);
			delay_cycles(1);
		}

		if( cmd == 'c')
		{
			output_low(PIN_B2);
			delay_cycles(3);
			output_low(PIN_B3);
			delay_cycles(1);
		}

		if( cmd == 'd')
		{
			output_high(PIN_B4);
			delay_cycles(3);
			output_low(PIN_B5);
			delay_cycles(1);
		}

		if( cmd == 'e')
		{
			output_low(PIN_B4);
			delay_cycles(3);
			output_high(PIN_B5);
			delay_cycles(1);
		}

		if( cmd == 'f')
		{
			output_low(PIN_B4);
			delay_cycles(3);
			output_low(PIN_B5);
			delay_cycles(1);
		}

		if( cmd == 'g')
		{

			//
			// Give some time for the clear to send 
			//

			delay_ms(3);

			//
			// Read the analog value from the range finder	
			//
		
			value = Read_ADC();

			//
			// Send the value to the PDA
			//

			putc(value);
			//delay_cycles(1);
		}
	} 
}
	