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 #ifndef _FSL_USART_H_
9 #define _FSL_USART_H_
10 
11 #include "fsl_common.h"
12 
13 /*!
14  * @addtogroup usart_driver
15  * @{
16  */
17 
18 /*******************************************************************************
19  * Definitions
20  ******************************************************************************/
21 
22 /*! @name Driver version */
23 /*@{*/
24 /*! @brief USART driver version. */
25 #define FSL_USART_DRIVER_VERSION (MAKE_VERSION(2, 5, 1))
26 /*@}*/
27 
28 #define USART_FIFOTRIG_TXLVL_GET(base) (((base)->FIFOTRIG & USART_FIFOTRIG_TXLVL_MASK) >> USART_FIFOTRIG_TXLVL_SHIFT)
29 #define USART_FIFOTRIG_RXLVL_GET(base) (((base)->FIFOTRIG & USART_FIFOTRIG_RXLVL_MASK) >> USART_FIFOTRIG_RXLVL_SHIFT)
30 
31 /*! @brief Retry times for waiting flag. */
32 #ifndef UART_RETRY_TIMES
33 #define UART_RETRY_TIMES 0U /* Defining to zero means to keep waiting for the flag until it is assert/deassert. */
34 #endif
35 
36 /*! @brief Error codes for the USART driver. */
37 enum
38 {
39     kStatus_USART_TxBusy              = MAKE_STATUS(kStatusGroup_LPC_USART, 0),  /*!< Transmitter is busy. */
40     kStatus_USART_RxBusy              = MAKE_STATUS(kStatusGroup_LPC_USART, 1),  /*!< Receiver is busy. */
41     kStatus_USART_TxIdle              = MAKE_STATUS(kStatusGroup_LPC_USART, 2),  /*!< USART transmitter is idle. */
42     kStatus_USART_RxIdle              = MAKE_STATUS(kStatusGroup_LPC_USART, 3),  /*!< USART receiver is idle. */
43     kStatus_USART_TxError             = MAKE_STATUS(kStatusGroup_LPC_USART, 7),  /*!< Error happens on txFIFO. */
44     kStatus_USART_RxError             = MAKE_STATUS(kStatusGroup_LPC_USART, 9),  /*!< Error happens on rxFIFO. */
45     kStatus_USART_RxRingBufferOverrun = MAKE_STATUS(kStatusGroup_LPC_USART, 8),  /*!< Error happens on rx ring buffer */
46     kStatus_USART_NoiseError          = MAKE_STATUS(kStatusGroup_LPC_USART, 10), /*!< USART noise error. */
47     kStatus_USART_FramingError        = MAKE_STATUS(kStatusGroup_LPC_USART, 11), /*!< USART framing error. */
48     kStatus_USART_ParityError         = MAKE_STATUS(kStatusGroup_LPC_USART, 12), /*!< USART parity error. */
49     kStatus_USART_BaudrateNotSupport =
50         MAKE_STATUS(kStatusGroup_LPC_USART, 13), /*!< Baudrate is not support in current clock source */
51     kStatus_USART_Timeout = MAKE_STATUS(kStatusGroup_LPC_USART, 14), /*!< USART time out. */
52 };
53 
54 /*! @brief USART synchronous mode. */
55 typedef enum _usart_sync_mode
56 {
57     kUSART_SyncModeDisabled = 0x0U, /*!< Asynchronous mode.       */
58     kUSART_SyncModeSlave    = 0x2U, /*!< Synchronous slave mode.  */
59     kUSART_SyncModeMaster   = 0x3U, /*!< Synchronous master mode. */
60 } usart_sync_mode_t;
61 
62 /*! @brief USART parity mode. */
63 typedef enum _usart_parity_mode
64 {
65     kUSART_ParityDisabled = 0x0U, /*!< Parity disabled */
66     kUSART_ParityEven     = 0x2U, /*!< Parity enabled, type even, bit setting: PE|PT = 10 */
67     kUSART_ParityOdd      = 0x3U, /*!< Parity enabled, type odd,  bit setting: PE|PT = 11 */
68 } usart_parity_mode_t;
69 
70 /*! @brief USART stop bit count. */
71 typedef enum _usart_stop_bit_count
72 {
73     kUSART_OneStopBit = 0U, /*!< One stop bit */
74     kUSART_TwoStopBit = 1U, /*!< Two stop bits */
75 } usart_stop_bit_count_t;
76 
77 /*! @brief USART data size. */
78 typedef enum _usart_data_len
79 {
80     kUSART_7BitsPerChar = 0U, /*!< Seven bit mode */
81     kUSART_8BitsPerChar = 1U, /*!< Eight bit mode */
82 } usart_data_len_t;
83 
84 /*! @brief USART clock polarity configuration, used in sync mode.*/
85 typedef enum _usart_clock_polarity
86 {
87     kUSART_RxSampleOnFallingEdge = 0x0U, /*!< Un_RXD is sampled on the falling edge of SCLK. */
88     kUSART_RxSampleOnRisingEdge  = 0x1U, /*!< Un_RXD is sampled on the rising edge of SCLK. */
89 } usart_clock_polarity_t;
90 
91 /*! @brief txFIFO watermark values */
92 typedef enum _usart_txfifo_watermark
93 {
94     kUSART_TxFifo0 = 0, /*!< USART tx watermark is empty */
95     kUSART_TxFifo1 = 1, /*!< USART tx watermark at 1 item */
96     kUSART_TxFifo2 = 2, /*!< USART tx watermark at 2 items */
97     kUSART_TxFifo3 = 3, /*!< USART tx watermark at 3 items */
98     kUSART_TxFifo4 = 4, /*!< USART tx watermark at 4 items */
99     kUSART_TxFifo5 = 5, /*!< USART tx watermark at 5 items */
100     kUSART_TxFifo6 = 6, /*!< USART tx watermark at 6 items */
101     kUSART_TxFifo7 = 7, /*!< USART tx watermark at 7 items */
102 } usart_txfifo_watermark_t;
103 
104 /*! @brief rxFIFO watermark values */
105 typedef enum _usart_rxfifo_watermark
106 {
107     kUSART_RxFifo1 = 0, /*!< USART rx watermark at 1 item */
108     kUSART_RxFifo2 = 1, /*!< USART rx watermark at 2 items */
109     kUSART_RxFifo3 = 2, /*!< USART rx watermark at 3 items */
110     kUSART_RxFifo4 = 3, /*!< USART rx watermark at 4 items */
111     kUSART_RxFifo5 = 4, /*!< USART rx watermark at 5 items */
112     kUSART_RxFifo6 = 5, /*!< USART rx watermark at 6 items */
113     kUSART_RxFifo7 = 6, /*!< USART rx watermark at 7 items */
114     kUSART_RxFifo8 = 7, /*!< USART rx watermark at 8 items */
115 } usart_rxfifo_watermark_t;
116 
117 /*!
118  * @brief USART interrupt configuration structure, default settings all disabled.
119  */
120 enum _usart_interrupt_enable
121 {
122     kUSART_TxErrorInterruptEnable = (USART_FIFOINTENSET_TXERR_MASK),
123     kUSART_RxErrorInterruptEnable = (USART_FIFOINTENSET_RXERR_MASK),
124     kUSART_TxLevelInterruptEnable = (USART_FIFOINTENSET_TXLVL_MASK),
125     kUSART_RxLevelInterruptEnable = (USART_FIFOINTENSET_RXLVL_MASK),
126 };
127 
128 /*!
129  * @brief USART status flags.
130  *
131  * This provides constants for the USART status flags for use in the USART functions.
132  */
133 enum _usart_flags
134 {
135     kUSART_TxError            = (USART_FIFOSTAT_TXERR_MASK),      /*!< TEERR bit, sets if TX buffer is error */
136     kUSART_RxError            = (USART_FIFOSTAT_RXERR_MASK),      /*!< RXERR bit, sets if RX buffer is error */
137     kUSART_TxFifoEmptyFlag    = (USART_FIFOSTAT_TXEMPTY_MASK),    /*!< TXEMPTY bit, sets if TX buffer is empty */
138     kUSART_TxFifoNotFullFlag  = (USART_FIFOSTAT_TXNOTFULL_MASK),  /*!< TXNOTFULL bit, sets if TX buffer is not full */
139     kUSART_RxFifoNotEmptyFlag = (USART_FIFOSTAT_RXNOTEMPTY_MASK), /*!< RXNOEMPTY bit, sets if RX buffer is not empty */
140     kUSART_RxFifoFullFlag     = (USART_FIFOSTAT_RXFULL_MASK),     /*!< RXFULL bit, sets if RX buffer is full */
141 };
142 
143 /*! @brief USART configuration structure. */
144 typedef struct _usart_config
145 {
146     uint32_t baudRate_Bps;                /*!< USART baud rate  */
147     usart_parity_mode_t parityMode;       /*!< Parity mode, disabled (default), even, odd */
148     usart_stop_bit_count_t stopBitCount;  /*!< Number of stop bits, 1 stop bit (default) or 2 stop bits  */
149     usart_data_len_t bitCountPerChar;     /*!< Data length - 7 bit, 8 bit  */
150     bool loopback;                        /*!< Enable peripheral loopback */
151     bool enableRx;                        /*!< Enable RX */
152     bool enableTx;                        /*!< Enable TX */
153     bool enableContinuousSCLK;            /*!< USART continuous Clock generation enable in synchronous master mode. */
154     bool enableMode32k;                   /*!< USART uses 32 kHz clock from the RTC oscillator as the clock source. */
155     bool enableHardwareFlowControl;       /*!< Enable hardware control RTS/CTS */
156     usart_txfifo_watermark_t txWatermark; /*!< txFIFO watermark */
157     usart_rxfifo_watermark_t rxWatermark; /*!< rxFIFO watermark */
158     usart_sync_mode_t syncMode; /*!< Transfer mode select - asynchronous, synchronous master, synchronous slave. */
159     usart_clock_polarity_t clockPolarity; /*!< Selects the clock polarity and sampling edge in synchronous mode. */
160 } usart_config_t;
161 
162 /*! @brief USART transfer structure. */
163 typedef struct _usart_transfer
164 {
165     /*
166      * Use separate TX and RX data pointer, because TX data is const data.
167      * The member data is kept for backward compatibility.
168      */
169     union
170     {
171         uint8_t *data;         /*!< The buffer of data to be transfer.*/
172         uint8_t *rxData;       /*!< The buffer to receive data. */
173         const uint8_t *txData; /*!< The buffer of data to be sent. */
174     };
175     size_t dataSize; /*!< The byte count to be transfer. */
176 } usart_transfer_t;
177 
178 /* Forward declaration of the handle typedef. */
179 typedef struct _usart_handle usart_handle_t;
180 
181 /*! @brief USART transfer callback function. */
182 typedef void (*usart_transfer_callback_t)(USART_Type *base, usart_handle_t *handle, status_t status, void *userData);
183 
184 /*! @brief USART handle structure. */
185 struct _usart_handle
186 {
187     const uint8_t *volatile txData; /*!< Address of remaining data to send. */
188     volatile size_t txDataSize;     /*!< Size of the remaining data to send. */
189     size_t txDataSizeAll;           /*!< Size of the data to send out. */
190     uint8_t *volatile rxData;       /*!< Address of remaining data to receive. */
191     volatile size_t rxDataSize;     /*!< Size of the remaining data to receive. */
192     size_t rxDataSizeAll;           /*!< Size of the data to receive. */
193 
194     uint8_t *rxRingBuffer;              /*!< Start address of the receiver ring buffer. */
195     size_t rxRingBufferSize;            /*!< Size of the ring buffer. */
196     volatile uint16_t rxRingBufferHead; /*!< Index for the driver to store received data into ring buffer. */
197     volatile uint16_t rxRingBufferTail; /*!< Index for the user to get data from the ring buffer. */
198 
199     usart_transfer_callback_t callback; /*!< Callback function. */
200     void *userData;                     /*!< USART callback function parameter.*/
201 
202     volatile uint8_t txState; /*!< TX transfer state. */
203     volatile uint8_t rxState; /*!< RX transfer state */
204 
205     uint8_t txWatermark; /*!< txFIFO watermark */
206     uint8_t rxWatermark; /*!< rxFIFO watermark */
207 };
208 
209 /*! @brief Typedef for usart interrupt handler. */
210 typedef void (*flexcomm_usart_irq_handler_t)(USART_Type *base, usart_handle_t *handle);
211 
212 /*******************************************************************************
213  * API
214  ******************************************************************************/
215 
216 #if defined(__cplusplus)
217 extern "C" {
218 #endif /* _cplusplus */
219 
220 /*! @brief Returns instance number for USART peripheral base address. */
221 uint32_t USART_GetInstance(USART_Type *base);
222 
223 /*!
224  * @name Initialization and deinitialization
225  * @{
226  */
227 
228 /*!
229  * @brief Initializes a USART instance with user configuration structure and peripheral clock.
230  *
231  * This function configures the USART module with the user-defined settings. The user can configure the configuration
232  * structure and also get the default configuration by using the USART_GetDefaultConfig() function.
233  * Example below shows how to use this API to configure USART.
234  * @code
235  *  usart_config_t usartConfig;
236  *  usartConfig.baudRate_Bps = 115200U;
237  *  usartConfig.parityMode = kUSART_ParityDisabled;
238  *  usartConfig.stopBitCount = kUSART_OneStopBit;
239  *  USART_Init(USART1, &usartConfig, 20000000U);
240  * @endcode
241  *
242  * @param base USART peripheral base address.
243  * @param config Pointer to user-defined configuration structure.
244  * @param srcClock_Hz USART clock source frequency in HZ.
245  * @retval kStatus_USART_BaudrateNotSupport Baudrate is not support in current clock source.
246  * @retval kStatus_InvalidArgument USART base address is not valid
247  * @retval kStatus_Success Status USART initialize succeed
248  */
249 status_t USART_Init(USART_Type *base, const usart_config_t *config, uint32_t srcClock_Hz);
250 
251 /*!
252  * @brief Deinitializes a USART instance.
253  *
254  * This function waits for TX complete, disables TX and RX, and disables the USART clock.
255  *
256  * @param base USART peripheral base address.
257  */
258 void USART_Deinit(USART_Type *base);
259 
260 /*!
261  * @brief Gets the default configuration structure.
262  *
263  * This function initializes the USART configuration structure to a default value. The default
264  * values are:
265  *   usartConfig->baudRate_Bps = 115200U;
266  *   usartConfig->parityMode = kUSART_ParityDisabled;
267  *   usartConfig->stopBitCount = kUSART_OneStopBit;
268  *   usartConfig->bitCountPerChar = kUSART_8BitsPerChar;
269  *   usartConfig->loopback = false;
270  *   usartConfig->enableTx = false;
271  *   usartConfig->enableRx = false;
272  *
273  * @param config Pointer to configuration structure.
274  */
275 void USART_GetDefaultConfig(usart_config_t *config);
276 
277 /*!
278  * @brief Sets the USART instance baud rate.
279  *
280  * This function configures the USART module baud rate. This function is used to update
281  * the USART module baud rate after the USART module is initialized by the USART_Init.
282  * @code
283  *  USART_SetBaudRate(USART1, 115200U, 20000000U);
284  * @endcode
285  *
286  * @param base USART peripheral base address.
287  * @param baudrate_Bps USART baudrate to be set.
288  * @param srcClock_Hz USART clock source frequency in HZ.
289  * @retval kStatus_USART_BaudrateNotSupport Baudrate is not support in current clock source.
290  * @retval kStatus_Success Set baudrate succeed.
291  * @retval kStatus_InvalidArgument One or more arguments are invalid.
292  */
293 status_t USART_SetBaudRate(USART_Type *base, uint32_t baudrate_Bps, uint32_t srcClock_Hz);
294 
295 /*!
296  * @brief Enable 32 kHz mode which USART uses clock from the RTC oscillator as the clock source
297  *
298  * Please note that in order to use a 32 kHz clock to operate USART properly, the RTC oscillator
299  * and its 32 kHz output must be manully enabled by user, by calling RTC_Init and setting
300  * SYSCON_RTCOSCCTRL_EN bit to 1.
301  * And in 32kHz clocking mode the USART can only work at 9600 baudrate or at the baudrate that
302  * 9600 can evenly divide, eg: 4800, 3200.
303  *
304  * @param base USART peripheral base address.
305  * @param baudRate_Bps USART baudrate to be set..
306  * @param enableMode32k true is 32k mode, false is normal mode.
307  * @param srcClock_Hz USART clock source frequency in HZ.
308  * @retval kStatus_USART_BaudrateNotSupport Baudrate is not support in current clock source.
309  * @retval kStatus_Success Set baudrate succeed.
310  * @retval kStatus_InvalidArgument One or more arguments are invalid.
311  */
312 status_t USART_Enable32kMode(USART_Type *base, uint32_t baudRate_Bps, bool enableMode32k, uint32_t srcClock_Hz);
313 
314 /*!
315  * @brief Enable 9-bit data mode for USART.
316  *
317  * This function set the 9-bit mode for USART module. The 9th bit is not used for parity thus can be modified by user.
318  *
319  * @param base USART peripheral base address.
320  * @param enable true to enable, false to disable.
321  */
322 void USART_Enable9bitMode(USART_Type *base, bool enable);
323 
324 /*!
325  * @brief Set the USART slave address.
326  *
327  * This function configures the address for USART module that works as slave in 9-bit data mode. When the address
328  * detection is enabled, the frame it receices with MSB being 1 is considered as an address frame, otherwise it is
329  * considered as data frame. Once the address frame matches slave's own addresses, this slave is addressed. This
330  * address frame and its following data frames are stored in the receive buffer, otherwise the frames will be discarded.
331  * To un-address a slave, just send an address frame with unmatched address.
332  *
333  * @note Any USART instance joined in the multi-slave system can work as slave. The position of the address mark is the
334  * same as the parity bit when parity is enabled for 8 bit and 9 bit data formats.
335  *
336  * @param base USART peripheral base address.
337  * @param address USART slave address.
338  */
USART_SetMatchAddress(USART_Type * base,uint8_t address)339 static inline void USART_SetMatchAddress(USART_Type *base, uint8_t address)
340 {
341     /* Configure match address. */
342     base->ADDR = (uint32_t)address;
343 }
344 
345 /*!
346  * @brief Enable the USART match address feature.
347  *
348  * @param base USART peripheral base address.
349  * @param match true to enable match address, false to disable.
350  */
USART_EnableMatchAddress(USART_Type * base,bool match)351 static inline void USART_EnableMatchAddress(USART_Type *base, bool match)
352 {
353     /* Configure match address enable bit. */
354     if (match)
355     {
356         base->CFG |= (uint32_t)USART_CFG_AUTOADDR_MASK;
357         base->CTL |= (uint32_t)USART_CTL_ADDRDET_MASK;
358     }
359     else
360     {
361         base->CFG &= ~(uint32_t)USART_CFG_AUTOADDR_MASK;
362         base->CTL &= ~(uint32_t)USART_CTL_ADDRDET_MASK;
363     }
364 }
365 
366 /* @} */
367 
368 /*!
369  * @name Status
370  * @{
371  */
372 
373 /*!
374  * @brief Get USART status flags.
375  *
376  * This function get all USART status flags, the flags are returned as the logical
377  * OR value of the enumerators @ref _usart_flags. To check a specific status,
378  * compare the return value with enumerators in @ref _usart_flags.
379  * For example, to check whether the TX is empty:
380  * @code
381  *     if (kUSART_TxFifoNotFullFlag & USART_GetStatusFlags(USART1))
382  *     {
383  *         ...
384  *     }
385  * @endcode
386  *
387  * @param base USART peripheral base address.
388  * @return USART status flags which are ORed by the enumerators in the _usart_flags.
389  */
USART_GetStatusFlags(USART_Type * base)390 static inline uint32_t USART_GetStatusFlags(USART_Type *base)
391 {
392     return base->FIFOSTAT;
393 }
394 
395 /*!
396  * @brief Clear USART status flags.
397  *
398  * This function clear supported USART status flags
399  * Flags that can be cleared or set are:
400  *      kUSART_TxError
401  *      kUSART_RxError
402  * For example:
403  * @code
404  *     USART_ClearStatusFlags(USART1, kUSART_TxError | kUSART_RxError)
405  * @endcode
406  *
407  * @param base USART peripheral base address.
408  * @param mask status flags to be cleared.
409  */
USART_ClearStatusFlags(USART_Type * base,uint32_t mask)410 static inline void USART_ClearStatusFlags(USART_Type *base, uint32_t mask)
411 {
412     /* Only TXERR, RXERR fields support write. Remaining fields should be set to zero */
413     base->FIFOSTAT = mask & (USART_FIFOSTAT_TXERR_MASK | USART_FIFOSTAT_RXERR_MASK);
414 }
415 
416 /* @} */
417 
418 /*!
419  * @name Interrupts
420  * @{
421  */
422 
423 /*!
424  * @brief Enables USART interrupts according to the provided mask.
425  *
426  * This function enables the USART interrupts according to the provided mask. The mask
427  * is a logical OR of enumeration members. See @ref _usart_interrupt_enable.
428  * For example, to enable TX empty interrupt and RX full interrupt:
429  * @code
430  *     USART_EnableInterrupts(USART1, kUSART_TxLevelInterruptEnable | kUSART_RxLevelInterruptEnable);
431  * @endcode
432  *
433  * @param base USART peripheral base address.
434  * @param mask The interrupts to enable. Logical OR of @ref _usart_interrupt_enable.
435  */
USART_EnableInterrupts(USART_Type * base,uint32_t mask)436 static inline void USART_EnableInterrupts(USART_Type *base, uint32_t mask)
437 {
438     base->FIFOINTENSET = mask & 0xFUL;
439 }
440 
441 /*!
442  * @brief Disables USART interrupts according to a provided mask.
443  *
444  * This function disables the USART interrupts according to a provided mask. The mask
445  * is a logical OR of enumeration members. See @ref _usart_interrupt_enable.
446  * This example shows how to disable the TX empty interrupt and RX full interrupt:
447  * @code
448  *     USART_DisableInterrupts(USART1, kUSART_TxLevelInterruptEnable | kUSART_RxLevelInterruptEnable);
449  * @endcode
450  *
451  * @param base USART peripheral base address.
452  * @param mask The interrupts to disable. Logical OR of @ref _usart_interrupt_enable.
453  */
USART_DisableInterrupts(USART_Type * base,uint32_t mask)454 static inline void USART_DisableInterrupts(USART_Type *base, uint32_t mask)
455 {
456     base->FIFOINTENCLR = mask & 0xFUL;
457 }
458 
459 /*!
460  * @brief Returns enabled USART interrupts.
461  *
462  * This function returns the enabled USART interrupts.
463  *
464  * @param base USART peripheral base address.
465  */
USART_GetEnabledInterrupts(USART_Type * base)466 static inline uint32_t USART_GetEnabledInterrupts(USART_Type *base)
467 {
468     return base->FIFOINTENSET;
469 }
470 
471 /*!
472  * @brief Enable DMA for Tx
473  */
USART_EnableTxDMA(USART_Type * base,bool enable)474 static inline void USART_EnableTxDMA(USART_Type *base, bool enable)
475 {
476     if (enable)
477     {
478         base->FIFOCFG |= USART_FIFOCFG_DMATX_MASK;
479     }
480     else
481     {
482         base->FIFOCFG &= ~(USART_FIFOCFG_DMATX_MASK);
483     }
484 }
485 
486 /*!
487  * @brief Enable DMA for Rx
488  */
USART_EnableRxDMA(USART_Type * base,bool enable)489 static inline void USART_EnableRxDMA(USART_Type *base, bool enable)
490 {
491     if (enable)
492     {
493         base->FIFOCFG |= USART_FIFOCFG_DMARX_MASK;
494     }
495     else
496     {
497         base->FIFOCFG &= ~(USART_FIFOCFG_DMARX_MASK);
498     }
499 }
500 
501 /*!
502  * @brief Enable CTS.
503  * This function will determine whether CTS is used for flow control.
504  *
505  * @param base    USART peripheral base address.
506  * @param enable  Enable CTS or not, true for enable and false for disable.
507  */
USART_EnableCTS(USART_Type * base,bool enable)508 static inline void USART_EnableCTS(USART_Type *base, bool enable)
509 {
510     if (enable)
511     {
512         base->CFG |= USART_CFG_CTSEN_MASK;
513     }
514     else
515     {
516         base->CFG &= ~USART_CFG_CTSEN_MASK;
517     }
518 }
519 
520 /*!
521  * @brief Continuous Clock generation.
522  * By default, SCLK is only output while data is being transmitted in synchronous mode.
523  * Enable this funciton, SCLK will run continuously in synchronous mode, allowing
524  * characters to be received on Un_RxD independently from transmission on Un_TXD).
525  *
526  * @param base    USART peripheral base address.
527  * @param enable  Enable Continuous Clock generation mode or not, true for enable and false for disable.
528  */
USART_EnableContinuousSCLK(USART_Type * base,bool enable)529 static inline void USART_EnableContinuousSCLK(USART_Type *base, bool enable)
530 {
531     if (enable)
532     {
533         base->CTL |= USART_CTL_CC_MASK;
534     }
535     else
536     {
537         base->CTL &= ~USART_CTL_CC_MASK;
538     }
539 }
540 
541 /*!
542  * @brief Enable Continuous Clock generation bit auto clear.
543  * While enable this cuntion, the Continuous Clock bit is automatically cleared when a complete
544  * character has been received. This bit is cleared at the same time.
545  *
546  * @param base    USART peripheral base address.
547  * @param enable  Enable auto clear or not, true for enable and false for disable.
548  */
USART_EnableAutoClearSCLK(USART_Type * base,bool enable)549 static inline void USART_EnableAutoClearSCLK(USART_Type *base, bool enable)
550 {
551     if (enable)
552     {
553         base->CTL |= USART_CTL_CLRCCONRX_MASK;
554     }
555     else
556     {
557         base->CTL &= ~USART_CTL_CLRCCONRX_MASK;
558     }
559 }
560 
561 /*!
562  * @brief Sets the rx FIFO watermark.
563  *
564  * @param base USART peripheral base address.
565  * @param water Rx FIFO watermark.
566  */
USART_SetRxFifoWatermark(USART_Type * base,uint8_t water)567 static inline void USART_SetRxFifoWatermark(USART_Type *base, uint8_t water)
568 {
569     assert(water <= (USART_FIFOTRIG_RXLVL_MASK >> USART_FIFOTRIG_RXLVL_SHIFT));
570     base->FIFOTRIG = (base->FIFOTRIG & ~USART_FIFOTRIG_RXLVL_MASK) | USART_FIFOTRIG_RXLVL(water);
571 }
572 
573 /*!
574  * @brief Sets the tx FIFO watermark.
575  *
576  * @param base USART peripheral base address.
577  * @param water Tx FIFO watermark.
578  */
USART_SetTxFifoWatermark(USART_Type * base,uint8_t water)579 static inline void USART_SetTxFifoWatermark(USART_Type *base, uint8_t water)
580 {
581     assert(water <= (USART_FIFOTRIG_TXLVL_MASK >> USART_FIFOTRIG_TXLVL_SHIFT));
582     base->FIFOTRIG = (base->FIFOTRIG & ~USART_FIFOTRIG_TXLVL_MASK) | USART_FIFOTRIG_TXLVL(water);
583 }
584 /* @} */
585 
586 /*!
587  * @name Bus Operations
588  * @{
589  */
590 
591 /*!
592  * @brief Writes to the FIFOWR register.
593  *
594  * This function writes data to the txFIFO directly. The upper layer must ensure
595  * that txFIFO has space for data to write before calling this function.
596  *
597  * @param base USART peripheral base address.
598  * @param data The byte to write.
599  */
USART_WriteByte(USART_Type * base,uint8_t data)600 static inline void USART_WriteByte(USART_Type *base, uint8_t data)
601 {
602     base->FIFOWR = data;
603 }
604 
605 /*!
606  * @brief Reads the FIFORD register directly.
607  *
608  * This function reads data from the rxFIFO directly. The upper layer must
609  * ensure that the rxFIFO is not empty before calling this function.
610  *
611  * @param base USART peripheral base address.
612  * @return The byte read from USART data register.
613  */
USART_ReadByte(USART_Type * base)614 static inline uint8_t USART_ReadByte(USART_Type *base)
615 {
616     return (uint8_t)base->FIFORD;
617 }
618 
619 /*!
620  * @brief Gets the rx FIFO data count.
621  *
622  * @param base USART peripheral base address.
623  * @return rx FIFO data count.
624  */
USART_GetRxFifoCount(USART_Type * base)625 static inline uint8_t USART_GetRxFifoCount(USART_Type *base)
626 {
627     return (uint8_t)((base->FIFOSTAT & USART_FIFOSTAT_RXLVL_MASK) >> USART_FIFOSTAT_RXLVL_SHIFT);
628 }
629 
630 /*!
631  * @brief Gets the tx FIFO data count.
632  *
633  * @param base USART peripheral base address.
634  * @return tx FIFO data count.
635  */
USART_GetTxFifoCount(USART_Type * base)636 static inline uint8_t USART_GetTxFifoCount(USART_Type *base)
637 {
638     return (uint8_t)((base->FIFOSTAT & USART_FIFOSTAT_TXLVL_MASK) >> USART_FIFOSTAT_TXLVL_SHIFT);
639 }
640 
641 /*!
642  * @brief Transmit an address frame in 9-bit data mode.
643  *
644  * @param base USART peripheral base address.
645  * @param address USART slave address.
646  */
647 void USART_SendAddress(USART_Type *base, uint8_t address);
648 
649 /*!
650  * @brief Writes to the TX register using a blocking method.
651  *
652  * This function polls the TX register, waits for the TX register to be empty or for the TX FIFO
653  * to have room and writes data to the TX buffer.
654  *
655  * @param base USART peripheral base address.
656  * @param data Start address of the data to write.
657  * @param length Size of the data to write.
658  * @retval kStatus_USART_Timeout Transmission timed out and was aborted.
659  * @retval kStatus_InvalidArgument Invalid argument.
660  * @retval kStatus_Success Successfully wrote all data.
661  */
662 status_t USART_WriteBlocking(USART_Type *base, const uint8_t *data, size_t length);
663 
664 /*!
665  * @brief Read RX data register using a blocking method.
666  *
667  * This function polls the RX register, waits for the RX register to be full or for RX FIFO to
668  * have data and read data from the TX register.
669  *
670  * @param base USART peripheral base address.
671  * @param data Start address of the buffer to store the received data.
672  * @param length Size of the buffer.
673  * @retval kStatus_USART_FramingError Receiver overrun happened while receiving data.
674  * @retval kStatus_USART_ParityError Noise error happened while receiving data.
675  * @retval kStatus_USART_NoiseError Framing error happened while receiving data.
676  * @retval kStatus_USART_RxError Overflow or underflow rxFIFO happened.
677  * @retval kStatus_USART_Timeout Transmission timed out and was aborted.
678  * @retval kStatus_Success Successfully received all data.
679  */
680 status_t USART_ReadBlocking(USART_Type *base, uint8_t *data, size_t length);
681 
682 /* @} */
683 
684 /*!
685  * @name Transactional
686  * @{
687  */
688 
689 /*!
690  * @brief Initializes the USART handle.
691  *
692  * This function initializes the USART handle which can be used for other USART
693  * transactional APIs. Usually, for a specified USART instance,
694  * call this API once to get the initialized handle.
695  *
696  * @param base USART peripheral base address.
697  * @param handle USART handle pointer.
698  * @param callback The callback function.
699  * @param userData The parameter of the callback function.
700  */
701 status_t USART_TransferCreateHandle(USART_Type *base,
702                                     usart_handle_t *handle,
703                                     usart_transfer_callback_t callback,
704                                     void *userData);
705 
706 /*!
707  * @brief Transmits a buffer of data using the interrupt method.
708  *
709  * This function sends data using an interrupt method. This is a non-blocking function, which
710  * returns directly without waiting for all data to be written to the TX register. When
711  * all data is written to the TX register in the IRQ handler, the USART driver calls the callback
712  * function and passes the @ref kStatus_USART_TxIdle as status parameter.
713  *
714  * @note The kStatus_USART_TxIdle is passed to the upper layer when all data is written
715  * to the TX register. However it does not ensure that all data are sent out. Before disabling the TX,
716  * check the kUSART_TransmissionCompleteFlag to ensure that the TX is finished.
717  *
718  * @param base USART peripheral base address.
719  * @param handle USART handle pointer.
720  * @param xfer USART transfer structure. See  #usart_transfer_t.
721  * @retval kStatus_Success Successfully start the data transmission.
722  * @retval kStatus_USART_TxBusy Previous transmission still not finished, data not all written to TX register yet.
723  * @retval kStatus_InvalidArgument Invalid argument.
724  */
725 status_t USART_TransferSendNonBlocking(USART_Type *base, usart_handle_t *handle, usart_transfer_t *xfer);
726 
727 /*!
728  * @brief Sets up the RX ring buffer.
729  *
730  * This function sets up the RX ring buffer to a specific USART handle.
731  *
732  * When the RX ring buffer is used, data received are stored into the ring buffer even when the
733  * user doesn't call the USART_TransferReceiveNonBlocking() API. If there is already data received
734  * in the ring buffer, the user can get the received data from the ring buffer directly.
735  *
736  * @note When using the RX ring buffer, one byte is reserved for internal use. In other
737  * words, if @p ringBufferSize is 32, then only 31 bytes are used for saving data.
738  *
739  * @param base USART peripheral base address.
740  * @param handle USART handle pointer.
741  * @param ringBuffer Start address of the ring buffer for background receiving. Pass NULL to disable the ring buffer.
742  * @param ringBufferSize size of the ring buffer.
743  */
744 void USART_TransferStartRingBuffer(USART_Type *base,
745                                    usart_handle_t *handle,
746                                    uint8_t *ringBuffer,
747                                    size_t ringBufferSize);
748 
749 /*!
750  * @brief Aborts the background transfer and uninstalls the ring buffer.
751  *
752  * This function aborts the background transfer and uninstalls the ring buffer.
753  *
754  * @param base USART peripheral base address.
755  * @param handle USART handle pointer.
756  */
757 void USART_TransferStopRingBuffer(USART_Type *base, usart_handle_t *handle);
758 
759 /*!
760  * @brief Get the length of received data in RX ring buffer.
761  *
762  * @param handle USART handle pointer.
763  * @return Length of received data in RX ring buffer.
764  */
765 size_t USART_TransferGetRxRingBufferLength(usart_handle_t *handle);
766 
767 /*!
768  * @brief Aborts the interrupt-driven data transmit.
769  *
770  * This function aborts the interrupt driven data sending. The user can get the remainBtyes to find out
771  * how many bytes are still not sent out.
772  *
773  * @param base USART peripheral base address.
774  * @param handle USART handle pointer.
775  */
776 void USART_TransferAbortSend(USART_Type *base, usart_handle_t *handle);
777 
778 /*!
779  * @brief Get the number of bytes that have been sent out to bus.
780  *
781  * This function gets the number of bytes that have been sent out to bus by interrupt method.
782  *
783  * @param base USART peripheral base address.
784  * @param handle USART handle pointer.
785  * @param count Send bytes count.
786  * @retval kStatus_NoTransferInProgress No send in progress.
787  * @retval kStatus_InvalidArgument Parameter is invalid.
788  * @retval kStatus_Success Get successfully through the parameter \p count;
789  */
790 status_t USART_TransferGetSendCount(USART_Type *base, usart_handle_t *handle, uint32_t *count);
791 
792 /*!
793  * @brief Receives a buffer of data using an interrupt method.
794  *
795  * This function receives data using an interrupt method. This is a non-blocking function, which
796  *  returns without waiting for all data to be received.
797  * If the RX ring buffer is used and not empty, the data in the ring buffer is copied and
798  * the parameter @p receivedBytes shows how many bytes are copied from the ring buffer.
799  * After copying, if the data in the ring buffer is not enough to read, the receive
800  * request is saved by the USART driver. When the new data arrives, the receive request
801  * is serviced first. When all data is received, the USART driver notifies the upper layer
802  * through a callback function and passes the status parameter @ref kStatus_USART_RxIdle.
803  * For example, the upper layer needs 10 bytes but there are only 5 bytes in the ring buffer.
804  * The 5 bytes are copied to the xfer->data and this function returns with the
805  * parameter @p receivedBytes set to 5. For the left 5 bytes, newly arrived data is
806  * saved from the xfer->data[5]. When 5 bytes are received, the USART driver notifies the upper layer.
807  * If the RX ring buffer is not enabled, this function enables the RX and RX interrupt
808  * to receive data to the xfer->data. When all data is received, the upper layer is notified.
809  *
810  * @param base USART peripheral base address.
811  * @param handle USART handle pointer.
812  * @param xfer USART transfer structure, see #usart_transfer_t.
813  * @param receivedBytes Bytes received from the ring buffer directly.
814  * @retval kStatus_Success Successfully queue the transfer into transmit queue.
815  * @retval kStatus_USART_RxBusy Previous receive request is not finished.
816  * @retval kStatus_InvalidArgument Invalid argument.
817  */
818 status_t USART_TransferReceiveNonBlocking(USART_Type *base,
819                                           usart_handle_t *handle,
820                                           usart_transfer_t *xfer,
821                                           size_t *receivedBytes);
822 
823 /*!
824  * @brief Aborts the interrupt-driven data receiving.
825  *
826  * This function aborts the interrupt-driven data receiving. The user can get the remainBytes to find out
827  * how many bytes not received yet.
828  *
829  * @param base USART peripheral base address.
830  * @param handle USART handle pointer.
831  */
832 void USART_TransferAbortReceive(USART_Type *base, usart_handle_t *handle);
833 
834 /*!
835  * @brief Get the number of bytes that have been received.
836  *
837  * This function gets the number of bytes that have been received.
838  *
839  * @param base USART peripheral base address.
840  * @param handle USART handle pointer.
841  * @param count Receive bytes count.
842  * @retval kStatus_NoTransferInProgress No receive in progress.
843  * @retval kStatus_InvalidArgument Parameter is invalid.
844  * @retval kStatus_Success Get successfully through the parameter \p count;
845  */
846 status_t USART_TransferGetReceiveCount(USART_Type *base, usart_handle_t *handle, uint32_t *count);
847 
848 /*!
849  * @brief USART IRQ handle function.
850  *
851  * This function handles the USART transmit and receive IRQ request.
852  *
853  * @param base USART peripheral base address.
854  * @param handle USART handle pointer.
855  */
856 void USART_TransferHandleIRQ(USART_Type *base, usart_handle_t *handle);
857 
858 /* @} */
859 
860 #if defined(__cplusplus)
861 }
862 #endif
863 
864 /*! @}*/
865 
866 #endif /* _FSL_USART_H_ */
867