#include #include __CONFIG(INTIO & WDTDIS & PWRTDIS & MCLRDIS & UNPROTECT & BORDIS & IESODIS & FCMDIS); /* A simple demonstration of serial communications which * incorporates the on-board hardware USART of the Microchip * PIC16Fxxx series of devices. */ #define BAUD 9600 #define FOSC 4000000L #define RX_PIN TRISB5 #define TX_PIN TRISB7 void init_comms(void) { // None of the inputs as analog inputs ANSEL = 0; ANSELH = 0; RX_PIN = 1; TX_PIN = 1; // compute the divider for speed (see page 161) SPBRG = ((int)(FOSC/(16UL * BAUD) -1)); // Asynchronous mode (TXSTA) SYNC = 0; // 8 bits reception (RCSTA) RX9 = 0; // enable the receiver (RCSTA) CREN = 1; // High baud rate select (TXSTA) BRGH = 1; // 8 bits transmission (TXTSA) TX9 = 0; // enable transmission (TXTSA) TXEN = 1; // enable the Serial Port (RCSTA) SPEN = 1; } void putch(unsigned char byte) { /* output one byte */ while(!TXIF) /* set when register is empty */ continue; TXREG = byte; } unsigned char getch() { /* retrieve one byte */ while(!RCIF) /* set when register is not empty */ continue; return RCREG; } unsigned char getche(void) { unsigned char c; putch(c = getch()); return c; } void main(void){ unsigned char input; // No interrupts. INTCON=0; // Get the UART ready init_comms(); // Output a message to prompt the user for a keypress printf("\rPress a key and I will echo it back:\n"); while(1){ input = getch(); // read a response from the user printf("\rI detected [%c]",input); // echo it back } }