// CONFIG PART
#pragma config FOSC = INTOSCIO  	// Oscillator Selection bits (INTOSCIO oscillator: I/O function on RA4/OSC2/CLKOUT pin, I/O function on RA5/OSC1/CLKIN)
#pragma config WDTE = OFF       	// Watchdog Timer Enable bit (WDT disabled)
#pragma config PWRTE = ON       	// Power-up Timer Enable bit (PWRT enabled)
#pragma config MCLRE = OFF      	// MCLR Pin Function Select bit (MCLR pin function is digital input, MCLR internally tied to VDD)
#pragma config CP = OFF         	// Code Protection bit (Program memory code protection is disabled)
#pragma config CPD = OFF        	// Data Code Protection bit (Data memory code protection is disabled)
#pragma config BOREN = ON       	// Brown Out Detect (BOR enabled)
#pragma config IESO = OFF       	// Internal External Switchover bit (Internal External Switchover mode is disabled)
#pragma config FCMEN = OFF      	// Fail-Safe Clock Monitor Enabled bit (Fail-Safe Clock Monitor is disabled)

#include <xc.h>

#define _XTAL_FREQ  8000000     	// Let the compiler know we will be running at 8MHz

// MAIN LOOP

void main(void) {			// Enter the main loop
	OSCCONbits.IRCF = 0b111;    	// Select 8MHz clock
	TRISIO = 0b111000;          	// GPIO5/4/3 inputs, 2/1/0 outputs
	ANSEL = 0;                  	// Force all GPIO pins to digital mode
	while (1)	   		// Loop forever
    	{				// The TSOP outputs a ttl level 1 when idle. So a ttl 0 level is in fact a logical 1
        	while (GPIObits.GP5==0) // So We have to invert our thinking and ttl 0 = logic 1. Using GPIO pin 5 as input
        	{			// When logic 1 enter the 38Khz generator loop. 
            		GPIObits.GP0=1;	// Using GPIO pin 0 as the generator output. Switch GPIO 0 to ttl 1
            		__delay_us(10);	// wait 10 µSec
            		GPIObits.GP0=0;	// Switch GPIO 0 to ttl 0
            		__delay_us(10); // wait 10 µSec
        	}			// Repeat as long GPIO5 stays at logic 1. 50/50% duty cycle ( 37,8Khz in real life )
        GPIObits.GP0=0;			// When in logic 0 state switch off BS170.
    	}				// keep waiting for incomming ttl 0 on GPIO5 for ever
}					// Close main loop