// See fsl_lpuart_hal.h for documentation of this function.
status_t lpuart_hal_set_baud_rate(LPUART_Type * baseAddr, uint32_t sourceClockInHz,
                                uint32_t desiredBaudRate)
{

    // Calculate SBR rounded to nearest whole number, 14.4 = 14, 14.6 = 15
    // This gives the least error possible
    uint32_t sbr = (uint32_t)(((sourceClockInHz * 10)/(desiredBaudRate * kLPUART_OSR_Value)) + 5) / 10;
    uint32_t calculatedBaud = (uint32_t)(sourceClockInHz/(sbr * kLPUART_OSR_Value));
    uint32_t baudDiff = MAX(calculatedBaud, desiredBaudRate) - MIN(calculatedBaud, desiredBaudRate);

    // next, check to see if actual baud rate is within 3% of desired baud rate
    // based on the best calculate osr value
    if (baudDiff < ((desiredBaudRate / 100) * 3))
    {
        // program the osr value (bit value is one less than actual value)
        LPUART_WR_BAUD(baseAddr,
                          LPUART_BAUD_OSR(kLPUART_OSR_Value - 1) |
                          LPUART_BAUD_SBR(sbr) |
                          LPUART_BAUD_BOTHEDGE_MASK);
    }
    else
    {
        // Unacceptable baud rate difference of more than 3%
        return kStatus_LPUART_BaudRatePercentDiffExceeded;
    }

    return kStatus_Success;
}
/*
 * Initialises the LPUART
 *
 * @param baudrate - the baud rate to use e.g. 19200
 */
void uart_initialise(int baudrate) {
   initDefaultUart();

   #define OVERSAMPLE (16)

   // Disable LPUART before changing registers
   LPUART->CTRL &= ~(LPUART_CTRL_RE_MASK|LPUART_CTRL_TE_MASK);

   // Calculate LPUART clock setting
   int baudValue = UART_CLOCK/(OVERSAMPLE*baudrate);

   // Set Baud rate register
   LPUART->BAUD = LPUART_BAUD_SBR(baudValue)|LPUART_BAUD_OSR(OVERSAMPLE-1);

#ifdef USE_IRQ
   // Enable LPUART Tx & Rx - with Rx IRQ
   LPUART->CTRL = LPUART_CTRL_RE_MASK|LPUART_CTRL_TE_MASK|LPUART_CTRL_RIE_MASK|LPUART_CTRL_TIE_MASK;
#else
   // Enable LPUART Tx & Rx
   LPUART->CTRL = LPUART_CTRL_RE_MASK|LPUART_CTRL_TE_MASK;
#endif
}