1 /*
2  * Copyright (c) 2016, Freescale Semiconductor, Inc.
3  * Copyright 2016-2021 NXP
4  * All rights reserved.
5  *
6  * SPDX-License-Identifier: BSD-3-Clause
7  */
8 
9 #ifndef _FSL_UART_H_
10 #define _FSL_UART_H_
11 
12 #include "fsl_common.h"
13 
14 /*!
15  * @addtogroup uart_driver
16  * @{
17  */
18 
19 /*******************************************************************************
20  * Definitions
21  ******************************************************************************/
22 /*! @name Driver version */
23 /*@{*/
24 /*! @brief UART driver version. */
25 #define FSL_UART_DRIVER_VERSION (MAKE_VERSION(2, 3, 2))
26 /*@}*/
27 
28 /*! @brief Retry times for waiting flag. */
29 #ifndef UART_RETRY_TIMES
30 #define UART_RETRY_TIMES 0U /* Defining to zero means to keep waiting for the flag until it is assert/deassert. */
31 #endif
32 
33 /*! @brief Error codes for the UART driver. */
34 enum
35 {
36     kStatus_UART_TxBusy              = MAKE_STATUS(kStatusGroup_IUART, 0), /*!< Transmitter is busy. */
37     kStatus_UART_RxBusy              = MAKE_STATUS(kStatusGroup_IUART, 1), /*!< Receiver is busy. */
38     kStatus_UART_TxIdle              = MAKE_STATUS(kStatusGroup_IUART, 2), /*!< UART transmitter is idle. */
39     kStatus_UART_RxIdle              = MAKE_STATUS(kStatusGroup_IUART, 3), /*!< UART receiver is idle. */
40     kStatus_UART_TxWatermarkTooLarge = MAKE_STATUS(kStatusGroup_IUART, 4), /*!< TX FIFO watermark too large  */
41     kStatus_UART_RxWatermarkTooLarge = MAKE_STATUS(kStatusGroup_IUART, 5), /*!< RX FIFO watermark too large  */
42     kStatus_UART_FlagCannotClearManually =
43         MAKE_STATUS(kStatusGroup_IUART, 6),                                /*!< UART flag can't be manually cleared. */
44     kStatus_UART_Error               = MAKE_STATUS(kStatusGroup_IUART, 7), /*!< Error happens on UART. */
45     kStatus_UART_RxRingBufferOverrun = MAKE_STATUS(kStatusGroup_IUART, 8), /*!< UART RX software ring buffer overrun. */
46     kStatus_UART_RxHardwareOverrun   = MAKE_STATUS(kStatusGroup_IUART, 9), /*!< UART RX receiver overrun. */
47     kStatus_UART_NoiseError          = MAKE_STATUS(kStatusGroup_IUART, 10), /*!< UART noise error. */
48     kStatus_UART_FramingError        = MAKE_STATUS(kStatusGroup_IUART, 11), /*!< UART framing error. */
49     kStatus_UART_ParityError         = MAKE_STATUS(kStatusGroup_IUART, 12), /*!< UART parity error. */
50     kStatus_UART_BaudrateNotSupport =
51         MAKE_STATUS(kStatusGroup_IUART, 13), /*!< Baudrate is not support in current clock source */
52     kStatus_UART_BreakDetect = MAKE_STATUS(kStatusGroup_IUART, 14), /*!< Receiver detect BREAK signal */
53     kStatus_UART_Timeout     = MAKE_STATUS(kStatusGroup_IUART, 15), /*!< UART times out. */
54 };
55 
56 /*! @brief UART data bits count. */
57 typedef enum _uart_data_bits
58 {
59     kUART_SevenDataBits = 0x0U, /*!< Seven data bit */
60     kUART_EightDataBits = 0x1U, /*!< Eight data bit */
61 } uart_data_bits_t;
62 
63 /*! @brief UART parity mode. */
64 typedef enum _uart_parity_mode
65 {
66     kUART_ParityDisabled = 0x0U, /*!< Parity disabled */
67     kUART_ParityEven     = 0x2U, /*!< Even error check is selected */
68     kUART_ParityOdd      = 0x3U, /*!< Odd error check is selected */
69 } uart_parity_mode_t;
70 
71 /*! @brief UART stop bit count. */
72 typedef enum _uart_stop_bit_count
73 {
74     kUART_OneStopBit = 0x0U, /*!< One stop bit */
75     kUART_TwoStopBit = 0x1U, /*!< Two stop bits */
76 } uart_stop_bit_count_t;
77 
78 /*! @brief UART idle condition detect. */
79 typedef enum _uart_idle_condition
80 {
81     kUART_IdleFor4Frames  = 0x0U, /*!< Idle for more than 4 frames */
82     kUART_IdleFor8Frames  = 0x1U, /*!< Idle for more than 8 frames */
83     kUART_IdleFor16Frames = 0x2U, /*!< Idle for more than 16 frames */
84     kUART_IdleFor32Frames = 0x3U, /*!< Idle for more than 32 frames */
85 } uart_idle_condition_t;
86 
87 /*! @brief This structure contains the settings for all of the UART interrupt configurations. */
88 enum _uart_interrupt_enable
89 {
90     kUART_AutoBaudEnable    = 0x1U,         /* !< Automatic baud rate detection Interrupt Enable. */
91     kUART_TxReadyEnable     = (0X1U << 1),  /* !< transmitter ready Interrupt Enable. */
92     kUART_IdleEnable        = (0x1U << 2),  /* !< IDLE Interrupt Enable. */
93     kUART_RxReadyEnable     = (0x1U << 3),  /* !< Receiver Ready Interrupt Enable. */
94     kUART_TxEmptyEnable     = (0x1U << 4),  /* !< Transmitter Empty Interrupt Enable. */
95     kUART_RtsDeltaEnable    = (0x1U << 5),  /* !< RTS Delta Interrupt Enable. */
96     kUART_EscapeEnable      = (0x1U << 8),  /* !< Escape Sequence Interrupt Enable. */
97     kUART_RtsEnable         = (0x1U << 9),  /* !< Request to Send Interrupt Enable. */
98     kUART_AgingTimerEnable  = (0x1U << 10), /* !< Aging Timer Interrupt Enable. */
99     kUART_DtrEnable         = (0x1U << 12), /* !< Data Terminal Ready Interrupt Enable. */
100     kUART_ParityErrorEnable = (0x1U << 13), /* !< Parity Error Interrupt Enable.  */
101     kUART_FrameErrorEnable  = (0x1U << 14), /* !< Frame Error Interrupt Enable. */
102     kUART_DcdEnable         = (0x1U << 15), /* !< Data Carrier Detect Interrupt Enable. */
103     kUART_RiEnable          = (0x1U << 16), /* !< Ring Indicator Interrupt Enable. */
104     kUART_RxDsEnable        = (0x1U << 17), /* !< Receive Status Interrupt Enable. */
105     kUART_tAirWakeEnable    = (0x1U << 18), /* !< Asynchronous IR WAKE Interrupt Enable. */
106     kUART_AwakeEnable       = (0x1U << 19), /* !< Asynchronous WAKE Interrupt Enable. */
107     kUART_DtrDeltaEnable    = (0x1U << 20), /* !< Data Terminal Ready Delta Interrupt Enable. */
108     kUART_AutoBaudCntEnable = (0x1U << 21), /* !< Auto-baud Counter Interrupt Enable. */
109     kUART_IrEnable          = (0X1U << 24), /* !< Serial Infrared Interrupt Enable. */
110     kUART_WakeEnable        = (0X1U << 25), /* !< WAKE Interrupt Enable. */
111     kUART_TxCompleteEnable  = (0X1U << 26), /* !< TransmitComplete Interrupt Enable. */
112     kUART_BreakDetectEnable = (0X1U << 27), /* !< BREAK Condition Detected Interrupt Enable. */
113     kUART_RxOverrunEnable   = (0X1U << 28), /* !< Receiver Overrun Interrupt Enable. */
114     kUART_RxDataReadyEnable = (0X1U << 29), /* !< Receive Data Ready Interrupt Enable. */
115     kUART_RxDmaIdleEnable   = (0X1U << 30), /* !< Receive DMA IDLE detect Interrupt Enable. */
116     kUART_AllInterruptsEnable =
117         kUART_AutoBaudEnable | kUART_TxReadyEnable | kUART_IdleEnable | kUART_RxReadyEnable | kUART_TxEmptyEnable |
118         kUART_RtsDeltaEnable | kUART_EscapeEnable | kUART_RtsEnable | kUART_AgingTimerEnable | kUART_DtrEnable |
119         kUART_ParityErrorEnable | kUART_FrameErrorEnable | kUART_DcdEnable | kUART_RiEnable | kUART_RxDsEnable |
120         kUART_tAirWakeEnable | kUART_AwakeEnable | kUART_DtrDeltaEnable | kUART_AutoBaudCntEnable | kUART_IrEnable |
121         kUART_WakeEnable | kUART_TxCompleteEnable | kUART_BreakDetectEnable | kUART_RxOverrunEnable |
122         kUART_RxDataReadyEnable | kUART_RxDmaIdleEnable,
123 };
124 
125 /*!
126  * @brief UART status flags.
127  *
128  * This provides constants for the UART status flags for use in the UART functions.
129  */
130 enum
131 {
132     kUART_RxCharReadyFlag         = 0x0000000FU, /*!< Rx Character Ready Flag. */
133     kUART_RxErrorFlag             = 0x0000000EU, /*!< Rx Error Detect Flag. */
134     kUART_RxOverrunErrorFlag      = 0x0000000DU, /*!< Rx Overrun Flag. */
135     kUART_RxFrameErrorFlag        = 0x0000000CU, /*!< Rx Frame Error Flag. */
136     kUART_RxBreakDetectFlag       = 0x0000000BU, /*!< Rx Break Detect Flag. */
137     kUART_RxParityErrorFlag       = 0x0000000AU, /*!< Rx Parity Error Flag. */
138     kUART_ParityErrorFlag         = 0x0094000FU, /*!< Parity Error Interrupt Flag. */
139     kUART_RtsStatusFlag           = 0x0094000EU, /*!< RTS_B Pin Status Flag. */
140     kUART_TxReadyFlag             = 0x0094000DU, /*!< Transmitter Ready Interrupt/DMA Flag. */
141     kUART_RtsDeltaFlag            = 0x0094000CU, /*!< RTS Delta Flag. */
142     kUART_EscapeFlag              = 0x0094000BU, /*!< Escape Sequence Interrupt Flag. */
143     kUART_FrameErrorFlag          = 0x0094000AU, /*!< Frame Error Interrupt Flag. */
144     kUART_RxReadyFlag             = 0x00940009U, /*!< Receiver Ready Interrupt/DMA Flag. */
145     kUART_AgingTimerFlag          = 0x00940008U, /*!< Aging Timer Interrupt Flag. */
146     kUART_DtrDeltaFlag            = 0x00940007U, /*!< DTR Delta Flag. */
147     kUART_RxDsFlag                = 0x00940006U, /*!< Receiver IDLE Interrupt Flag. */
148     kUART_tAirWakeFlag            = 0x00940005U, /*!< Asynchronous IR WAKE Interrupt Flag. */
149     kUART_AwakeFlag               = 0x00940004U, /*!< Asynchronous WAKE Interrupt Flag. */
150     kUART_Rs485SlaveAddrMatchFlag = 0x00940003U, /*!< RS-485 Slave Address Detected Interrupt Flag. */
151     kUART_AutoBaudFlag            = 0x0098000FU, /*!< Automatic Baud Rate Detect Complete Flag. */
152     kUART_TxEmptyFlag             = 0x0098000EU, /*!< Transmit Buffer FIFO Empty. */
153     kUART_DtrFlag                 = 0x0098000DU, /*!< DTR edge triggered interrupt flag. */
154     kUART_IdleFlag                = 0x0098000CU, /*!< Idle Condition Flag. */
155     kUART_AutoBaudCntStopFlag     = 0x0098000BU, /*!< Auto-baud Counter Stopped Flag. */
156     kUART_RiDeltaFlag             = 0x0098000AU, /*!< Ring Indicator Delta Flag. */
157     kUART_RiFlag                  = 0x00980009U, /*!< Ring Indicator Input Flag. */
158     kUART_IrFlag                  = 0x00980008U, /*!< Serial Infrared Interrupt Flag. */
159     kUART_WakeFlag                = 0x00980007U, /*!< Wake Flag. */
160     kUART_DcdDeltaFlag            = 0x00980006U, /*!< Data Carrier Detect Delta Flag. */
161     kUART_DcdFlag                 = 0x00980005U, /*!< Data Carrier Detect Input Flag. */
162     kUART_RtsFlag                 = 0x00980004U, /*!< RTS Edge Triggered Interrupt Flag. */
163     kUART_TxCompleteFlag          = 0x00980003U, /*!< Transmitter Complete Flag. */
164     kUART_BreakDetectFlag         = 0x00980002U, /*!< BREAK Condition Detected Flag. */
165     kUART_RxOverrunFlag           = 0x00980001U, /*!< Overrun Error Flag. */
166     kUART_RxDataReadyFlag         = 0x00980000U, /*!< Receive Data Ready Flag. */
167 };
168 
169 /*! @brief UART configuration structure. */
170 typedef struct _uart_config
171 {
172     uint32_t baudRate_Bps;              /*!< UART baud rate. */
173     uart_parity_mode_t parityMode;      /*!< Parity error check mode of this module. */
174     uart_data_bits_t dataBitsCount;     /*!< Data bits count, eight (default), seven */
175     uart_stop_bit_count_t stopBitCount; /*!< Number of stop bits in one frame. */
176     uint8_t txFifoWatermark;            /*!< TX FIFO watermark */
177     uint8_t rxFifoWatermark;            /*!< RX FIFO watermark */
178     uint8_t rxRTSWatermark; /*!< RX RTS watermark, RX FIFO data count being larger than this triggers RTS deassertion */
179     bool enableAutoBaudRate; /*!< Enable automatic baud rate detection */
180     bool enableTx;           /*!< Enable TX */
181     bool enableRx;           /*!< Enable RX */
182     bool enableRxRTS;        /*!< RX RTS enable */
183     bool enableTxCTS;        /*!< TX CTS enable */
184 } uart_config_t;
185 
186 /*! @brief UART transfer structure. */
187 typedef struct _uart_transfer
188 {
189     /*
190      * Use separate TX and RX data pointer, because TX data is const data.
191      * The member data is kept for backward compatibility.
192      */
193     union
194     {
195         uint8_t *data;         /*!< The buffer of data to be transfer.*/
196         uint8_t *rxData;       /*!< The buffer to receive data. */
197         const uint8_t *txData; /*!< The buffer of data to be sent. */
198     };
199     size_t dataSize; /*!< The byte count to be transfer. */
200 } uart_transfer_t;
201 
202 /*! @brief Forward declaration of the handle typedef. */
203 typedef struct _uart_handle uart_handle_t;
204 
205 /*! @brief UART transfer callback function. */
206 typedef void (*uart_transfer_callback_t)(UART_Type *base, uart_handle_t *handle, status_t status, void *userData);
207 
208 /*! @brief UART handle structure. */
209 struct _uart_handle
210 {
211     const uint8_t *volatile txData; /*!< Address of remaining data to send. */
212     volatile size_t txDataSize;     /*!< Size of the remaining data to send. */
213     size_t txDataSizeAll;           /*!< Size of the data to send out. */
214     uint8_t *volatile rxData;       /*!< Address of remaining data to receive. */
215     volatile size_t rxDataSize;     /*!< Size of the remaining data to receive. */
216     size_t rxDataSizeAll;           /*!< Size of the data to receive. */
217 
218     uint8_t *rxRingBuffer;              /*!< Start address of the receiver ring buffer. */
219     size_t rxRingBufferSize;            /*!< Size of the ring buffer. */
220     volatile uint16_t rxRingBufferHead; /*!< Index for the driver to store received data into ring buffer. */
221     volatile uint16_t rxRingBufferTail; /*!< Index for the user to get data from the ring buffer. */
222 
223     uart_transfer_callback_t callback; /*!< Callback function. */
224     void *userData;                    /*!< UART callback function parameter.*/
225 
226     volatile uint8_t txState; /*!< TX transfer state. */
227     volatile uint8_t rxState; /*!< RX transfer state */
228 };
229 
230 /* Typedef for interrupt handler. */
231 typedef void (*uart_isr_t)(UART_Type *base, void *handle);
232 
233 /*******************************************************************************
234  * Variables
235  ******************************************************************************/
236 /* Array of UART IRQ number. */
237 extern const IRQn_Type s_uartIRQ[];
238 
239 /* UART ISR for transactional APIs. */
240 extern uart_isr_t s_uartIsr;
241 
242 /*! Pointers to uart handles for each instance. */
243 extern void *s_uartHandle[];
244 
245 /*******************************************************************************
246  * API
247  ******************************************************************************/
248 
249 #if defined(__cplusplus)
250 extern "C" {
251 #endif
252 
253 /*!
254  * @brief Get the UART instance from peripheral base address.
255  *
256  * @param base UART peripheral base address.
257  * @return UART instance.
258  */
259 uint32_t UART_GetInstance(UART_Type *base);
260 
261 /*!
262  * @name Software Reset
263  * @{
264  */
265 
266 /*!
267  * @brief Resets the UART using software.
268  *
269  * This function resets the transmit and receive state machines, all FIFOs and register
270  * USR1, USR2, UBIR, UBMR, UBRC , URXD, UTXD and UTS[6-3]
271  *
272  * @param base UART peripheral base address.
273  */
UART_SoftwareReset(UART_Type * base)274 static inline void UART_SoftwareReset(UART_Type *base)
275 {
276     base->UCR2 &= ~UART_UCR2_SRST_MASK;
277     while ((base->UCR2 & UART_UCR2_SRST_MASK) == 0U)
278     {
279     }
280 }
281 
282 /* @} */
283 
284 /*!
285  * @name Initialization and deinitialization
286  * @{
287  */
288 
289 /*!
290  * @brief Initializes an UART instance with the user configuration structure and the peripheral clock.
291  *
292  * This function configures the UART module with user-defined settings. Call the UART_GetDefaultConfig() function
293  * to configure the configuration structure and get the default configuration.
294  * The example below shows how to use this API to configure the UART.
295  * @code
296  *  uart_config_t uartConfig;
297  *  uartConfig.baudRate_Bps = 115200U;
298  *  uartConfig.parityMode = kUART_ParityDisabled;
299  *  uartConfig.dataBitsCount = kUART_EightDataBits;
300  *  uartConfig.stopBitCount = kUART_OneStopBit;
301  *  uartConfig.txFifoWatermark = 2;
302  *  uartConfig.rxFifoWatermark = 1;
303  *  uartConfig.enableAutoBaudrate = false;
304  *  uartConfig.enableTx = true;
305  *  uartConfig.enableRx = true;
306  *  UART_Init(UART1, &uartConfig, 24000000U);
307  * @endcode
308  *
309  * @param base UART peripheral base address.
310  * @param config Pointer to a user-defined configuration structure.
311  * @param srcClock_Hz UART clock source frequency in HZ.
312  * @retval kStatus_Success UART initialize succeed
313  */
314 status_t UART_Init(UART_Type *base, const uart_config_t *config, uint32_t srcClock_Hz);
315 
316 /*!
317  * @brief Deinitializes a UART instance.
318  *
319  * This function waits for transmit to complete, disables TX and RX, and disables the UART clock.
320  *
321  * @param base UART peripheral base address.
322  */
323 void UART_Deinit(UART_Type *base);
324 
325 /*!l
326  * @brief Gets the default configuration structure.
327  *
328  * This function initializes the UART configuration structure to a default value. The default
329  * values are:
330  *   uartConfig->baudRate_Bps = 115200U;
331  *   uartConfig->parityMode = kUART_ParityDisabled;
332  *   uartConfig->dataBitsCount = kUART_EightDataBits;
333  *   uartConfig->stopBitCount = kUART_OneStopBit;
334  *   uartConfig->txFifoWatermark = 2;
335  *   uartConfig->rxFifoWatermark = 1;
336  *   uartConfig->enableAutoBaudrate = flase;
337  *   uartConfig->enableTx = false;
338  *   uartConfig->enableRx = false;
339  *
340  * @param config Pointer to a configuration structure.
341  */
342 void UART_GetDefaultConfig(uart_config_t *config);
343 
344 /*!
345  * @brief Sets the UART instance baud rate.
346  *
347  * This function configures the UART module baud rate. This function is used to update
348  * the UART module baud rate after the UART module is initialized by the UART_Init.
349  * @code
350  *  UART_SetBaudRate(UART1, 115200U, 20000000U);
351  * @endcode
352  *
353  * @param base UART peripheral base address.
354  * @param baudRate_Bps UART baudrate to be set.
355  * @param srcClock_Hz UART clock source frequency in Hz.
356  * @retval kStatus_UART_BaudrateNotSupport Baudrate is not support in the current clock source.
357  * @retval kStatus_Success Set baudrate succeeded.
358  */
359 status_t UART_SetBaudRate(UART_Type *base, uint32_t baudRate_Bps, uint32_t srcClock_Hz);
360 
361 /*!
362  * @brief This function is used to Enable the UART Module.
363  *
364  * @param base UART base pointer.
365  */
UART_Enable(UART_Type * base)366 static inline void UART_Enable(UART_Type *base)
367 {
368     base->UCR1 |= UART_UCR1_UARTEN_MASK;
369 }
370 
371 /*!
372  * @brief This function is used to configure the IDLE line condition.
373  *
374  * @param base UART base pointer.
375  * @param condition IDLE line detect condition of the enumerators in @ref uart_idle_condition_t.
376  */
UART_SetIdleCondition(UART_Type * base,uart_idle_condition_t condition)377 static inline void UART_SetIdleCondition(UART_Type *base, uart_idle_condition_t condition)
378 {
379     base->UCR1 = (base->UCR1 & ~UART_UCR1_ICD_MASK) | UART_UCR1_ICD(condition);
380 }
381 
382 /*!
383  * @brief This function is used to Disable the UART Module.
384  *
385  * @param base UART base pointer.
386  */
UART_Disable(UART_Type * base)387 static inline void UART_Disable(UART_Type *base)
388 {
389     base->UCR1 &= ~UART_UCR1_UARTEN_MASK;
390 }
391 
392 /* @} */
393 
394 /*!
395  * @name Status
396  * @{
397  */
398 
399 /*!
400  * @brief This function is used to get the current status of specific
401  *        UART status flag(including interrupt flag). The available
402  *        status flag can be select from uart_status_flag_t enumeration.
403  *
404  * @param base UART base pointer.
405  * @param flag Status flag to check.
406  * @retval current state of corresponding status flag.
407  */
408 bool UART_GetStatusFlag(UART_Type *base, uint32_t flag);
409 
410 /*!
411  * @brief This function is used to clear the current status
412  *        of specific UART status flag. The available status
413  *        flag can be select from uart_status_flag_t enumeration.
414  *
415  * @param base UART base pointer.
416  * @param flag Status flag to clear.
417  */
418 void UART_ClearStatusFlag(UART_Type *base, uint32_t flag);
419 
420 /*@}*/
421 
422 /*!
423  * @name Interrupts
424  * @{
425  */
426 
427 /*!
428  * @brief Enables UART interrupts according to the provided mask.
429  *
430  * This function enables the UART interrupts according to the provided mask. The mask
431  * is a logical OR of enumeration members. See @ref _uart_interrupt_enable.
432  * For example, to enable TX empty interrupt and RX data ready interrupt, do the following.
433  * @code
434  *     UART_EnableInterrupts(UART1,kUART_TxEmptyEnable | kUART_RxDataReadyEnable);
435  * @endcode
436  *
437  * @param base UART peripheral base address.
438  * @param mask The interrupts to enable. Logical OR of @ref _uart_interrupt_enable.
439  */
440 void UART_EnableInterrupts(UART_Type *base, uint32_t mask);
441 
442 /*!
443  * @brief Disables the UART interrupts according to the provided mask.
444  *
445  * This function disables the UART interrupts according to the provided mask. The mask
446  * is a logical OR of enumeration members. See @ref _uart_interrupt_enable.
447  * For example, to disable TX empty interrupt and RX data ready interrupt do the following.
448  * @code
449  *     UART_EnableInterrupts(UART1,kUART_TxEmptyEnable | kUART_RxDataReadyEnable);
450  * @endcode
451  *
452  * @param base UART peripheral base address.
453  * @param mask The interrupts to disable. Logical OR of @ref _uart_interrupt_enable.
454  */
455 void UART_DisableInterrupts(UART_Type *base, uint32_t mask);
456 
457 /*!
458  * @brief Gets enabled UART interrupts.
459  *
460  * This function gets the enabled UART interrupts. The enabled interrupts are returned
461  * as the logical OR value of the enumerators @ref _uart_interrupt_enable. To check
462  * a specific interrupt enable status, compare the return value with enumerators
463  * in @ref _uart_interrupt_enable.
464  * For example, to check whether the TX empty interrupt is enabled:
465  * @code
466  *     uint32_t enabledInterrupts = UART_GetEnabledInterrupts(UART1);
467  *
468  *     if (kUART_TxEmptyEnable & enabledInterrupts)
469  *     {
470  *         ...
471  *     }
472  * @endcode
473  *
474  * @param base UART peripheral base address.
475  * @return UART interrupt flags which are logical OR of the enumerators in @ref _uart_interrupt_enable.
476  */
477 uint32_t UART_GetEnabledInterrupts(UART_Type *base);
478 
479 /* @} */
480 
481 /*!
482  * @name Bus Operations
483  * @{
484  */
485 
486 /*!
487  * @brief Enables or disables the UART transmitter.
488  *
489  * This function enables or disables the UART transmitter.
490  *
491  * @param base UART peripheral base address.
492  * @param enable True to enable, false to disable.
493  */
UART_EnableTx(UART_Type * base,bool enable)494 static inline void UART_EnableTx(UART_Type *base, bool enable)
495 {
496     if (enable)
497     {
498         base->UCR2 |= UART_UCR2_TXEN_MASK;
499     }
500     else
501     {
502         base->UCR2 &= ~UART_UCR2_TXEN_MASK;
503     }
504 }
505 
506 /*!
507  * @brief Enables or disables the UART receiver.
508  *
509  * This function enables or disables the UART receiver.
510  *
511  * @param base UART peripheral base address.
512  * @param enable True to enable, false to disable.
513  */
UART_EnableRx(UART_Type * base,bool enable)514 static inline void UART_EnableRx(UART_Type *base, bool enable)
515 {
516     if (enable)
517     {
518         base->UCR2 |= UART_UCR2_RXEN_MASK;
519     }
520     else
521     {
522         base->UCR2 &= ~UART_UCR2_RXEN_MASK;
523     }
524 }
525 
526 /*!
527  * @brief Writes to the transmitter register.
528  *
529  * This function is used to write data to transmitter register.
530  * The upper layer must ensure that the TX register is empty or that
531  * the TX FIFO has room before calling this function.
532  *
533  * @param base UART peripheral base address.
534  * @param data Data write to the TX register.
535  */
UART_WriteByte(UART_Type * base,uint8_t data)536 static inline void UART_WriteByte(UART_Type *base, uint8_t data)
537 {
538     base->UTXD = (uint32_t)data & UART_UTXD_TX_DATA_MASK;
539 }
540 
541 /*!
542  * @brief Reads the receiver register.
543  *
544  * This function is used to read data from receiver register.
545  * The upper layer must ensure that the receiver register is full or that
546  * the RX FIFO has data before calling this function.
547  *
548  * @param base UART peripheral base address.
549  * @return Data read from data register.
550  */
UART_ReadByte(UART_Type * base)551 static inline uint8_t UART_ReadByte(UART_Type *base)
552 {
553     return (uint8_t)((base->URXD & UART_URXD_RX_DATA_MASK) >> UART_URXD_RX_DATA_SHIFT);
554 }
555 
556 /*!
557  * @brief Writes to the TX register using a blocking method.
558  *
559  * This function polls the TX register, waits for the TX register to be empty or for the TX FIFO
560  * to have room and writes data to the TX buffer.
561  *
562  * @param base UART peripheral base address.
563  * @param data Start address of the data to write.
564  * @param length Size of the data to write.
565  * @retval kStatus_UART_Timeout Transmission timed out and was aborted.
566  * @retval kStatus_Success Successfully wrote all data.
567  */
568 status_t UART_WriteBlocking(UART_Type *base, const uint8_t *data, size_t length);
569 
570 /*!
571  * @brief Read RX data register using a blocking method.
572  *
573  * This function polls the RX register, waits for the RX register to be full or for RX FIFO to
574  * have data, and reads data from the TX register.
575  *
576  * @param base UART peripheral base address.
577  * @param data Start address of the buffer to store the received data.
578  * @param length Size of the buffer.
579  * @retval kStatus_UART_RxHardwareOverrun Receiver overrun occurred while receiving data.
580  * @retval kStatus_UART_NoiseError A noise error occurred while receiving data.
581  * @retval kStatus_UART_FramingError A framing error occurred while receiving data.
582  * @retval kStatus_UART_ParityError A parity error occurred while receiving data.
583  * @retval kStatus_UART_Timeout Transmission timed out and was aborted.
584  * @retval kStatus_Success Successfully received all data.
585  */
586 status_t UART_ReadBlocking(UART_Type *base, uint8_t *data, size_t length);
587 
588 /* @} */
589 
590 /*!
591  * @name Transactional
592  * @{
593  */
594 
595 /*!
596  * @brief Initializes the UART handle.
597  *
598  * This function initializes the UART handle which can be used for other UART
599  * transactional APIs. Usually, for a specified UART instance,
600  * call this API once to get the initialized handle.
601  *
602  * @param base UART peripheral base address.
603  * @param handle UART handle pointer.
604  * @param callback The callback function.
605  * @param userData The parameter of the callback function.
606  */
607 void UART_TransferCreateHandle(UART_Type *base,
608                                uart_handle_t *handle,
609                                uart_transfer_callback_t callback,
610                                void *userData);
611 
612 /*!
613  * @brief Sets up the RX ring buffer.
614  *
615  * This function sets up the RX ring buffer to a specific UART handle.
616  *
617  * When the RX ring buffer is used, data received are stored into the ring buffer even when the
618  * user doesn't call the UART_TransferReceiveNonBlocking() API. If data is already received
619  * in the ring buffer, the user can get the received data from the ring buffer directly.
620  *
621  * @note When using the RX ring buffer, one byte is reserved for internal use. In other
622  * words, if @p ringBufferSize is 32, only 31 bytes are used for saving data.
623  *
624  * @param base UART peripheral base address.
625  * @param handle UART handle pointer.
626  * @param ringBuffer Start address of the ring buffer for background receiving. Pass NULL to disable the ring buffer.
627  * @param ringBufferSize Size of the ring buffer.
628  */
629 void UART_TransferStartRingBuffer(UART_Type *base, uart_handle_t *handle, uint8_t *ringBuffer, size_t ringBufferSize);
630 
631 /*!
632  * @brief Aborts the background transfer and uninstalls the ring buffer.
633  *
634  * This function aborts the background transfer and uninstalls the ring buffer.
635  *
636  * @param base UART peripheral base address.
637  * @param handle UART handle pointer.
638  */
639 void UART_TransferStopRingBuffer(UART_Type *base, uart_handle_t *handle);
640 
641 /*!
642  * @brief Get the length of received data in RX ring buffer.
643  *
644  * @param handle UART handle pointer.
645  * @return Length of received data in RX ring buffer.
646  */
647 size_t UART_TransferGetRxRingBufferLength(uart_handle_t *handle);
648 
649 /*!
650  * @brief Transmits a buffer of data using the interrupt method.
651  *
652  * This function sends data using an interrupt method. This is a non-blocking function, which
653  * returns directly without waiting for all data to be written to the TX register. When
654  * all data is written to the TX register in the ISR, the UART driver calls the callback
655  * function and passes the @ref kStatus_UART_TxIdle as status parameter.
656  *
657  * @note The kStatus_UART_TxIdle is passed to the upper layer when all data is written
658  * to the TX register. However, it does not ensure that all data is sent out. Before disabling the TX,
659  * check the kUART_TransmissionCompleteFlag to ensure that the TX is finished.
660  *
661  * @param base UART peripheral base address.
662  * @param handle UART handle pointer.
663  * @param xfer UART transfer structure. See  #uart_transfer_t.
664  * @retval kStatus_Success Successfully start the data transmission.
665  * @retval kStatus_UART_TxBusy Previous transmission still not finished; data not all written to TX register yet.
666  * @retval kStatus_InvalidArgument Invalid argument.
667  */
668 status_t UART_TransferSendNonBlocking(UART_Type *base, uart_handle_t *handle, uart_transfer_t *xfer);
669 
670 /*!
671  * @brief Aborts the interrupt-driven data transmit.
672  *
673  * This function aborts the interrupt-driven data sending. The user can get the remainBytes to find out
674  * how many bytes are not sent out.
675  *
676  * @param base UART peripheral base address.
677  * @param handle UART handle pointer.
678  */
679 void UART_TransferAbortSend(UART_Type *base, uart_handle_t *handle);
680 
681 /*!
682  * @brief Gets the number of bytes written to the UART TX register.
683  *
684  * This function gets the number of bytes written to the UART TX
685  * register by using the interrupt method.
686  *
687  * @param base UART peripheral base address.
688  * @param handle UART handle pointer.
689  * @param count Send bytes count.
690  * @retval kStatus_NoTransferInProgress No send in progress.
691  * @retval kStatus_InvalidArgument The parameter is invalid.
692  * @retval kStatus_Success Get successfully through the parameter \p count;
693  */
694 status_t UART_TransferGetSendCount(UART_Type *base, uart_handle_t *handle, uint32_t *count);
695 
696 /*!
697  * @brief Receives a buffer of data using an interrupt method.
698  *
699  * This function receives data using an interrupt method. This is a non-blocking function, which
700  *  returns without waiting for all data to be received.
701  * If the RX ring buffer is used and not empty, the data in the ring buffer is copied and
702  * the parameter @p receivedBytes shows how many bytes are copied from the ring buffer.
703  * After copying, if the data in the ring buffer is not enough to read, the receive
704  * request is saved by the UART driver. When the new data arrives, the receive request
705  * is serviced first. When all data is received, the UART driver notifies the upper layer
706  * through a callback function and passes the status parameter @ref kStatus_UART_RxIdle.
707  * For example, the upper layer needs 10 bytes but there are only 5 bytes in the ring buffer.
708  * The 5 bytes are copied to the xfer->data and this function returns with the
709  * parameter @p receivedBytes set to 5. For the left 5 bytes, newly arrived data is
710  * saved from the xfer->data[5]. When 5 bytes are received, the UART driver notifies the upper layer.
711  * If the RX ring buffer is not enabled, this function enables the RX and RX interrupt
712  * to receive data to the xfer->data. When all data is received, the upper layer is notified.
713  *
714  * @param base UART peripheral base address.
715  * @param handle UART handle pointer.
716  * @param xfer UART transfer structure, see #uart_transfer_t.
717  * @param receivedBytes Bytes received from the ring buffer directly.
718  * @retval kStatus_Success Successfully queue the transfer into transmit queue.
719  * @retval kStatus_UART_RxBusy Previous receive request is not finished.
720  * @retval kStatus_InvalidArgument Invalid argument.
721  */
722 status_t UART_TransferReceiveNonBlocking(UART_Type *base,
723                                          uart_handle_t *handle,
724                                          uart_transfer_t *xfer,
725                                          size_t *receivedBytes);
726 
727 /*!
728  * @brief Aborts the interrupt-driven data receiving.
729  *
730  * This function aborts the interrupt-driven data receiving. The user can get the remainBytes to know
731  * how many bytes are not received yet.
732  *
733  * @param base UART peripheral base address.
734  * @param handle UART handle pointer.
735  */
736 void UART_TransferAbortReceive(UART_Type *base, uart_handle_t *handle);
737 
738 /*!
739  * @brief Gets the number of bytes that have been received.
740  *
741  * This function gets the number of bytes that have been received.
742  *
743  * @param base UART peripheral base address.
744  * @param handle UART handle pointer.
745  * @param count Receive bytes count.
746  * @retval kStatus_NoTransferInProgress No receive in progress.
747  * @retval kStatus_InvalidArgument Parameter is invalid.
748  * @retval kStatus_Success Get successfully through the parameter \p count;
749  */
750 status_t UART_TransferGetReceiveCount(UART_Type *base, uart_handle_t *handle, uint32_t *count);
751 
752 /*!
753  * @brief UART IRQ handle function.
754  *
755  * This function handles the UART transmit and receive IRQ request.
756  *
757  * @param base UART peripheral base address.
758  * @param irqHandle UART handle pointer.
759  */
760 void UART_TransferHandleIRQ(UART_Type *base, void *irqHandle);
761 
762 /*@}*/
763 
764 /*!
765  * @name DMA control functions.
766  * @{
767  */
768 
769 /*!
770  * @brief Enables or disables the UART transmitter DMA request.
771  *
772  * This function enables or disables the transmit request when the transmitter
773  * has one or more slots available in the TxFIFO. The fill level in the TxFIFO
774  * that generates the DMA request is controlled by the TXTL bits.
775  *
776  * @param base UART peripheral base address.
777  * @param enable True to enable, false to disable.
778  */
UART_EnableTxDMA(UART_Type * base,bool enable)779 static inline void UART_EnableTxDMA(UART_Type *base, bool enable)
780 {
781     assert(base != NULL);
782 
783     if (enable)
784     {
785         base->UCR1 |= UART_UCR1_TXDMAEN_MASK;
786     }
787     else
788     {
789         base->UCR1 &= ~UART_UCR1_TXDMAEN_MASK;
790     }
791 }
792 
793 /*!
794  * @brief Enables or disables the UART receiver DMA request.
795  *
796  * This function enables or disables the receive request when the receiver
797  * has data in the RxFIFO. The fill level in the RxFIFO at which a DMA request
798  * is generated is controlled by the RXTL bits .
799  *
800  * @param base UART peripheral base address.
801  * @param enable True to enable, false to disable.
802  */
UART_EnableRxDMA(UART_Type * base,bool enable)803 static inline void UART_EnableRxDMA(UART_Type *base, bool enable)
804 {
805     assert(base != NULL);
806 
807     if (enable)
808     {
809         base->UCR1 |= UART_UCR1_RXDMAEN_MASK;
810     }
811     else
812     {
813         base->UCR1 &= ~UART_UCR1_RXDMAEN_MASK;
814     }
815 }
816 
817 /*@}*/
818 
819 /*!
820  * @name FIFO control functions.
821  * @{
822  */
823 
824 /*!
825  * @brief This function is used to set the watermark of UART Tx FIFO.
826  *        A maskable interrupt is generated whenever the data level in
827  *        the TxFIFO falls below the Tx FIFO watermark.
828  *
829  * @param base UART base pointer.
830  * @param watermark The Tx FIFO watermark.
831  */
UART_SetTxFifoWatermark(UART_Type * base,uint8_t watermark)832 static inline void UART_SetTxFifoWatermark(UART_Type *base, uint8_t watermark)
833 {
834     assert((watermark >= 2U) && ((int32_t)watermark <= (int32_t)FSL_FEATURE_IUART_FIFO_SIZEn(base)));
835     base->UFCR = (base->UFCR & ~UART_UFCR_TXTL_MASK) | UART_UFCR_TXTL(watermark);
836 }
837 
838 /*!
839  * @brief This function is used to set the watermark of UART RTS deassertion.
840  *
841  * The RTS signal deasserts whenever the data count in RxFIFO reaches the Rx
842  * RTS watermark.
843  *
844  * @param base UART base pointer.
845  * @param watermark The Rx RTS watermark.
846  */
UART_SetRxRTSWatermark(UART_Type * base,uint8_t watermark)847 static inline void UART_SetRxRTSWatermark(UART_Type *base, uint8_t watermark)
848 {
849     assert((int32_t)watermark <= (int32_t)FSL_FEATURE_IUART_FIFO_SIZEn(base));
850     base->UCR4 = (base->UCR4 & ~UART_UCR4_CTSTL_MASK) | UART_UCR4_CTSTL(watermark);
851 }
852 
853 /*!
854  * @brief This function is used to set the watermark of UART Rx FIFO.
855  *        A maskable interrupt is generated whenever the data level in
856  *        the RxFIFO reaches the Rx FIFO watermark.
857  *
858  * @param base UART base pointer.
859  * @param watermark The Rx FIFO watermark.
860  */
UART_SetRxFifoWatermark(UART_Type * base,uint8_t watermark)861 static inline void UART_SetRxFifoWatermark(UART_Type *base, uint8_t watermark)
862 {
863     assert((int32_t)watermark <= (int32_t)FSL_FEATURE_IUART_FIFO_SIZEn(base));
864     base->UFCR = (base->UFCR & ~UART_UFCR_RXTL_MASK) | UART_UFCR_RXTL(watermark);
865 }
866 
867 /*@}*/
868 
869 /*!
870  * @name Auto baud rate detection.
871  * @{
872  */
873 
874 /*!
875  * @brief This function is used to set the enable condition of
876  *        Automatic Baud Rate Detection feature.
877  *
878  * @param base UART base pointer.
879  * @param enable Enable/Disable Automatic Baud Rate Detection feature.
880  *               - true: Enable Automatic Baud Rate Detection feature.
881  *               - false: Disable Automatic Baud Rate Detection feature.
882  */
UART_EnableAutoBaudRate(UART_Type * base,bool enable)883 static inline void UART_EnableAutoBaudRate(UART_Type *base, bool enable)
884 {
885     if (enable)
886     {
887         /* When ADET=0 and ADBR=1, automatic baud rate detection starts */
888         /* Enable automatic baud rate detection */
889         base->UCR1 |= UART_UCR1_ADBR_MASK;
890         /* Clear ADET brfore start automatic baud rate detection*/
891         base->USR2 |= UART_USR2_ADET_MASK;
892     }
893     else
894     {
895         /* Disable automatic baud rate detection */
896         base->UCR1 &= ~UART_UCR1_ADBR_MASK;
897     }
898 }
899 /*!
900  * @brief This function is used to read if the automatic baud rate detection
901  *        has finished.
902  *
903  * @param base UART base pointer.
904  * @return - true: Automatic baud rate detection has finished.
905  *         - false: Automatic baud rate detection has not finished.
906  */
UART_IsAutoBaudRateComplete(UART_Type * base)907 static inline bool UART_IsAutoBaudRateComplete(UART_Type *base)
908 {
909     if ((UART_USR2_ACST_MASK & base->USR2) != 0U)
910     {
911         base->USR2 |= UART_USR2_ACST_MASK;
912         return true;
913     }
914     else
915     {
916         return false;
917     }
918 }
919 
920 #ifdef __cplusplus
921 }
922 #endif
923 
924 /*@}*/
925 /*! @}*/
926 
927 #endif /* _FSL_UART_H_ */
928