//---------------------------------------------------------------------------------------------------------
// 
//	Project:         Serial communcation with hardwar UART. 9600 baud, 8N1.
//	Processor:       PIC16F887 (int.osc @ 4 MHz, Vdd=5 V)
//      Compiler:        HI-TECH PICC LITE v5.90
//      Schematic & PCB: http://www.eeng.biz/
// 			
//---------------------------------------------------------------------------------------------------------


#include <htc.h>
__CONFIG(INTIO & WDTDIS & PWRTEN & MCLREN & UNPROTECT & BORDIS & IESODIS& FCMDIS & LVPDIS & DEBUGDIS); 
__CONFIG(UNPROTECT);

unsigned char ch;
unsigned int  b, tmp;

//---------------------------------------------------------------------------------------------------------
// EUSART_init: this function initialize the EUSART module
// with the desired baud rate. If baud is 0, the auto-baud detect
// routine is executed.
//---------------------------------------------------------------------------------------------------------
void EUSART_Init(unsigned int baud){
	
	SYNC   = 0;
	BRGH   = 1;				// 16-bit Baud Rate Generator
	BRG16  = 1;
	
	switch(baud){
		
		case  1200:
			b = 832;
			break;
		case  2400: 
			b = 416;
			break;
		case  4800: 
			b = 207;
			break;
		case  9600:	
			b = 103;
			break;
		case 19200: 
			b = 51;
			break;
		
		default:    
			b = 103; 
		
		}

	SPBRGH = (unsigned char)(b>>8);
	SPBRG  = (unsigned char)(b & 0x00FF);

	SPEN   = 1;				// enable Serial Port
	TXEN   = 1;				// enable transmission
	CREN   = 1;				// enable Reception
	
	for(tmp=0; tmp<1000; tmp++);		// delay	

}
//---------------------------------------------------------------------------------------------------------
// EUSART_RX: this function receives a byte 
//---------------------------------------------------------------------------------------------------------
unsigned char EUSART_RX(void){
	while(RCIF==0);
	return RCREG;
}
//---------------------------------------------------------------------------------------------------------
// EUSART_TX: this function transmits a byte
//---------------------------------------------------------------------------------------------------------
void EUSART_TX(unsigned char a){
	while(TXIF==0);
	TXREG = a;
}
//---------------------------------------------------------------------------------------------------------
void main(void){
	
	while (HTS == 0);			// oscillator stable?
	
	// Configure PIC16F887
	PORTA  = 0;
	PORTB  = 0;
	PORTC  = 0;
	PORTD  = 0;
	PORTE  = 0;
	
	ANSELH = 0;
	ANSEL  = 0b00001101;			// RA0, RA2, RA3 as analog inputs

	TRISA  = 0b00111111;			// RA6, RA7 as outputs
	TRISB  = 0b11001111;			// RB5, RB4 as outputs	
	TRISC  = 0b11110000;			// RC0, RC1, RC2, RC2 as outputs	

	EUSART_Init(9600);			// 9600 baud	

	while(1){
		ch = EUSART_RX();		// wait for a byte
		EUSART_TX(ch);			// send it back
		}
	
}


