/* www.MicroDigitalEd.com * p4_5.c C library Console I/O using UART0 * * This program demonstrates the use of C library console I/O. * The functions fputc() and fgetc() are implemented using * UART0Tx() and UART0Rx() for character I/O. * In the fgetc(), the received charater is echoed and if a '\r' * is received, it is substituted by a '\n' but both characters are * echoed. * In fputc() and fgetc(), the file descripter is not checked. All * file I/O's are directed to the console. * * By default the subsystem master clock is 3 MHz. * Setting EUSCI_A0->BRW=26 with oversampling disabled yields 115200 Baud. * * Tested with Keil 5.20 and MSP432 Device Family Pack V2.2.0. */ #include "msp.h" #include void UART0_init(void); unsigned char UART0Rx(void); int UART0Tx(unsigned char c); int main(void) { int n; char str[80]; UART0_init(); printf("Test stdio library console I/O functions\r\n"); fprintf(stdout, " test for stdout\r\n"); fprintf(stderr, " test for stderr\r\n"); while (1) { printf("please enter a number: "); scanf("%d", &n); printf("the number entered is: %d\r\n", n); printf("please type a string: "); gets(str); printf("the string entered is: "); puts(str); printf("\r\n"); } } /* initialize UART0 to 115200 Baud at 3 MHz system clock */ void UART0_init(void) { EUSCI_A0->CTLW0 |= 1; /* put in reset mode for config */ EUSCI_A0->MCTLW = 0; /* disable oversampling */ EUSCI_A0->CTLW0 = 0x0081; /* 1 stop bit, no parity, SMCLK, 8-bit data */ EUSCI_A0->BRW = 26; /* 3000000 / 115200 = 26 */ P1->SEL0 |= 0x0C; /* P1.3, P1.2 for UART */ P1->SEL1 &= ~0x0C; EUSCI_A0->CTLW0 &= ~1; /* take UART out of reset mode */ } /* read a character from UART0 */ unsigned char UART0Rx(void) { char c; while(!(EUSCI_A0->IFG & 0x01)) ; c = EUSCI_A0->RXBUF; return c; } /* write a character to UART */ int UART0Tx(unsigned char c) { while(!(EUSCI_A0->IFG&0x02)) ; EUSCI_A0->TXBUF = c; return c; } /* The code below is the interface to the C standard I/O library. * All the I/O are directed to the console, which is UART0. */ struct __FILE { int handle; }; FILE __stdin = {0}; FILE __stdout = {1}; FILE __stderr = {2}; /* Called by C library console/file input * This function echoes the character received. * If the character is '\r', it is substituted by '\n'. */ int fgetc(FILE *f) { int c; c = UART0Rx(); /* read the character from console */ if (c == '\r') { /* if '\r', replace with '\n' */ UART0Tx(c); /* echo */ c = '\n'; } UART0Tx(c); /* echo */ return c; } /* Called by C library console/file output */ int fputc(int c, FILE *f) { return UART0Tx(c); /* write the character to console */ }