1 /*
2  * Copyright 2017-2022 NXP
3  * All rights reserved.
4  *
5  * SPDX-License-Identifier: BSD-3-Clause
6  */
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 /*! @name Driver version */
22 /*! @{ */
23 /*! @brief USART driver version. */
24 #define FSL_USART_DRIVER_VERSION (MAKE_VERSION(2, 5, 1))
25 /*! @} */
26 
27 /*! @brief Macro gate for enable transaction API.  1 for enable, 0 for disable. */
28 #ifndef FSL_SDK_ENABLE_USART_DRIVER_TRANSACTIONAL_APIS
29 #define FSL_SDK_ENABLE_USART_DRIVER_TRANSACTIONAL_APIS 1
30 #endif
31 
32 /*! @brief USART baud rate auto generate switch gate. 1 for enable, 0 for disable*/
33 #ifndef FSL_SDK_USART_DRIVER_ENABLE_BAUDRATE_AUTO_GENERATE
34 #define FSL_SDK_USART_DRIVER_ENABLE_BAUDRATE_AUTO_GENERATE 1
35 #endif /* FSL_SDK_USART_DRIVER_ENABLE_BAUDRATE_AUTO_GENERATE */
36 
37 #if !(defined(FSL_SDK_USART_DRIVER_ENABLE_BAUDRATE_AUTO_GENERATE) && FSL_SDK_USART_DRIVER_ENABLE_BAUDRATE_AUTO_GENERATE)
38 /*! @brief Macro for generating baud rate manually.
39  * <pre>
40  *  Table of common register values for generating baud rate in specific USART clock frequency.
41  *     Target baud rate(Hz)  |  USART clock frequency(Hz)   |      OSR value      |    BRG value   |
42  *         9600              |         12,000,000           |       10            |       124      |
43  *         9600              |         24,000,000           |       10            |       249      |
44  *         9600              |         30,000,000           |       16            |       194      |
45  *         9600              |         12,000,000           | NO OSR register(16) |       77       |
46  *         115200            |         12,000,000           |       13            |       7        |
47  *         115200            |         24,000,000           |       16            |       12       |
48  *         115200            |         30,000,000           |       13            |       19       |
49  * </pre>
50  *  @note: The formula for generating a baud rate is: baduRate = usartClock_Hz / (OSR * (BRG +1)).
51  *        For some devices, there is no OSR register for setting, so the default OSR value is 16 in formula.
52  *        If the USART clock source can not generate a precise baud rate, please setting the FRG register
53  *        in SYSCON module to get a precise USART clock frequency.
54  */
55 /* Macro for setiing OSR register. */
56 #ifndef FSL_SDK_USART_OSR_VALUE
57 #define FSL_SDK_USART_OSR_VALUE 10U
58 #endif /* FSL_SDK_USART_OSR_VALUE */
59 
60 /* Macro for setting BRG register. */
61 #ifndef FSL_SDK_USART_BRG_VALUE
62 #define FSL_SDK_USART_BRG_VALUE 124U
63 #endif /* FSL_SDK_USART_BRG_VALUE */
64 #endif /* FSL_SDK_USART_DRIVER_ENABLE_BAUDRATE_AUTO_GENERATE */
65 
66 /*! @brief Retry times for waiting flag. */
67 #ifndef UART_RETRY_TIMES
68 #define UART_RETRY_TIMES 0U /*!< Defining to zero means to keep waiting for the flag until it is assert/deassert. */
69 #endif
70 
71 /*! @brief Error codes for the USART driver. */
72 enum
73 {
74     kStatus_USART_TxBusy              = MAKE_STATUS(kStatusGroup_LPC_USART, 0),  /*!< Transmitter is busy. */
75     kStatus_USART_RxBusy              = MAKE_STATUS(kStatusGroup_LPC_USART, 1),  /*!< Receiver is busy. */
76     kStatus_USART_TxIdle              = MAKE_STATUS(kStatusGroup_LPC_USART, 2),  /*!< USART transmitter is idle. */
77     kStatus_USART_RxIdle              = MAKE_STATUS(kStatusGroup_LPC_USART, 3),  /*!< USART receiver is idle. */
78     kStatus_USART_TxError             = MAKE_STATUS(kStatusGroup_LPC_USART, 4),  /*!< Error happens on tx. */
79     kStatus_USART_RxError             = MAKE_STATUS(kStatusGroup_LPC_USART, 5),  /*!< Error happens on rx. */
80     kStatus_USART_RxRingBufferOverrun = MAKE_STATUS(kStatusGroup_LPC_USART, 6),  /*!< Error happens on rx ring buffer */
81     kStatus_USART_NoiseError          = MAKE_STATUS(kStatusGroup_LPC_USART, 7),  /*!< USART noise error. */
82     kStatus_USART_FramingError        = MAKE_STATUS(kStatusGroup_LPC_USART, 8),  /*!< USART framing error. */
83     kStatus_USART_ParityError         = MAKE_STATUS(kStatusGroup_LPC_USART, 9),  /*!< USART parity error. */
84     kStatus_USART_HardwareOverrun     = MAKE_STATUS(kStatusGroup_LPC_USART, 10), /*!< USART hardware over flow. */
85     kStatus_USART_BaudrateNotSupport =
86         MAKE_STATUS(kStatusGroup_LPC_USART, 11), /*!< Baudrate is not support in current clock source */
87     kStatus_USART_Timeout = MAKE_STATUS(kStatusGroup_LPC_USART, 12), /*!< USART times out. */
88 #if defined(FSL_FEATURE_USART_HAS_RXIDLETO_CHECK) && FSL_FEATURE_USART_HAS_RXIDLETO_CHECK
89     kStatus_USART_RxIdleTimeout = MAKE_STATUS(kStatusGroup_LPC_USART, 13), /*!< USART receive idle times out. */
90 #endif
91 };
92 
93 /*! @brief USART parity mode. */
94 typedef enum _usart_parity_mode
95 {
96     kUSART_ParityDisabled = 0x0U, /*!< Parity disabled */
97     kUSART_ParityEven     = 0x2U, /*!< Parity enabled, type even, bit setting: PARITYSEL = 10 */
98     kUSART_ParityOdd      = 0x3U, /*!< Parity enabled, type odd,  bit setting: PARITYSEL = 11 */
99 } usart_parity_mode_t;
100 
101 /*! @brief USART synchronous mode. */
102 typedef enum _usart_sync_mode
103 {
104     kUSART_SyncModeDisabled = 0x0U, /*!< Asynchronous mode.       */
105     kUSART_SyncModeSlave    = 0x2U, /*!< Synchronous slave mode.  */
106     kUSART_SyncModeMaster   = 0x3U, /*!< Synchronous master mode. */
107 } usart_sync_mode_t;
108 
109 /*! @brief USART stop bit count. */
110 typedef enum _usart_stop_bit_count
111 {
112     kUSART_OneStopBit = 0U, /*!< One stop bit */
113     kUSART_TwoStopBit = 1U, /*!< Two stop bits */
114 } usart_stop_bit_count_t;
115 
116 /*! @brief USART data size. */
117 typedef enum _usart_data_len
118 {
119     kUSART_7BitsPerChar = 0U, /*!< Seven bit mode */
120     kUSART_8BitsPerChar = 1U, /*!< Eight bit mode */
121 } usart_data_len_t;
122 
123 /*! @brief USART clock polarity configuration, used in sync mode.*/
124 typedef enum _usart_clock_polarity
125 {
126     kUSART_RxSampleOnFallingEdge = 0x0U, /*!< Un_RXD is sampled on the falling edge of SCLK. */
127     kUSART_RxSampleOnRisingEdge  = 0x1U, /*!< Un_RXD is sampled on the rising edge of SCLK. */
128 } usart_clock_polarity_t;
129 
130 /*!
131  * @brief USART interrupt configuration structure, default settings all disabled.
132  */
133 enum _usart_interrupt_enable
134 {
135     kUSART_RxReadyInterruptEnable = (USART_INTENSET_RXRDYEN_MASK), /*!< Receive ready interrupt. */
136     kUSART_TxReadyInterruptEnable = (USART_INTENSET_TXRDYEN_MASK), /*!< Transmit ready interrupt. */
137 #if defined(FSL_FEATURE_USART_HAS_INTENSET_TXIDLEEN) && FSL_FEATURE_USART_HAS_INTENSET_TXIDLEEN
138     kUSART_TxIdleInterruptEnable = (USART_INTENSET_TXIDLEEN_MASK), /*!< Transmit idle interrupt. */
139 #endif
140     kUSART_DeltaCtsInterruptEnable        = (USART_INTENSET_DELTACTSEN_MASK),   /*!< Cts pin change interrupt. */
141     kUSART_TxDisableInterruptEnable       = (USART_INTENSET_TXDISEN_MASK),      /*!< Transmit disable interrupt. */
142     kUSART_HardwareOverRunInterruptEnable = (USART_INTENSET_OVERRUNEN_MASK),    /*!< hardware ove run interrupt. */
143     kUSART_RxBreakInterruptEnable         = (USART_INTENSET_DELTARXBRKEN_MASK), /*!< Receive break interrupt. */
144     kUSART_RxStartInterruptEnable         = (USART_INTENSET_STARTEN_MASK),      /*!< Receive ready interrupt. */
145     kUSART_FramErrorInterruptEnable       = (USART_INTENSET_FRAMERREN_MASK),    /*!< Receive start interrupt. */
146     kUSART_ParityErrorInterruptEnable     = (USART_INTENSET_PARITYERREN_MASK),  /*!< Receive frame error interrupt. */
147     kUSART_RxNoiseInterruptEnable         = (USART_INTENSET_RXNOISEEN_MASK),    /*!< Receive noise error interrupt. */
148 #if defined(FSL_FEATURE_USART_HAS_RXIDLETO_CHECK) && FSL_FEATURE_USART_HAS_RXIDLETO_CHECK
149     kUSART_RxIdleTimeoutInterruptEnable = (USART_INTENSET_RXIDLETOEN_MASK), /*!< Receive idle timeout interrupt. */
150 #endif
151 #if defined(FSL_FEATURE_USART_HAS_ABERR_CHECK) && FSL_FEATURE_USART_HAS_ABERR_CHECK
152     kUSART_AutoBaudErrorInterruptEnable = (USART_INTENSET_ABERREN_MASK), /*!< Receive auto baud error interrupt. */
153 #endif
154     kUSART_AllInterruptEnable =
155         (USART_INTENSET_RXRDYEN_MASK | USART_INTENSET_TXRDYEN_MASK |
156 #if defined(FSL_FEATURE_USART_HAS_INTENSET_TXIDLEEN) && FSL_FEATURE_USART_HAS_INTENSET_TXIDLEEN
157          USART_INTENSET_TXIDLEEN_MASK |
158 #endif
159          USART_INTENSET_DELTACTSEN_MASK | USART_INTENSET_TXDISEN_MASK | USART_INTENSET_OVERRUNEN_MASK |
160          USART_INTENSET_DELTARXBRKEN_MASK | USART_INTENSET_STARTEN_MASK | USART_INTENSET_FRAMERREN_MASK |
161          USART_INTENSET_PARITYERREN_MASK | USART_INTENSET_RXNOISEEN_MASK
162 #if defined(FSL_FEATURE_USART_HAS_ABERR_CHECK) && FSL_FEATURE_USART_HAS_ABERR_CHECK
163          | USART_INTENSET_ABERREN_MASK
164 #endif
165          ), /*!< All interrupt. */
166 };
167 
168 /*!
169  * @brief USART status flags.
170  *
171  * This provides constants for the USART status flags for use in the USART functions.
172  */
173 enum _usart_flags
174 {
175     kUSART_RxReady             = (USART_STAT_RXRDY_MASK),        /*!< Receive ready flag. */
176     kUSART_RxIdleFlag          = (USART_STAT_RXIDLE_MASK),       /*!< Receive IDLE flag. */
177     kUSART_TxReady             = (USART_STAT_TXRDY_MASK),        /*!< Transmit ready flag. */
178     kUSART_TxIdleFlag          = (USART_STAT_TXIDLE_MASK),       /*!< Transmit idle flag. */
179     kUSART_CtsState            = (USART_STAT_CTS_MASK),          /*!< Cts pin status. */
180     kUSART_DeltaCtsFlag        = (USART_STAT_DELTACTS_MASK),     /*!< Cts pin change flag. */
181     kUSART_TxDisableFlag       = (USART_STAT_TXDISSTAT_MASK),    /*!< Transmit disable flag. */
182     kUSART_HardwareOverrunFlag = (USART_STAT_OVERRUNINT_MASK),   /*!< Hardware over run flag. */
183     kUSART_RxBreakFlag         = (USART_STAT_DELTARXBRK_MASK),   /*!< Receive break flag. */
184     kUSART_RxStartFlag         = (USART_STAT_START_MASK),        /*!< receive start flag. */
185     kUSART_FramErrorFlag       = (USART_STAT_FRAMERRINT_MASK),   /*!< Frame error flag. */
186     kUSART_ParityErrorFlag     = (USART_STAT_PARITYERRINT_MASK), /*!< Parity error flag. */
187     kUSART_RxNoiseFlag         = (USART_STAT_RXNOISEINT_MASK),   /*!< Receive noise flag. */
188 #if defined(FSL_FEATURE_USART_HAS_ABERR_CHECK) && FSL_FEATURE_USART_HAS_ABERR_CHECK
189     kUSART_AutoBaudErrorFlag = (USART_STAT_ABERR_MASK), /*!< Auto baud error flag. */
190 #endif
191 #if defined(FSL_FEATURE_USART_HAS_RXIDLETO_CHECK) && FSL_FEATURE_USART_HAS_RXIDLETO_CHECK
192     kUSART_RxIdleTimeoutFlag = (USART_STAT_RXIDLETO_MASK), /*!< Receive idle timeout flag. */
193 #endif
194 };
195 
196 /*! @brief USART configuration structure. */
197 typedef struct _usart_config
198 {
199     uint32_t baudRate_Bps;                /*!< USART baud rate  */
200     bool enableRx;                        /*!< USART receive enable.  */
201     bool enableTx;                        /*!< USART transmit enable.  */
202     bool loopback;                        /*!< Enable peripheral loopback */
203     bool enableContinuousSCLK;            /*!< USART continuous Clock generation enable in synchronous master mode. */
204     bool enableHardwareFlowControl;       /*!< Enable hardware control RTS/CTS */
205     usart_parity_mode_t parityMode;       /*!< Parity mode, disabled (default), even, odd */
206     usart_stop_bit_count_t stopBitCount;  /*!< Number of stop bits, 1 stop bit (default) or 2 stop bits  */
207     usart_data_len_t bitCountPerChar;     /*!< Data length - 7 bit, 8 bit  */
208     usart_sync_mode_t syncMode;           /*!< Transfer mode - asynchronous, synchronous master, synchronous slave. */
209     usart_clock_polarity_t clockPolarity; /*!< Selects the clock polarity and sampling edge in sync mode. */
210 #if defined(FSL_FEATURE_USART_HAS_RXIDLETO_CHECK) && FSL_FEATURE_USART_HAS_RXIDLETO_CHECK
211     uint8_t rxIdleTimeout; /*!< Receive idle bytes. Value [0,7]. Set the value to n then the idle byte count will be
212                                  the (n)th power of 2.*/
213 #endif
214 } usart_config_t;
215 
216 #if defined(FSL_SDK_ENABLE_USART_DRIVER_TRANSACTIONAL_APIS) && (FSL_SDK_ENABLE_USART_DRIVER_TRANSACTIONAL_APIS)
217 /*! @brief USART transfer structure. */
218 typedef struct _usart_transfer
219 {
220     /*
221      * Use separate TX and RX data pointer, because TX data is const data.
222      * The member data is kept for backward compatibility.
223      */
224     union
225     {
226         uint8_t *data;         /*!< The buffer of data to be transfer.*/
227         uint8_t *rxData;       /*!< The buffer to receive data. */
228         const uint8_t *txData; /*!< The buffer of data to be sent. */
229     };
230     size_t dataSize; /*!< The byte count to be transfer. */
231 } usart_transfer_t;
232 
233 /* Forward declaration of the handle typedef. */
234 typedef struct _usart_handle usart_handle_t;
235 
236 /*! @brief USART transfer callback function. */
237 typedef void (*usart_transfer_callback_t)(USART_Type *base, usart_handle_t *handle, status_t status, void *userData);
238 
239 /*! @brief USART handle structure. */
240 struct _usart_handle
241 {
242     const uint8_t *volatile txData; /*!< Address of remaining data to send. */
243     volatile size_t txDataSize;     /*!< Size of the remaining data to send. */
244     size_t txDataSizeAll;           /*!< Size of the data to send out. */
245     uint8_t *volatile rxData;       /*!< Address of remaining data to receive. */
246     volatile size_t rxDataSize;     /*!< Size of the remaining data to receive. */
247     size_t rxDataSizeAll;           /*!< Size of the data to receive. */
248 
249     uint8_t *rxRingBuffer;              /*!< Start address of the receiver ring buffer. */
250     size_t rxRingBufferSize;            /*!< Size of the ring buffer. */
251     volatile uint16_t rxRingBufferHead; /*!< Index for the driver to store received data into ring buffer. */
252     volatile uint16_t rxRingBufferTail; /*!< Index for the user to get data from the ring buffer. */
253 
254     usart_transfer_callback_t callback; /*!< Callback function. */
255     void *userData;                     /*!< USART callback function parameter.*/
256 
257     volatile uint8_t txState; /*!< TX transfer state. */
258     volatile uint8_t rxState; /*!< RX transfer state */
259 };
260 #endif /* FSL_SDK_ENABLE_USART_DRIVER_TRANSACTIONAL_APIS */
261 
262 /*******************************************************************************
263  * API
264  ******************************************************************************/
265 
266 #if defined(__cplusplus)
267 extern "C" {
268 #endif /* _cplusplus */
269 
270 /*!
271  * @name Get the instance of USART
272  * @{
273  */
274 
275 /*! @brief Returns instance number for USART peripheral base address. */
276 uint32_t USART_GetInstance(USART_Type *base);
277 /*! @} */
278 
279 /*!
280  * @name Initialization and deinitialization
281  * @{
282  */
283 
284 /*!
285  * @brief Initializes a USART instance with user configuration structure and peripheral clock.
286  *
287  * This function configures the USART module with the user-defined settings. The user can configure the configuration
288  * structure and also get the default configuration by using the USART_GetDefaultConfig() function.
289  * Example below shows how to use this API to configure USART.
290  * @code
291  *  usart_config_t usartConfig;
292  *  usartConfig.baudRate_Bps = 115200U;
293  *  usartConfig.parityMode = kUSART_ParityDisabled;
294  *  usartConfig.stopBitCount = kUSART_OneStopBit;
295  *  USART_Init(USART1, &usartConfig, 20000000U);
296  * @endcode
297  *
298  * @param base USART peripheral base address.
299  * @param config Pointer to user-defined configuration structure.
300  * @param srcClock_Hz USART clock source frequency in HZ.
301  * @retval kStatus_USART_BaudrateNotSupport Baudrate is not support in current clock source.
302  * @retval kStatus_InvalidArgument USART base address is not valid
303  * @retval kStatus_Success Status USART initialize succeed
304  */
305 status_t USART_Init(USART_Type *base, const usart_config_t *config, uint32_t srcClock_Hz);
306 
307 /*!
308  * @brief Deinitializes a USART instance.
309  *
310  * This function waits for TX complete, disables the USART clock.
311  *
312  * @param base USART peripheral base address.
313  */
314 void USART_Deinit(USART_Type *base);
315 
316 /*!
317  * @brief Gets the default configuration structure.
318  *
319  * This function initializes the USART configuration structure to a default value. The default
320  * values are:
321  *   usartConfig->baudRate_Bps = 9600U;
322  *   usartConfig->parityMode = kUSART_ParityDisabled;
323  *   usartConfig->stopBitCount = kUSART_OneStopBit;
324  *   usartConfig->bitCountPerChar = kUSART_8BitsPerChar;
325  *   usartConfig->loopback = false;
326  *   usartConfig->enableTx = false;
327  *   usartConfig->enableRx = false;
328  *   ...
329  * @param config Pointer to configuration structure.
330  */
331 void USART_GetDefaultConfig(usart_config_t *config);
332 
333 /*!
334  * @brief Sets the USART instance baud rate.
335  *
336  * This function configures the USART module baud rate. This function is used to update
337  * the USART module baud rate after the USART module is initialized by the USART_Init.
338  * @code
339  *  USART_SetBaudRate(USART1, 115200U, 20000000U);
340  * @endcode
341  *
342  * @param base USART peripheral base address.
343  * @param baudrate_Bps USART baudrate to be set.
344  * @param srcClock_Hz USART clock source frequency in HZ.
345  * @retval kStatus_USART_BaudrateNotSupport Baudrate is not support in current clock source.
346  * @retval kStatus_Success Set baudrate succeed.
347  * @retval kStatus_InvalidArgument One or more arguments are invalid.
348  */
349 status_t USART_SetBaudRate(USART_Type *base, uint32_t baudrate_Bps, uint32_t srcClock_Hz);
350 /*! @} */
351 
352 /*!
353  * @name Status
354  * @{
355  */
356 
357 /*!
358  * @brief Get USART status flags.
359  *
360  * This function get all USART status flags, the flags are returned as the logical
361  * OR value of the enumerators @ref _usart_flags. To check a specific status,
362  * compare the return value with enumerators in @ref _usart_flags.
363  * For example, to check whether the RX is ready:
364  * @code
365  *     if (kUSART_RxReady & USART_GetStatusFlags(USART1))
366  *     {
367  *         ...
368  *     }
369  * @endcode
370  *
371  * @param base USART peripheral base address.
372  * @return USART status flags which are ORed by the enumerators in the _usart_flags.
373  */
USART_GetStatusFlags(USART_Type * base)374 static inline uint32_t USART_GetStatusFlags(USART_Type *base)
375 {
376     return base->STAT;
377 }
378 
379 /*!
380  * @brief Clear USART status flags.
381  *
382  * This function clear supported USART status flags
383  * For example:
384  * @code
385  *     USART_ClearStatusFlags(USART1, kUSART_HardwareOverrunFlag)
386  * @endcode
387  *
388  * @param base USART peripheral base address.
389  * @param mask status flags to be cleared.
390  */
USART_ClearStatusFlags(USART_Type * base,uint32_t mask)391 static inline void USART_ClearStatusFlags(USART_Type *base, uint32_t mask)
392 {
393     base->STAT = mask;
394 }
395 /*! @} */
396 
397 /*!
398  * @name Interrupts
399  * @{
400  */
401 
402 /*!
403  * @brief Enables USART interrupts according to the provided mask.
404  *
405  * This function enables the USART interrupts according to the provided mask. The mask
406  * is a logical OR of enumeration members. See @ref _usart_interrupt_enable.
407  * For example, to enable TX ready interrupt and RX ready interrupt:
408  * @code
409  *     USART_EnableInterrupts(USART1, kUSART_RxReadyInterruptEnable | kUSART_TxReadyInterruptEnable);
410  * @endcode
411  *
412  * @param base USART peripheral base address.
413  * @param mask The interrupts to enable. Logical OR of @ref _usart_interrupt_enable.
414  */
USART_EnableInterrupts(USART_Type * base,uint32_t mask)415 static inline void USART_EnableInterrupts(USART_Type *base, uint32_t mask)
416 {
417     base->INTENSET = mask & 0x0003FFFFU;
418 }
419 /*!
420  * @brief Disables USART interrupts according to a provided mask.
421  *
422  * This function disables the USART interrupts according to a provided mask. The mask
423  * is a logical OR of enumeration members. See @ref _usart_interrupt_enable.
424  * This example shows how to disable the TX ready interrupt and RX ready interrupt:
425  * @code
426  *     USART_DisableInterrupts(USART1, kUSART_TxReadyInterruptEnable | kUSART_RxReadyInterruptEnable);
427  * @endcode
428  *
429  * @param base USART peripheral base address.
430  * @param mask The interrupts to disable. Logical OR of @ref _usart_interrupt_enable.
431  */
USART_DisableInterrupts(USART_Type * base,uint32_t mask)432 static inline void USART_DisableInterrupts(USART_Type *base, uint32_t mask)
433 {
434     base->INTENCLR = mask & 0x0003FFFFU;
435 }
436 #if defined(FSL_FEATURE_USART_HAS_RXIDLETO_CHECK) && FSL_FEATURE_USART_HAS_RXIDLETO_CHECK
437 /*!
438  * @brief Config the USART instance rx idle timeout.
439  *
440  * This function configures the number idle character of USART rx idle.
441  * For 115200,8n1, 1 character timing is 86.81uS = 1/ (115200/(1start+8data+0parity+1stop))
442  * @code
443  *    USART_SetRxIdleTimeout(USART1, 1);
444  * @endcode
445  *
446  * @param base USART peripheral base address.
447  * @param rxIdleTimeout The configuration of UART rx idle .
448  */
USART_SetRxIdleTimeout(USART_Type * base,uint8_t rxIdleTimeout)449 static inline void USART_SetRxIdleTimeout(USART_Type *base, uint8_t rxIdleTimeout)
450 {
451     base->CTL = (base->CTL & ~USART_CTL_RXIDLETOCFG_MASK) | USART_CTL_RXIDLETOCFG((uint32_t)rxIdleTimeout);
452 }
453 #endif
454 /*!
455  * @brief Returns enabled USART interrupts.
456  *
457  * This function returns the enabled USART interrupts.
458  *
459  * @param base USART peripheral base address.
460  */
USART_GetEnabledInterrupts(USART_Type * base)461 static inline uint32_t USART_GetEnabledInterrupts(USART_Type *base)
462 {
463     return base->INTENSET;
464 }
465 /*! @} */
466 
467 /*!
468  * @name Bus Operations
469  * @{
470  */
471 
472 /*!
473  * @brief Continuous Clock generation.
474  * By default, SCLK is only output while data is being transmitted in synchronous mode.
475  * Enable this funciton, SCLK will run continuously in synchronous mode, allowing
476  * characters to be received on Un_RxD independently from transmission on Un_TXD).
477  *
478  * @param base    USART peripheral base address.
479  * @param enable  Enable Continuous Clock generation mode or not, true for enable and false for disable.
480  */
USART_EnableContinuousSCLK(USART_Type * base,bool enable)481 static inline void USART_EnableContinuousSCLK(USART_Type *base, bool enable)
482 {
483     if (enable)
484     {
485         base->CTL |= USART_CTL_CC_MASK;
486     }
487     else
488     {
489         base->CTL &= ~USART_CTL_CC_MASK;
490     }
491 }
492 
493 /*!
494  * @brief Enable Continuous Clock generation bit auto clear.
495  * While enable this cuntion, the Continuous Clock bit is automatically cleared when a complete
496  * character has been received. This bit is cleared at the same time.
497  *
498  * @param base    USART peripheral base address.
499  * @param enable  Enable auto clear or not, true for enable and false for disable.
500  */
USART_EnableAutoClearSCLK(USART_Type * base,bool enable)501 static inline void USART_EnableAutoClearSCLK(USART_Type *base, bool enable)
502 {
503     if (enable)
504     {
505         base->CTL |= USART_CTL_CLRCCONRX_MASK;
506     }
507     else
508     {
509         base->CTL &= ~USART_CTL_CLRCCONRX_MASK;
510     }
511 }
512 
513 /*!
514  * @brief Enable CTS.
515  * This function will determine whether CTS is used for flow control.
516  *
517  * @param base    USART peripheral base address.
518  * @param enable  Enable CTS or not, true for enable and false for disable.
519  */
USART_EnableCTS(USART_Type * base,bool enable)520 static inline void USART_EnableCTS(USART_Type *base, bool enable)
521 {
522     if (enable)
523     {
524         base->CFG |= USART_CFG_CTSEN_MASK;
525     }
526     else
527     {
528         base->CFG &= ~USART_CFG_CTSEN_MASK;
529     }
530 }
531 
532 /*!
533  * @brief Enable the USART transmit.
534  *
535  * This function will enable or disable the USART transmit.
536  *
537  * @param base USART peripheral base address.
538  * @param enable true for enable and false for disable.
539  */
USART_EnableTx(USART_Type * base,bool enable)540 static inline void USART_EnableTx(USART_Type *base, bool enable)
541 {
542     if (enable)
543     {
544         /* Make sure the USART module is enabled. */
545         base->CFG |= USART_CFG_ENABLE_MASK;
546         base->CTL &= ~USART_CTL_TXDIS_MASK;
547     }
548     else
549     {
550         base->CTL |= USART_CTL_TXDIS_MASK;
551     }
552 }
553 
554 /*!
555  * @brief Enable the USART receive.
556  *
557  * This function will enable or disable the USART receive.
558  * Note: if the transmit is enabled, the receive will not be disabled.
559  * @param base USART peripheral base address.
560  * @param enable true for enable and false for disable.
561  */
USART_EnableRx(USART_Type * base,bool enable)562 static inline void USART_EnableRx(USART_Type *base, bool enable)
563 {
564     if (enable)
565     {
566         /* Make sure the USART module is enabled. */
567         base->CFG |= USART_CFG_ENABLE_MASK;
568     }
569     else
570     {
571         /* If the transmit is disabled too. */
572         if ((base->CTL & USART_CTL_TXDIS_MASK) != 0U)
573         {
574             base->CFG &= ~USART_CFG_ENABLE_MASK;
575         }
576     }
577 }
578 
579 /*!
580  * @brief Writes to the TXDAT  register.
581  *
582  * This function will writes data to the TXDAT automatly.The upper layer must ensure
583  * that TXDATA has space for data to write before calling this function.
584  *
585  * @param base USART peripheral base address.
586  * @param data The byte to write.
587  */
USART_WriteByte(USART_Type * base,uint8_t data)588 static inline void USART_WriteByte(USART_Type *base, uint8_t data)
589 {
590     base->TXDAT = data;
591 }
592 
593 /*!
594  * @brief Reads the RXDAT directly.
595  *
596  * This function reads data from the RXDAT automatly. The upper layer must
597  * ensure that the RXDAT is not empty before calling this function.
598  *
599  * @param base USART peripheral base address.
600  * @return The byte read from USART data register.
601  */
USART_ReadByte(USART_Type * base)602 static inline uint8_t USART_ReadByte(USART_Type *base)
603 {
604     return (uint8_t)base->RXDAT & 0xFFU;
605 }
606 
607 /*!
608  * @brief Writes to the TX register using a blocking method.
609  *
610  * This function polls the TX register, waits for the TX register to be empty.
611  *
612  * @param base USART peripheral base address.
613  * @param data Start address of the data to write.
614  * @param length Size of the data to write.
615  * @retval kStatus_USART_Timeout Transmission timed out and was aborted.
616  * @retval kStatus_Success Successfully wrote all data.
617  */
618 status_t USART_WriteBlocking(USART_Type *base, const uint8_t *data, size_t length);
619 
620 /*!
621  * @brief Read RX data register using a blocking method.
622  *
623  * This function polls the RX register, waits for the RX register to be full.
624  *
625  * @param base USART peripheral base address.
626  * @param data Start address of the buffer to store the received data.
627  * @param length Size of the buffer.
628  * @retval kStatus_USART_FramingError Receiver overrun happened while receiving data.
629  * @retval kStatus_USART_ParityError Noise error happened while receiving data.
630  * @retval kStatus_USART_NoiseError Framing error happened while receiving data.
631  * @retval kStatus_USART_RxError Overflow or underflow happened.
632  * @retval kStatus_USART_Timeout Transmission timed out and was aborted.
633  * @retval kStatus_Success Successfully received all data.
634  */
635 status_t USART_ReadBlocking(USART_Type *base, uint8_t *data, size_t length);
636 
637 /*! @} */
638 
639 #if defined(FSL_SDK_ENABLE_USART_DRIVER_TRANSACTIONAL_APIS) && (FSL_SDK_ENABLE_USART_DRIVER_TRANSACTIONAL_APIS)
640 /*!
641  * @name Transactional
642  * @{
643  */
644 
645 /*!
646  * @brief Initializes the USART handle.
647  *
648  * This function initializes the USART handle which can be used for other USART
649  * transactional APIs. Usually, for a specified USART instance,
650  * call this API once to get the initialized handle.
651  *
652  * @param base USART peripheral base address.
653  * @param handle USART handle pointer.
654  * @param callback The callback function.
655  * @param userData The parameter of the callback function.
656  */
657 status_t USART_TransferCreateHandle(USART_Type *base,
658                                     usart_handle_t *handle,
659                                     usart_transfer_callback_t callback,
660                                     void *userData);
661 
662 /*!
663  * @brief Transmits a buffer of data using the interrupt method.
664  *
665  * This function sends data using an interrupt method. This is a non-blocking function, which
666  * returns directly without waiting for all data to be written to the TX register. When
667  * all data is written to the TX register in the IRQ handler, the USART driver calls the callback
668  * function and passes the @ref kStatus_USART_TxIdle as status parameter.
669  *
670  * @note The kStatus_USART_TxIdle is passed to the upper layer when all data is written
671  * to the TX register. However it does not ensure that all data are sent out. Before disabling the TX,
672  * check the kUSART_TransmissionCompleteFlag to ensure that the TX is finished.
673  *
674  * @param base USART peripheral base address.
675  * @param handle USART handle pointer.
676  * @param xfer USART transfer structure. See  #usart_transfer_t.
677  * @retval kStatus_Success Successfully start the data transmission.
678  * @retval kStatus_USART_TxBusy Previous transmission still not finished, data not all written to TX register yet.
679  * @retval kStatus_InvalidArgument Invalid argument.
680  */
681 status_t USART_TransferSendNonBlocking(USART_Type *base, usart_handle_t *handle, usart_transfer_t *xfer);
682 
683 /*!
684  * @brief Sets up the RX ring buffer.
685  *
686  * This function sets up the RX ring buffer to a specific USART handle.
687  *
688  * When the RX ring buffer is used, data received are stored into the ring buffer even when the
689  * user doesn't call the USART_TransferReceiveNonBlocking() API. If there is already data received
690  * in the ring buffer, the user can get the received data from the ring buffer directly.
691  *
692  * @note When using the RX ring buffer, one byte is reserved for internal use. In other
693  * words, if ringBufferSize is 32, then only 31 bytes are used for saving data.
694  *
695  * @param base USART peripheral base address.
696  * @param handle USART handle pointer.
697  * @param ringBuffer Start address of the ring buffer for background receiving. Pass NULL to disable the ring buffer.
698  * @param ringBufferSize size of the ring buffer.
699  */
700 void USART_TransferStartRingBuffer(USART_Type *base,
701                                    usart_handle_t *handle,
702                                    uint8_t *ringBuffer,
703                                    size_t ringBufferSize);
704 
705 /*!
706  * @brief Aborts the background transfer and uninstalls the ring buffer.
707  *
708  * This function aborts the background transfer and uninstalls the ring buffer.
709  *
710  * @param base USART peripheral base address.
711  * @param handle USART handle pointer.
712  */
713 void USART_TransferStopRingBuffer(USART_Type *base, usart_handle_t *handle);
714 
715 /*!
716  * @brief Get the length of received data in RX ring buffer.
717  *
718  * @param handle USART handle pointer.
719  * @return Length of received data in RX ring buffer.
720  */
721 size_t USART_TransferGetRxRingBufferLength(usart_handle_t *handle);
722 
723 /*!
724  * @brief Aborts the interrupt-driven data transmit.
725  *
726  * This function aborts the interrupt driven data sending. The user can get the remainBtyes to find out
727  * how many bytes are still not sent out.
728  *
729  * @param base USART peripheral base address.
730  * @param handle USART handle pointer.
731  */
732 void USART_TransferAbortSend(USART_Type *base, usart_handle_t *handle);
733 
734 /*!
735  * @brief Get the number of bytes that have been written to USART TX register.
736  *
737  * This function gets the number of bytes that have been written to USART TX
738  * register by interrupt method.
739  *
740  * @param base USART peripheral base address.
741  * @param handle USART handle pointer.
742  * @param count Send bytes count.
743  * @retval kStatus_NoTransferInProgress No send in progress.
744  * @retval kStatus_InvalidArgument Parameter is invalid.
745  * @retval kStatus_Success Get successfully through the parameter \p count;
746  */
747 status_t USART_TransferGetSendCount(USART_Type *base, usart_handle_t *handle, uint32_t *count);
748 
749 /*!
750  * @brief Receives a buffer of data using an interrupt method.
751  *
752  * This function receives data using an interrupt method. This is a non-blocking function, which
753  *  returns without waiting for all data to be received.
754  * If the RX ring buffer is used and not empty, the data in the ring buffer is copied and
755  * the parameter @p receivedBytes shows how many bytes are copied from the ring buffer.
756  * After copying, if the data in the ring buffer is not enough to read, the receive
757  * request is saved by the USART driver. When the new data arrives, the receive request
758  * is serviced first. When all data is received, the USART driver notifies the upper layer
759  * through a callback function and passes the status parameter @ref kStatus_USART_RxIdle.
760  * For example, the upper layer needs 10 bytes but there are only 5 bytes in the ring buffer.
761  * The 5 bytes are copied to the xfer->data and this function returns with the
762  * parameter @p receivedBytes set to 5. For the left 5 bytes, newly arrived data is
763  * saved from the xfer->data[5]. When 5 bytes are received, the USART driver notifies the upper layer.
764  * If the RX ring buffer is not enabled, this function enables the RX and RX interrupt
765  * to receive data to the xfer->data. When all data is received, the upper layer is notified.
766  *
767  * @param base USART peripheral base address.
768  * @param handle USART handle pointer.
769  * @param xfer USART transfer structure, see #usart_transfer_t.
770  * @param receivedBytes Bytes received from the ring buffer directly.
771  * @retval kStatus_Success Successfully queue the transfer into transmit queue.
772  * @retval kStatus_USART_RxBusy Previous receive request is not finished.
773  * @retval kStatus_InvalidArgument Invalid argument.
774  */
775 status_t USART_TransferReceiveNonBlocking(USART_Type *base,
776                                           usart_handle_t *handle,
777                                           usart_transfer_t *xfer,
778                                           size_t *receivedBytes);
779 
780 /*!
781  * @brief Aborts the interrupt-driven data receiving.
782  *
783  * This function aborts the interrupt-driven data receiving. The user can get the remainBytes to find out
784  * how many bytes not received yet.
785  *
786  * @param base USART peripheral base address.
787  * @param handle USART handle pointer.
788  */
789 void USART_TransferAbortReceive(USART_Type *base, usart_handle_t *handle);
790 
791 /*!
792  * @brief Get the number of bytes that have been received.
793  *
794  * This function gets the number of bytes that have been received.
795  *
796  * @param base USART peripheral base address.
797  * @param handle USART handle pointer.
798  * @param count Receive bytes count.
799  * @retval kStatus_NoTransferInProgress No receive in progress.
800  * @retval kStatus_InvalidArgument Parameter is invalid.
801  * @retval kStatus_Success Get successfully through the parameter \p count;
802  */
803 status_t USART_TransferGetReceiveCount(USART_Type *base, usart_handle_t *handle, uint32_t *count);
804 
805 /*!
806  * @brief USART IRQ handle function.
807  *
808  * This function handles the USART transmit and receive IRQ request.
809  *
810  * @param base USART peripheral base address.
811  * @param handle USART handle pointer.
812  */
813 void USART_TransferHandleIRQ(USART_Type *base, usart_handle_t *handle);
814 
815 /*! @} */
816 #endif
817 
818 #if defined(__cplusplus)
819 }
820 #endif
821 
822 /*! @}*/
823 
824 #endif /* FSL_USART_H_ */
825