/*The main function demonstrates printing to the console and reading from the console using the putstrserial() and getstrserial() functions. It also demonstrates using printf(), from stdio.h, which automatically prints through UART3.*/ #include #include void initUART(void) { // Configure UART // Using UART3 since nothing else uses PORTF TRISFbits.TRISF5 = 0; // RF5 is UART3 TX (output) TRISFbits.TRISF4 = 1; // RF4 is UART3 RX (input) // Want rate of 115.2 Kbaud // Assuming PIC peripheral clock Fpb = Fosc / 2 = 20 MHz // based on default instructions in lab 1. // U3BRG = (Fpb / 4*baud rate) - 1 // -> U3BRG = 10 (decimal) // Actual baud rate 113636.4 (-1.2% error) U3ABRG = 10; // UART3 Mode Register // bit 31-16: unused // bit 15: ON = 1: enable UART // bit 14: FRZ = 0: don't care when CPU in normal state // bit 13: SIDL = 0: don't care when CPU in normal state // bit 12: IREN = 0: disable IrDA // bit 11: RTSMD = 0: don't care if not using flow control // bit 10: unused // bit 9-8: UEN = 00: enable U1TX and U1RX, disable U1CTSb and U1RTSb // bit 7: WAKE = 0: do not wake on UART if in sleep mode // bit 6: LPBACK = 0: disable loopback mode // bit 5: ABAUD = 0: don't auto detect baud rate // bit 4: RXINV = 0: U1RX idle state is high // bit 3: BRGH = 0: standard speed mode // bit 2-1: PDSEL = 00: 8-bit data, no parity // bit 0: STSEL = 0: 1 stop bit U3AMODE = 0x8000; // UART3 Status and control register // bit 31-25: unused // bit 13: UTXINV = 0: U1TX idle state is high // bit 12: URXEN = 1: enable receiver // bit 11: UTXBRK = 0: disable break transmission // bit 10: UTXEN = 1: enable transmitter // bit 9: UTXBF: don't care (read-only) // bit 8: TRMT: don't care (read-only) // bit 7-6: URXISEL = 00: interrupt when receive buffer not empty // bit 5: ADDEN = 0: disable address detect // bit 4: RIDLE: don't care (read-only) // bit 3: PERR: don't care (read-only) // bit 2: FERR: don't care (read-only) // bit 1: OERR = 0: reset receive buffer overflow flag // bit 0: URXDA: don't care (read-only) U3ASTA = 0x1400; } char getcharserial(void) { while (!U3ASTAbits.URXDA); // wait until data available return U3ARXREG; // return character received from serial port } void getstrserial(char *str) { int i = 0; do { // read an entire string until detecting str[i] = getcharserial(); } while (str[i++] != '\r'); // look for return str[i-1] = 0; // null terminate the string } void putcharserial(char c) { while (U3ASTAbits.UTXBF); // wait until transmit buffer empty U3ATXREG = c; // transmit character over serial port } void putstrserial(char *str) { int i = 0; putcharserial('\n'); putcharserial('\r'); while (str[i] != 0) { putcharserial(str[i++]); } } void main(void) { char str[80]; inituart(); while(1) { // iterate over string // send each character putstrserial("Please type something: "); getstrserial(str); printf("\n\rYou typed: %s\n\r", str); } }