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, 0))
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  * @ref USART_CTL_RXIDLETOCFG
443  * @code
444  *    USART_SetRxIdleTimeout(USART1, 1);
445  * @endcode
446  *
447  * @param base USART peripheral base address.
448  * @param rxIdleTimeout The configuration of UART rx idle .
449  */
USART_SetRxIdleTimeout(USART_Type * base,uint8_t rxIdleTimeout)450 static inline void USART_SetRxIdleTimeout(USART_Type *base, uint8_t rxIdleTimeout)
451 {
452     base->CTL = (base->CTL & ~USART_CTL_RXIDLETOCFG_MASK) | USART_CTL_RXIDLETOCFG((uint32_t)rxIdleTimeout);
453 }
454 #endif
455 /*!
456  * @brief Returns enabled USART interrupts.
457  *
458  * This function returns the enabled USART interrupts.
459  *
460  * @param base USART peripheral base address.
461  */
USART_GetEnabledInterrupts(USART_Type * base)462 static inline uint32_t USART_GetEnabledInterrupts(USART_Type *base)
463 {
464     return base->INTENSET;
465 }
466 /* @} */
467 
468 /*!
469  * @name Bus Operations
470  * @{
471  */
472 
473 /*!
474  * @brief Continuous Clock generation.
475  * By default, SCLK is only output while data is being transmitted in synchronous mode.
476  * Enable this funciton, SCLK will run continuously in synchronous mode, allowing
477  * characters to be received on Un_RxD independently from transmission on Un_TXD).
478  *
479  * @param base    USART peripheral base address.
480  * @param enable  Enable Continuous Clock generation mode or not, true for enable and false for disable.
481  */
USART_EnableContinuousSCLK(USART_Type * base,bool enable)482 static inline void USART_EnableContinuousSCLK(USART_Type *base, bool enable)
483 {
484     if (enable)
485     {
486         base->CTL |= USART_CTL_CC_MASK;
487     }
488     else
489     {
490         base->CTL &= ~USART_CTL_CC_MASK;
491     }
492 }
493 
494 /*!
495  * @brief Enable Continuous Clock generation bit auto clear.
496  * While enable this cuntion, the Continuous Clock bit is automatically cleared when a complete
497  * character has been received. This bit is cleared at the same time.
498  *
499  * @param base    USART peripheral base address.
500  * @param enable  Enable auto clear or not, true for enable and false for disable.
501  */
USART_EnableAutoClearSCLK(USART_Type * base,bool enable)502 static inline void USART_EnableAutoClearSCLK(USART_Type *base, bool enable)
503 {
504     if (enable)
505     {
506         base->CTL |= USART_CTL_CLRCCONRX_MASK;
507     }
508     else
509     {
510         base->CTL &= ~USART_CTL_CLRCCONRX_MASK;
511     }
512 }
513 
514 /*!
515  * @brief Enable CTS.
516  * This function will determine whether CTS is used for flow control.
517  *
518  * @param base    USART peripheral base address.
519  * @param enable  Enable CTS or not, true for enable and false for disable.
520  */
USART_EnableCTS(USART_Type * base,bool enable)521 static inline void USART_EnableCTS(USART_Type *base, bool enable)
522 {
523     if (enable)
524     {
525         base->CFG |= USART_CFG_CTSEN_MASK;
526     }
527     else
528     {
529         base->CFG &= ~USART_CFG_CTSEN_MASK;
530     }
531 }
532 
533 /*!
534  * @brief Enable the USART transmit.
535  *
536  * This function will enable or disable the USART transmit.
537  *
538  * @param base USART peripheral base address.
539  * @param enable true for enable and false for disable.
540  */
USART_EnableTx(USART_Type * base,bool enable)541 static inline void USART_EnableTx(USART_Type *base, bool enable)
542 {
543     if (enable)
544     {
545         /* Make sure the USART module is enabled. */
546         base->CFG |= USART_CFG_ENABLE_MASK;
547         base->CTL &= ~USART_CTL_TXDIS_MASK;
548     }
549     else
550     {
551         base->CTL |= USART_CTL_TXDIS_MASK;
552     }
553 }
554 
555 /*!
556  * @brief Enable the USART receive.
557  *
558  * This function will enable or disable the USART receive.
559  * Note: if the transmit is enabled, the receive will not be disabled.
560  * @param base USART peripheral base address.
561  * @param enable true for enable and false for disable.
562  */
USART_EnableRx(USART_Type * base,bool enable)563 static inline void USART_EnableRx(USART_Type *base, bool enable)
564 {
565     if (enable)
566     {
567         /* Make sure the USART module is enabled. */
568         base->CFG |= USART_CFG_ENABLE_MASK;
569     }
570     else
571     {
572         /* If the transmit is disabled too. */
573         if ((base->CTL & USART_CTL_TXDIS_MASK) != 0U)
574         {
575             base->CFG &= ~USART_CFG_ENABLE_MASK;
576         }
577     }
578 }
579 
580 /*!
581  * @brief Writes to the TXDAT  register.
582  *
583  * This function will writes data to the TXDAT automatly.The upper layer must ensure
584  * that TXDATA has space for data to write before calling this function.
585  *
586  * @param base USART peripheral base address.
587  * @param data The byte to write.
588  */
USART_WriteByte(USART_Type * base,uint8_t data)589 static inline void USART_WriteByte(USART_Type *base, uint8_t data)
590 {
591     base->TXDAT = data;
592 }
593 
594 /*!
595  * @brief Reads the RXDAT directly.
596  *
597  * This function reads data from the RXDAT automatly. The upper layer must
598  * ensure that the RXDAT is not empty before calling this function.
599  *
600  * @param base USART peripheral base address.
601  * @return The byte read from USART data register.
602  */
USART_ReadByte(USART_Type * base)603 static inline uint8_t USART_ReadByte(USART_Type *base)
604 {
605     return (uint8_t)base->RXDAT & 0xFFU;
606 }
607 
608 /*!
609  * @brief Writes to the TX register using a blocking method.
610  *
611  * This function polls the TX register, waits for the TX register to be empty.
612  *
613  * @param base USART peripheral base address.
614  * @param data Start address of the data to write.
615  * @param length Size of the data to write.
616  * @retval kStatus_USART_Timeout Transmission timed out and was aborted.
617  * @retval kStatus_Success Successfully wrote all data.
618  */
619 status_t USART_WriteBlocking(USART_Type *base, const uint8_t *data, size_t length);
620 
621 /*!
622  * @brief Read RX data register using a blocking method.
623  *
624  * This function polls the RX register, waits for the RX register to be full.
625  *
626  * @param base USART peripheral base address.
627  * @param data Start address of the buffer to store the received data.
628  * @param length Size of the buffer.
629  * @retval kStatus_USART_FramingError Receiver overrun happened while receiving data.
630  * @retval kStatus_USART_ParityError Noise error happened while receiving data.
631  * @retval kStatus_USART_NoiseError Framing error happened while receiving data.
632  * @retval kStatus_USART_RxError Overflow or underflow happened.
633  * @retval kStatus_USART_Timeout Transmission timed out and was aborted.
634  * @retval kStatus_Success Successfully received all data.
635  */
636 status_t USART_ReadBlocking(USART_Type *base, uint8_t *data, size_t length);
637 
638 /* @} */
639 
640 #if defined(FSL_SDK_ENABLE_USART_DRIVER_TRANSACTIONAL_APIS) && (FSL_SDK_ENABLE_USART_DRIVER_TRANSACTIONAL_APIS)
641 /*!
642  * @name Transactional
643  * @{
644  */
645 
646 /*!
647  * @brief Initializes the USART handle.
648  *
649  * This function initializes the USART handle which can be used for other USART
650  * transactional APIs. Usually, for a specified USART instance,
651  * call this API once to get the initialized handle.
652  *
653  * @param base USART peripheral base address.
654  * @param handle USART handle pointer.
655  * @param callback The callback function.
656  * @param userData The parameter of the callback function.
657  */
658 status_t USART_TransferCreateHandle(USART_Type *base,
659                                     usart_handle_t *handle,
660                                     usart_transfer_callback_t callback,
661                                     void *userData);
662 
663 /*!
664  * @brief Transmits a buffer of data using the interrupt method.
665  *
666  * This function sends data using an interrupt method. This is a non-blocking function, which
667  * returns directly without waiting for all data to be written to the TX register. When
668  * all data is written to the TX register in the IRQ handler, the USART driver calls the callback
669  * function and passes the @ref kStatus_USART_TxIdle as status parameter.
670  *
671  * @note The kStatus_USART_TxIdle is passed to the upper layer when all data is written
672  * to the TX register. However it does not ensure that all data are sent out. Before disabling the TX,
673  * check the kUSART_TransmissionCompleteFlag to ensure that the TX is finished.
674  *
675  * @param base USART peripheral base address.
676  * @param handle USART handle pointer.
677  * @param xfer USART transfer structure. See  #usart_transfer_t.
678  * @retval kStatus_Success Successfully start the data transmission.
679  * @retval kStatus_USART_TxBusy Previous transmission still not finished, data not all written to TX register yet.
680  * @retval kStatus_InvalidArgument Invalid argument.
681  */
682 status_t USART_TransferSendNonBlocking(USART_Type *base, usart_handle_t *handle, usart_transfer_t *xfer);
683 
684 /*!
685  * @brief Sets up the RX ring buffer.
686  *
687  * This function sets up the RX ring buffer to a specific USART handle.
688  *
689  * When the RX ring buffer is used, data received are stored into the ring buffer even when the
690  * user doesn't call the USART_TransferReceiveNonBlocking() API. If there is already data received
691  * in the ring buffer, the user can get the received data from the ring buffer directly.
692  *
693  * @note When using the RX ring buffer, one byte is reserved for internal use. In other
694  * words, if ringBufferSize is 32, then only 31 bytes are used for saving data.
695  *
696  * @param base USART peripheral base address.
697  * @param handle USART handle pointer.
698  * @param ringBuffer Start address of the ring buffer for background receiving. Pass NULL to disable the ring buffer.
699  * @param ringBufferSize size of the ring buffer.
700  */
701 void USART_TransferStartRingBuffer(USART_Type *base,
702                                    usart_handle_t *handle,
703                                    uint8_t *ringBuffer,
704                                    size_t ringBufferSize);
705 
706 /*!
707  * @brief Aborts the background transfer and uninstalls the ring buffer.
708  *
709  * This function aborts the background transfer and uninstalls the ring buffer.
710  *
711  * @param base USART peripheral base address.
712  * @param handle USART handle pointer.
713  */
714 void USART_TransferStopRingBuffer(USART_Type *base, usart_handle_t *handle);
715 
716 /*!
717  * @brief Get the length of received data in RX ring buffer.
718  *
719  * @param handle USART handle pointer.
720  * @return Length of received data in RX ring buffer.
721  */
722 size_t USART_TransferGetRxRingBufferLength(usart_handle_t *handle);
723 
724 /*!
725  * @brief Aborts the interrupt-driven data transmit.
726  *
727  * This function aborts the interrupt driven data sending. The user can get the remainBtyes to find out
728  * how many bytes are still not sent out.
729  *
730  * @param base USART peripheral base address.
731  * @param handle USART handle pointer.
732  */
733 void USART_TransferAbortSend(USART_Type *base, usart_handle_t *handle);
734 
735 /*!
736  * @brief Get the number of bytes that have been written to USART TX register.
737  *
738  * This function gets the number of bytes that have been written to USART TX
739  * register by interrupt method.
740  *
741  * @param base USART peripheral base address.
742  * @param handle USART handle pointer.
743  * @param count Send bytes count.
744  * @retval kStatus_NoTransferInProgress No send in progress.
745  * @retval kStatus_InvalidArgument Parameter is invalid.
746  * @retval kStatus_Success Get successfully through the parameter \p count;
747  */
748 status_t USART_TransferGetSendCount(USART_Type *base, usart_handle_t *handle, uint32_t *count);
749 
750 /*!
751  * @brief Receives a buffer of data using an interrupt method.
752  *
753  * This function receives data using an interrupt method. This is a non-blocking function, which
754  *  returns without waiting for all data to be received.
755  * If the RX ring buffer is used and not empty, the data in the ring buffer is copied and
756  * the parameter @p receivedBytes shows how many bytes are copied from the ring buffer.
757  * After copying, if the data in the ring buffer is not enough to read, the receive
758  * request is saved by the USART driver. When the new data arrives, the receive request
759  * is serviced first. When all data is received, the USART driver notifies the upper layer
760  * through a callback function and passes the status parameter @ref kStatus_USART_RxIdle.
761  * For example, the upper layer needs 10 bytes but there are only 5 bytes in the ring buffer.
762  * The 5 bytes are copied to the xfer->data and this function returns with the
763  * parameter @p receivedBytes set to 5. For the left 5 bytes, newly arrived data is
764  * saved from the xfer->data[5]. When 5 bytes are received, the USART driver notifies the upper layer.
765  * If the RX ring buffer is not enabled, this function enables the RX and RX interrupt
766  * to receive data to the xfer->data. When all data is received, the upper layer is notified.
767  *
768  * @param base USART peripheral base address.
769  * @param handle USART handle pointer.
770  * @param xfer USART transfer structure, see #usart_transfer_t.
771  * @param receivedBytes Bytes received from the ring buffer directly.
772  * @retval kStatus_Success Successfully queue the transfer into transmit queue.
773  * @retval kStatus_USART_RxBusy Previous receive request is not finished.
774  * @retval kStatus_InvalidArgument Invalid argument.
775  */
776 status_t USART_TransferReceiveNonBlocking(USART_Type *base,
777                                           usart_handle_t *handle,
778                                           usart_transfer_t *xfer,
779                                           size_t *receivedBytes);
780 
781 /*!
782  * @brief Aborts the interrupt-driven data receiving.
783  *
784  * This function aborts the interrupt-driven data receiving. The user can get the remainBytes to find out
785  * how many bytes not received yet.
786  *
787  * @param base USART peripheral base address.
788  * @param handle USART handle pointer.
789  */
790 void USART_TransferAbortReceive(USART_Type *base, usart_handle_t *handle);
791 
792 /*!
793  * @brief Get the number of bytes that have been received.
794  *
795  * This function gets the number of bytes that have been received.
796  *
797  * @param base USART peripheral base address.
798  * @param handle USART handle pointer.
799  * @param count Receive bytes count.
800  * @retval kStatus_NoTransferInProgress No receive in progress.
801  * @retval kStatus_InvalidArgument Parameter is invalid.
802  * @retval kStatus_Success Get successfully through the parameter \p count;
803  */
804 status_t USART_TransferGetReceiveCount(USART_Type *base, usart_handle_t *handle, uint32_t *count);
805 
806 /*!
807  * @brief USART IRQ handle function.
808  *
809  * This function handles the USART transmit and receive IRQ request.
810  *
811  * @param base USART peripheral base address.
812  * @param handle USART handle pointer.
813  */
814 void USART_TransferHandleIRQ(USART_Type *base, usart_handle_t *handle);
815 
816 /* @} */
817 #endif
818 
819 #if defined(__cplusplus)
820 }
821 #endif
822 
823 /*! @}*/
824 
825 #endif /* _FSL_USART_H_ */
826