// Working 
// by Phil Winder || www.philwinder.com

// DESCRIPTION: **************************************************
// These functions use two IR LED's and two TSOP4838's to detect a 
// wall or some other object.  A resistor (see notes) is used to 
// limit the current of the IR LED and therefore limit the range.

// NOTES: ********************************************************
// # IR Rx is affected by fluorescent/Energy saving lights
// # There should be some frequency dependance in the TSOP
//   recievers, but for some reason you can change the frequency
//   and it doesnt seem to matter (much -> i.e. non-linear).
// # A resistor had to be used due to the above statement, a value
//	 of 1.5kohm was used.  Probably better to use a pot to be able
//   to compensate for the IR LED/Rx pooness.
// # Fairly simple to add the watchdog timer for sleep operations
//   to make the power consumption much less.

// VERSION INFORMATION: ******************************************
// V1.0 @ 10/05/07 - Copied from earlier test programs
// ***************************************************************
#include <delays.h>

// Defines
#define IRCLKS			100		// Number of Pulses to make
#define IROUT 			0b1100	// PORTB.2+3
#define IRPOWERL 		LATB4	// PORTB.4
#define IRPOWERR 		LATB5	// PORTB.5
#define IRRx			3		// IR Rx Pin's


// Function Definitions
unsigned char Proximity_Detect(void);
void Transmit_38kHz(void);

// 38kHz IR Generator
void Transmit_38kHz(void)
	{
	unsigned char x;
	for(x = 0; x<(IRCLKS); x++)
		{
		// Output a 38kHz burst to the LED
		LATB = LATB ^ IROUT;	// Changes the LED's High
		LATB = LATB ^ IROUT;	// Then low
		Delay10TCYx(4);			// Then Delays (44 Clk Cycles actually 38kHz)
		Delay1TCY();			// But with the Latches, its 40ish (Tested Experimentally)
		// Can Increase the range by increasing/decreasing delays, although the results
		// are tempromental and can change per device.  Probably better to use a pot.
		}
	}

// Proximity Detect Function
unsigned char Proximity_Detect(void)
	{
	unsigned char temp;

	LATBbits.IRPOWERL = 1;	// Powers the IR Rx High
	LATBbits.IRPOWERR = 1;	// Powers the IR Rx High
	Transmit_38kHz();		// Transmit Pulse Train
	temp = PORTB;
	temp = temp & 0b00000011;
	LATBbits.IRPOWERL = 0;	// Powers the IR Rx Low
	LATBbits.IRPOWERR = 0;	// Powers the IR Rx Low
	return temp;
	}


