/* www.MicroDigitalEd.com
 * p4_4.c UART2 echo
 *
 * This program receives a character from UART2 receiver
 * then sends it back through UART2.
 * The UART2 is connected to P3.2 (RXD) and P3.3 (TXD) on the LaunchPad.
 * A 3.3V signal level to USB cable is used to connect to 
 * the host PC COM port.
 *
 * By default the subsystem master clock is 3 MHz.
 * Setting EUSCI_A2->BRW=26 with oversampling disabled yields 115200 Baud.
 *
 * Tested with Keil 5.20 and MSP432 Device Family Pack V2.2.0.
 */

#include "msp.h"

void UART2_init(void);

int main(void) {
    char c;

    UART2_init();

    while (1) {
        while(!(EUSCI_A2->IFG & 0x01)) { }    /* wait until receive buffer is full */
        c = EUSCI_A2->RXBUF;                  /* read the receive char */
        
        while(!(EUSCI_A2->IFG&0x02)) { }      /* wait for transmit buffer empty */
        EUSCI_A2->TXBUF = c;                  /* send the char */
    }
}

void UART2_init(void)
{
    EUSCI_A2->CTLW0 |= 1;       /* put in reset mode for config */
    EUSCI_A2->MCTLW = 0;        /* disable oversampling */
    EUSCI_A2->CTLW0 = 0x0081;   /* 1 stop bit, no parity, SMCLK, 8-bit data */
    EUSCI_A2->BRW = 26;         /* 3,000,000 / 115200 = 26 */
    P3->SEL0 |= 0x0C;           /* P1.3, P1.2 for UART */
    P3->SEL1 &= ~0x0C;
    EUSCI_A2->CTLW0 &= ~1;      /* take UART out of reset mode */
}