1 /***********************************************************************************************************************
2  * Copyright [2015-2017] Renesas Electronics Corporation and/or its licensors. All Rights Reserved.
3  *
4  * This file is part of Renesas SynergyTM Software Package (SSP)
5  *
6  * The contents of this file (the "contents") are proprietary and confidential to Renesas Electronics Corporation
7  * and/or its licensors ("Renesas") and subject to statutory and contractual protections.
8  *
9  * This file is subject to a Renesas SSP license agreement. Unless otherwise agreed in an SSP license agreement with
10  * Renesas: 1) you may not use, copy, modify, distribute, display, or perform the contents; 2) you may not use any name
11  * or mark of Renesas for advertising or publicity purposes or in connection with your use of the contents; 3) RENESAS
12  * MAKES NO WARRANTY OR REPRESENTATIONS ABOUT THE SUITABILITY OF THE CONTENTS FOR ANY PURPOSE; THE CONTENTS ARE PROVIDED
13  * "AS IS" WITHOUT ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
14  * PARTICULAR PURPOSE, AND NON-INFRINGEMENT; AND 4) RENESAS SHALL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, OR
15  * CONSEQUENTIAL DAMAGES, INCLUDING DAMAGES RESULTING FROM LOSS OF USE, DATA, OR PROJECTS, WHETHER IN AN ACTION OF
16  * CONTRACT OR TORT, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE CONTENTS. Third-party contents
17  * included in this file may be subject to different terms.
18  **********************************************************************************************************************/
19 
20 /**********************************************************************************************************************
21  * File Name    : r_sci_uart.c
22  * Description  : UART on SCI HAL driver
23  **********************************************************************************************************************/
24 
25 /***********************************************************************************************************************
26  * Includes
27  **********************************************************************************************************************/
28 #include "bsp_api.h"
29 #include "r_sci_uart.h"
30 #include "hw/hw_sci_uart_private.h"
31 #include "r_sci_uart_private_api.h"
32 #include "r_cgc.h"
33 #include "hw/hw_sci_common.h"
34 #include "r_ioport.h"
35 
36 /***********************************************************************************************************************
37  * Macro definitions
38  **********************************************************************************************************************/
39 #ifndef SCI_UART_ERROR_RETURN
40 /*LDRA_INSPECTED 77 S This macro does not work when surrounded by parentheses. */
41 #define SCI_UART_ERROR_RETURN(a, err) SSP_ERROR_RETURN((a), (err), &g_module_name[0], &module_version)
42 #endif
43 
44 /** SCI FIFO depth is defined by b2:3 of the variant data.  FIFO depth values defined in g_sci_uart_fifo_depth. */
45 #define SCI_UART_VARIANT_FIFO_DEPTH_MASK    (0x0CU)
46 #define SCI_UART_VARIANT_FIFO_DEPTH_SHIFT   (2U)
47 
48 /** Number of divisors in the data table used for baud rate calculation. */
49 #define SCI_UART_NUM_DIVISORS_ASYNC      (13U)
50 
51 /** Valid range of values for the modulation duty register is 128 - 256 (256 = modulation disabled). */
52 #define SCI_UART_MDDR_MIN                (128U)
53 #define SCI_UART_MDDR_MAX                (256U)
54 
55 /** The bit rate register is 8-bits, so the maximum value is 255. */
56 #define SCI_UART_BRR_MAX                 (255U)
57 
58 /** No limit to the number of bytes to read or write if DTC is not used. */
59 #define SCI_UART_MAX_READ_WRITE_NO_DTC   (0xFFFFFFFFU)
60 
61 /** Size of each data to transmit or receive in 9-bit mode. */
62 #define SCI_UART_DATA_SIZE_2_BYTES       (2U)
63 
64 /** Mask of invalid data bits in 9-bit mode. */
65 #define SCI_UART_ALIGN_2_BYTES           (0x1U)
66 
67 /** "SCIU" in ASCII.  Used to determine if the control block is open. */
68 #define SCI_UART_OPEN           (0x53434955U)
69 
70 /** Absolute maximum baud rate error. */
71 #define SCI_UART_MAX_BAUD_RATE_ERROR_X_1000  (15000U)
72 
73 /***********************************************************************************************************************
74  * Private constants
75  **********************************************************************************************************************/
76 static const int32_t SCI_UART_100_PERCENT_X_1000 = 100000;
77 static const int32_t SCI_UART_MDDR_DIVISOR       = 256;
78 
79 static const uint32_t   SCI_UART_DEFAULT_BAUD_RATE_ERROR_X_1000 = 10000;
80 
81 
82 /***********************************************************************************************************************
83  * Typedef definitions
84  **********************************************************************************************************************/
85 
86 /***********************************************************************************************************************
87  * Private function prototypes
88  **********************************************************************************************************************/
89 #if (SCI_UART_CFG_PARAM_CHECKING_ENABLE)
90 static ssp_err_t r_sci_uart_open_param_check  (sci_uart_instance_ctrl_t const * const p_ctrl,
91                                                uart_cfg_t               const * const p_cfg);
92 
93 static ssp_err_t r_sci_read_write_param_check (sci_uart_instance_ctrl_t const * const p_ctrl,
94                                                uint8_t const * const     addr,
95                                                uint32_t const            bytes);
96 #endif /* #if (SCI_UART_CFG_PARAM_CHECKING_ENABLE) */
97 
98 static void r_sci_uart_config_set (sci_uart_instance_ctrl_t * const p_ctrl,
99                                    uart_cfg_t         const * const p_cfg);
100 
101 static ssp_err_t r_sci_uart_transfer_configure (uart_cfg_t          const * const p_cfg,
102                                                 transfer_instance_t const *       p_transfer,
103                                                 ssp_signal_t                      signal,
104                                                 transfer_cfg_t            *       p_transfer_cfg);
105 
106 static ssp_err_t r_sci_uart_transfer_open (sci_uart_instance_ctrl_t * const p_ctrl,
107                                            uart_cfg_t         const * const p_cfg);
108 
109 static int32_t r_sci_uart_brr_mddr_calculate(uint32_t                freq_hz,
110                                              uint32_t                baudrate,
111                                              uint8_t               * p_brr_value,
112                                              baud_setting_t const ** pp_baud_setting,
113                                              uint32_t              * p_mddr,
114                                              bool                    select_16_base_clk_cycles);
115 
116 static ssp_err_t r_sci_uart_baud_calculate(sci_clk_src_t           clk_src,
117                                            uint32_t                baudrate,
118                                            uint8_t               * p_brr_value,
119                                            baud_setting_t const ** pp_baud_setting,
120                                            uint32_t              * p_mddr,
121                                            uint32_t                baud_rate_error_x_1000);
122 
123 static void r_sci_uart_baud_set (R_SCI0_Type          *       p_sci_reg,
124                                  sci_clk_src_t          const clk_src,
125                                  uint8_t                const brr,
126                                  baud_setting_t const * const p_baud_setting,
127                                  uint32_t       const * const p_mddr);
128 
129 static void r_sci_uart_fifo_cfg (sci_uart_instance_ctrl_t * const p_ctrl,
130                                  uart_cfg_t         const * const p_cfg);
131 
132 static ssp_err_t r_sci_irq_cfg(ssp_feature_t * const p_feature,
133                                ssp_signal_t    const signal,
134                                uint8_t         const ipl,
135                                void          * const p_ctrl,
136                                IRQn_Type     * const p_irq);
137 
138 static ssp_err_t r_sci_irqs_cfg(ssp_feature_t            * const p_feature,
139                                 sci_uart_instance_ctrl_t * const p_ctrl,
140                                 uart_cfg_t         const * const p_cfg);
141 
142 static void r_sci_uart_transfer_close (sci_uart_instance_ctrl_t * p_ctrl);
143 
144 static void r_sci_uart_rs485_de_pin_cfg (sci_uart_instance_ctrl_t * const p_ctrl);
145 
146 #if (SCI_UART_CFG_EXTERNAL_RTS_OPERATION)
147 static void r_sci_uart_external_rts_operation_enable (sci_uart_instance_ctrl_t * const p_ctrl,
148                                                       uart_cfg_t         const * const p_cfg);
149 #endif
150 
151 #if (SCI_UART_CFG_TX_ENABLE)
152 static ssp_err_t r_sci_uart_write_transfer_setup(sci_uart_instance_ctrl_t * const p_ctrl,
153                                                  uint8_t const * const p_src,
154                                                  uint32_t const bytes);
155 void r_sci_uart_write_no_transfer(sci_uart_instance_ctrl_t * const p_ctrl);
156 
157 #endif /* if (SCI_UART_CFG_TX_ENABLE) */
158 
159 
160 
161 #if (SCI_UART_CFG_RX_ENABLE)
162 void r_sci_uart_rxi_read_no_transfer_eventset(sci_uart_instance_ctrl_t * const p_ctrl,
163                                               uint32_t                   const data);
164 
165 void r_sci_uart_rxi_read_no_transfer(sci_uart_instance_ctrl_t * const p_ctrl);
166 
167 void sci_uart_rxi_isr (void);
168 
169 void r_sci_uart_read_data(sci_uart_instance_ctrl_t * const p_ctrl,
170                           uint32_t                 * const p_data);
171 
172 void sci_uart_eri_isr (void);
173 
174 static ssp_err_t r_sci_uart_abort_rx(sci_uart_instance_ctrl_t * p_ctrl);
175 #endif /* if (SCI_UART_CFG_RX_ENABLE) */
176 
177 #if (SCI_UART_CFG_TX_ENABLE)
178 static ssp_err_t r_sci_uart_abort_tx(sci_uart_instance_ctrl_t * p_ctrl);
179 
180 void sci_uart_txi_isr (void);
181 void sci_uart_tei_isr (void);
182 #endif /* if (SCI_UART_CFG_TX_ENABLE) */
183 
184 
185 
186 /***********************************************************************************************************************
187  * Private global variables
188  **********************************************************************************************************************/
189 /** Name of module used by error logger macro */
190 #if BSP_CFG_ERROR_LOG != 0
191 static const char g_module_name[] = "sci_uart";
192 #endif
193 
194 /** Baud rate divisor information (UART mode) */
195 static const baud_setting_t async_baud[SCI_UART_NUM_DIVISORS_ASYNC] =
196 {
197     {   6U,  0U,  0U,  1U,  0U }, /* divisor, BGDM, ABCS, ABCSE, n */
198     {   8U,  1U,  1U,  0U,  0U },
199     {  16U,  1U,  0U,  0U,  0U },
200     {  24U,  0U,  0U,  1U,  1U },
201     {  32U,  0U,  0U,  0U,  0U },
202     {  64U,  1U,  0U,  0U,  1U },
203     {  96U,  0U,  0U,  1U,  2U },
204     { 128U,  0U,  0U,  0U,  1U },
205     { 256U,  1U,  0U,  0U,  2U },
206     { 384U,  0U,  0U,  1U,  3U },
207     { 512U,  0U,  0U,  0U,  2U },
208     { 1024U, 1U,  0U,  0U,  3U },
209     { 2048U, 0U,  0U,  0U,  3U }
210 };
211 
212 /** FIFO depth values, use variant data b2:3 as index. */
213 static const uint8_t g_sci_uart_fifo_depth[] =
214 {
215     0U, 4U, 8U, 16U
216 };
217 
218 #if defined(__GNUC__)
219 /* This structure is affected by warnings from a GCC compiler bug. This pragma suppresses the warnings in this
220  * structure only.*/
221 /*LDRA_INSPECTED 69 S */
222 #pragma GCC diagnostic ignored "-Wmissing-field-initializers"
223 #endif
224 /** SCI UART HAL module version data structure */
225 static const ssp_version_t module_version =
226 {
227     .api_version_minor  = UART_API_VERSION_MINOR,
228     .api_version_major  = UART_API_VERSION_MAJOR,
229     .code_version_major = SCI_UART_CODE_VERSION_MAJOR,
230     .code_version_minor = SCI_UART_CODE_VERSION_MINOR
231 };
232 #if defined(__GNUC__)
233 /* Restore warning settings for 'missing-field-initializers' to as specified on command line. */
234 /*LDRA_INSPECTED 69 S */
235 #pragma GCC diagnostic pop
236 #endif
237 
238 /** UART on SCI HAL API mapping for UART interface */
239 /*LDRA_INSPECTED 27 D This structure must be accessible in user code. It cannot be static. */
240 const uart_api_t  g_uart_on_sci =
241 {
242     .open               = R_SCI_UartOpen,
243     .close              = R_SCI_UartClose,
244     .write              = R_SCI_UartWrite,
245     .read               = R_SCI_UartRead,
246     .infoGet            = R_SCI_UartInfoGet,
247     .baudSet            = R_SCI_UartBaudSet,
248     .versionGet         = R_SCI_UartVersionGet,
249     .communicationAbort = R_SCI_UartAbort
250 };
251 
252 /*******************************************************************************************************************//**
253  * @addtogroup UARTonSCI
254  * @{
255  **********************************************************************************************************************/
256 
257 /***********************************************************************************************************************
258  * Functions
259  **********************************************************************************************************************/
260 
261 /*******************************************************************************************************************//**
262  * Configures the UART driver based on the input configurations.  If reception is enabled at compile time, reception is
263  * enabled at the end of this function.
264  *
265  * @retval  SSP_SUCCESS                Channel opened successfully.
266  * @retval  SSP_ERR_ASSERTION          Pointer to UART control block or configuration structure is NULL.
267  * @retval  SSP_ERR_INVALID_ARGUMENT   Invalid parameter setting found in the configuration structure.
268  * @retval  SSP_ERR_IN_USE             Control block has already been opened or channel is being used by another
269  *                                     instance. Call close() then open() to reconfigure.
270  * @retval  SSP_ERR_IRQ_BSP_DISABLED   A required interrupt does not exist in the vector table
271  *
272  * @return                       See @ref Common_Error_Codes or functions called by this function for other possible
273  *                               return codes. This function calls:
274  *                                   * fmi_api_t::productFeatureGet
275  *                                   * fmi_api_t::eventInfoGet
276  *                                   * cgc_api_t::systemClockFreqGet
277  *                                   * transfer_api_t::open
278  **********************************************************************************************************************/
R_SCI_UartOpen(uart_ctrl_t * const p_api_ctrl,uart_cfg_t const * const p_cfg)279 ssp_err_t R_SCI_UartOpen (uart_ctrl_t      * const p_api_ctrl,
280                           uart_cfg_t const * const p_cfg)
281 {
282     ssp_err_t         err = SSP_SUCCESS;
283     sci_uart_instance_ctrl_t * p_ctrl = (sci_uart_instance_ctrl_t *) p_api_ctrl;
284 
285 #if (SCI_UART_CFG_PARAM_CHECKING_ENABLE)
286     /** Check parameters. */
287     err = r_sci_uart_open_param_check(p_ctrl, p_cfg);        /** check arguments */
288     SCI_UART_ERROR_RETURN((SSP_SUCCESS == err), err);
289 #endif
290 
291 
292     /** Make sure this channel exists. */
293     ssp_feature_t ssp_feature = {{(ssp_ip_t) 0U}};
294     ssp_feature.channel = p_cfg->channel;
295     ssp_feature.unit = 0U;
296     ssp_feature.id = SSP_IP_SCI;
297     fmi_feature_info_t info = {0U};
298     err = g_fmi_on_fmi.productFeatureGet(&ssp_feature, &info);
299     SCI_UART_ERROR_RETURN(SSP_SUCCESS == err, err);
300     p_ctrl->p_reg = info.ptr;
301     R_SCI0_Type * p_sci_reg = (R_SCI0_Type *) p_ctrl->p_reg;
302 
303     /** Reserve the hardware lock. */
304     err = R_BSP_HardwareLock(&ssp_feature);
305     SCI_UART_ERROR_RETURN(SSP_SUCCESS == err, err);
306 
307     /** Determine if this channel has a FIFO. */
308     uint32_t fifo_depth_index = (uint32_t) (info.variant_data & SCI_UART_VARIANT_FIFO_DEPTH_MASK)
309             >> SCI_UART_VARIANT_FIFO_DEPTH_SHIFT;
310     p_ctrl->fifo_depth = g_sci_uart_fifo_depth[fifo_depth_index];
311 
312     /** Calculate the baud rate register settings. */
313     uart_on_sci_cfg_t * p_extend = (uart_on_sci_cfg_t *) p_cfg->p_extend;
314 
315     sci_clk_src_t     clk_src = SCI_CLK_SRC_INT;
316     p_ctrl->baud_rate_error_x_1000 = SCI_UART_DEFAULT_BAUD_RATE_ERROR_X_1000;
317 
318     uint32_t mddr = 0U;
319     uint32_t * p_mddr = NULL;
320     if (NULL != p_extend)
321     {
322         clk_src = p_extend->clk_src;
323         if (p_extend->bitrate_modulation)
324         {
325             p_mddr = &mddr;
326             p_ctrl->bitrate_modulation = 1U;
327         }
328         else
329         {
330             p_ctrl->bitrate_modulation = 0U;
331         }
332         p_ctrl->baud_rate_error_x_1000 = p_extend->baud_rate_error_x_1000;
333     }
334 
335     uint8_t brr = 0U;
336     baud_setting_t const * p_baud_setting = NULL;
337     err = r_sci_uart_baud_calculate(clk_src, p_cfg->baud_rate, &brr, &p_baud_setting, p_mddr, p_ctrl->baud_rate_error_x_1000);
338 
339     /** Configure the interrupts. */
340     if (SSP_SUCCESS == err)
341     {
342         err = r_sci_irqs_cfg(&ssp_feature, p_ctrl, p_cfg);
343     }
344 
345     /** Configure the transfer interface for transmission and reception if provided. */
346     if (SSP_SUCCESS == err)
347     {
348         p_ctrl->p_transfer_rx = p_cfg->p_transfer_rx;
349         p_ctrl->p_transfer_tx = p_cfg->p_transfer_tx;
350 
351         err = r_sci_uart_transfer_open(p_ctrl, p_cfg);
352     }
353 
354     /* If any error occurred, close the transfer interfaces if provided and release the hardware lock. */
355     if (err != SSP_SUCCESS)
356     {
357         r_sci_uart_transfer_close(p_ctrl);
358         R_BSP_HardwareUnlock(&ssp_feature);
359     }
360     SCI_UART_ERROR_RETURN(SSP_SUCCESS == err, err);
361 
362     p_ctrl->uart_comm_mode                   = p_extend->uart_comm_mode;
363     p_ctrl->uart_rs485_mode                  = p_extend->uart_rs485_mode;
364     p_ctrl->rs485_de_pin                     = p_extend->rs485_de_pin;
365 
366     /** Configuration of driver enable pin for rs485 communication mode. */
367     r_sci_uart_rs485_de_pin_cfg(p_ctrl);
368 
369     /** Enable the SCI channel and reset the registers to their initial state. */
370     R_BSP_ModuleStart(&ssp_feature);
371     HW_SCI_RegisterReset(p_sci_reg);
372 
373     /** Set the default level of the TX pin to 1. */
374     HW_SCI_TransmitterLevelSet(p_sci_reg, 1U);
375 
376     /** Set the baud rate registers. */
377     r_sci_uart_baud_set(p_sci_reg, clk_src, brr, p_baud_setting, p_mddr);
378 
379     /** Set the UART configuration settings provided in ::uart_cfg_t and ::uart_on_sci_cfg_t. */
380     r_sci_uart_config_set(p_ctrl, p_cfg);
381 
382     p_ctrl->channel                          = p_cfg->channel;
383     p_ctrl->p_context                        = p_cfg->p_context;
384     p_ctrl->p_callback                       = p_cfg->p_callback;
385     p_ctrl->p_tx_src                         = NULL;
386     p_ctrl->tx_src_bytes                     = 0U;
387     p_ctrl->rx_transfer_in_progress          = 0U;
388     p_ctrl->rx_dst_bytes                     = 0U;
389     p_ctrl->rx_bytes_count                   = 0U;
390 
391 #if (SCI_UART_CFG_RX_ENABLE)
392     /** If reception is enabled at build time, enable reception. */
393     /* NOTE: Transmitter and its interrupt are enabled in R_SCI_UartWrite(). */
394     HW_SCI_RXIeventSelect(p_sci_reg);
395     HW_SCI_ReceiverEnable(p_sci_reg);
396     HW_SCI_RxIrqEnable(p_sci_reg, p_ctrl);
397 #endif
398 
399 #if (SCI_UART_CFG_TX_ENABLE)
400     HW_SCI_TransmitterEnable(p_ctrl->p_reg);
401 #endif
402 
403 #if (SCI_UART_CFG_EXTERNAL_RTS_OPERATION)
404     /** If external RTS operation is enabled at build time, call user provided RTS function to set initial RTS value
405      * to 0. */
406     r_sci_uart_external_rts_operation_enable(p_ctrl, p_cfg);
407 #endif
408 
409     p_ctrl->open = SCI_UART_OPEN;
410 
411     return SSP_SUCCESS;
412 }  /* End of function R_SCI_UartOpen() */
413 
414 /*******************************************************************************************************************//**
415  * Disables interrupts, receiver, and transmitter.  Closes lower level transfer drivers if used.  Removes power and
416  * releases hardware lock.
417  *
418  * @retval  SSP_SUCCESS              Channel successfully closed.
419  * @retval  SSP_ERR_ASSERTION        Pointer to UART control block is NULL.
420  * @retval  SSP_ERR_NOT_OPEN         The control block has not been opened
421  **********************************************************************************************************************/
R_SCI_UartClose(uart_ctrl_t * const p_api_ctrl)422 ssp_err_t R_SCI_UartClose (uart_ctrl_t * const p_api_ctrl)
423 {
424     sci_uart_instance_ctrl_t * p_ctrl = (sci_uart_instance_ctrl_t *) p_api_ctrl;
425 #if (SCI_UART_CFG_PARAM_CHECKING_ENABLE)
426     SSP_ASSERT(p_ctrl);
427     SCI_UART_ERROR_RETURN(SCI_UART_OPEN == p_ctrl->open, SSP_ERR_NOT_OPEN);
428 #endif
429 
430     /** Mark the channel not open so other APIs cannot use it. */
431     p_ctrl->open = 0U;
432 
433     /** Disable interrupts, receiver, and transmitter. */
434     R_SCI0_Type * p_sci_reg = (R_SCI0_Type *) p_ctrl->p_reg;
435 
436 #if (SCI_UART_CFG_RX_ENABLE | SCI_UART_CFG_TX_ENABLE)
437     HW_SCI_UartTransmitterReceiverDisable(p_sci_reg);
438 #endif
439 #if (SCI_UART_CFG_RX_ENABLE)
440     /** If reception is enabled at build time, disable reception irqs. */
441     NVIC_DisableIRQ(p_ctrl->rxi_irq);
442     if (SSP_INVALID_VECTOR != p_ctrl->eri_irq)
443     {
444         NVIC_DisableIRQ(p_ctrl->eri_irq);
445     }
446 #endif
447 #if (SCI_UART_CFG_TX_ENABLE)
448     /** If transmission is enabled at build time, disable transmission irqs. */
449     NVIC_DisableIRQ(p_ctrl->txi_irq);
450     NVIC_DisableIRQ(p_ctrl->tei_irq);
451 #endif
452 
453     /** Disable baud clock output. */
454     HW_SCI_BaudClkOutputDisable (p_sci_reg);
455 
456     /** Close the lower level transfer instances. */
457     r_sci_uart_transfer_close(p_ctrl);
458 
459     /** Clear control block parameters. */
460     p_ctrl->p_callback   = NULL;
461     p_ctrl->p_extpin_ctrl = NULL;
462 
463     /** Remove power to the channel. */
464     ssp_feature_t ssp_feature = {{(ssp_ip_t) 0U}};
465     ssp_feature.channel = p_ctrl->channel;
466     ssp_feature.unit = 0U;
467     ssp_feature.id = SSP_IP_SCI;
468     R_BSP_ModuleStop(&ssp_feature);
469 
470     /** Unlock the SCI channel. */
471     R_BSP_HardwareUnlock(&ssp_feature);
472 
473     return SSP_SUCCESS;
474 }  /* End of function R_SCI_UartClose() */
475 
476 /*******************************************************************************************************************//**
477  * Receives user specified number of bytes into destination buffer pointer.
478  *
479  * @retval  SSP_SUCCESS                  Data reception successfully ends.
480  * @retval  SSP_ERR_ASSERTION            Pointer to UART control block is NULL.
481  *                                       Number of transfers outside the max or min boundary when transfer instance used
482  * @retval  SSP_ERR_INVALID_ARGUMENT     Destination address or data size is not valid for 9-bit mode.
483  * @retval  SSP_ERR_NOT_OPEN             The control block has not been opened
484  * @retval  SSP_ERR_IN_USE               A previous read operation is still in progress.
485  * @retval  SSP_ERR_UNSUPPORTED          SCI_UART_CFG_RX_ENABLE is set to 0
486  *
487  * @return                       See @ref Common_Error_Codes or functions called by this function for other possible
488  *                               return codes. This function calls:
489  *                                   * transfer_api_t::reset
490  *
491  * @note This API is only valid when SCI_UART_CFG_RX_ENABLE is enabled.
492  *       If 9-bit data length is specified at R_SCI_UartOpen call, p_dest must be aligned 16-bit boundary.
493  **********************************************************************************************************************/
R_SCI_UartRead(uart_ctrl_t * const p_api_ctrl,uint8_t const * const p_dest,uint32_t const bytes)494 ssp_err_t R_SCI_UartRead (uart_ctrl_t   * const p_api_ctrl,
495                           uint8_t const * const p_dest,
496                           uint32_t        const bytes)
497 {
498 #if (SCI_UART_CFG_RX_ENABLE)
499     sci_uart_instance_ctrl_t * p_ctrl = (sci_uart_instance_ctrl_t *) p_api_ctrl;
500     ssp_err_t err        = SSP_SUCCESS;
501 
502 #if (SCI_UART_CFG_PARAM_CHECKING_ENABLE)
503     err = r_sci_read_write_param_check(p_ctrl, p_dest, bytes);
504     SCI_UART_ERROR_RETURN(SSP_SUCCESS == err, err);
505 #endif
506 
507     uint32_t data_bytes = p_ctrl->data_bytes;
508 
509     /** Configure transfer instance to receive the requested number of bytes if transfer is used for reception. */
510     if (NULL != p_ctrl->p_transfer_rx)
511     {
512         uint32_t size = bytes >> (data_bytes - 1);
513 #if (SCI_UART_CFG_PARAM_CHECKING_ENABLE)
514         transfer_properties_t transfer_max = {0U};
515         p_ctrl->p_transfer_rx->p_api->infoGet(p_ctrl->p_transfer_rx->p_ctrl, &transfer_max);
516         SSP_ASSERT(size <= transfer_max.transfer_length_max);
517 #endif
518         SCI_UART_ERROR_RETURN(0U == p_ctrl->rx_transfer_in_progress, SSP_ERR_IN_USE);
519         p_ctrl->rx_transfer_in_progress = 1U;
520         err = p_ctrl->p_transfer_rx->p_api->reset(p_ctrl->p_transfer_rx->p_ctrl, NULL, (void *) p_dest, (uint16_t) size);
521         SCI_UART_ERROR_RETURN(SSP_SUCCESS == err, err);
522     }
523     else
524     {
525         SCI_UART_ERROR_RETURN(0U == p_ctrl->rx_dst_bytes, SSP_ERR_IN_USE);
526         p_ctrl->p_rx_dst = (uint8_t *) p_dest;
527         p_ctrl->rx_dst_bytes = bytes;
528         p_ctrl->rx_bytes_count = 0U;
529     }
530 
531     return err;
532 #else
533     SSP_PARAMETER_NOT_USED(p_api_ctrl);
534     SSP_PARAMETER_NOT_USED(p_dest);
535     SSP_PARAMETER_NOT_USED(bytes);
536     return SSP_ERR_UNSUPPORTED;
537 #endif /* if (SCI_UART_CFG_RX_ENABLE) */
538 }  /* End of function R_SCI_UartRead() */
539 
540 /*******************************************************************************************************************//**
541  * Transmits user specified number of bytes from the source buffer pointer.
542  *
543  * @retval  SSP_SUCCESS                  Data transmission finished successfully.
544  * @retval  SSP_ERR_ASSERTION            Pointer to UART control block is NULL.
545  *                                       Number of transfers outside the max or min boundary when transfer instance used
546  * @retval  SSP_ERR_INVALID_ARGUMENT     Source address or data size is not valid for 9-bit mode.
547  * @retval  SSP_ERR_NOT_OPEN             The control block has not been opened
548  * @retval  SSP_ERR_IN_USE               A UART transmission is in progress
549  * @retval  SSP_ERR_UNSUPPORTED          SCI_UART_CFG_TX_ENABLE is set to 0
550  *
551  * @return                       See @ref Common_Error_Codes or functions called by this function for other possible
552  *                               return codes. This function calls:
553  *                                   * transfer_api_t::reset
554  *
555  * @note  This API is only valid when SCI_UART_CFG_TX_ENABLE is enabled.
556  *        If 9-bit data length is specified at R_SCI_UartOpen call, p_src must be aligned on a 16-bit boundary.
557  **********************************************************************************************************************/
R_SCI_UartWrite(uart_ctrl_t * const p_api_ctrl,uint8_t const * const p_src,uint32_t const bytes)558 ssp_err_t R_SCI_UartWrite (uart_ctrl_t   * const p_api_ctrl,
559                            uint8_t const * const p_src,
560                            uint32_t        const bytes)
561 {
562 #if (SCI_UART_CFG_TX_ENABLE)
563     sci_uart_instance_ctrl_t * p_ctrl = (sci_uart_instance_ctrl_t *) p_api_ctrl;
564     ssp_err_t err        = SSP_SUCCESS;
565 
566 #if (SCI_UART_CFG_PARAM_CHECKING_ENABLE)
567     err = r_sci_read_write_param_check(p_ctrl, p_src, bytes);
568     SCI_UART_ERROR_RETURN(SSP_SUCCESS == err, err);
569     SCI_UART_ERROR_RETURN(NULL == p_ctrl->p_tx_src, SSP_ERR_IN_USE);
570 #endif
571 
572     /**  Set the Driver Enable pin in RS485 half duplex mode to enable transmission. */
573     if ((UART_MODE_RS485 == p_ctrl->uart_comm_mode) && (UART_RS485_HD == p_ctrl->uart_rs485_mode))
574     {
575           g_ioport_on_ioport.pinWrite (p_ctrl->rs485_de_pin, IOPORT_LEVEL_HIGH);
576     }
577 
578     R_SCI0_Type * p_sci_reg = (R_SCI0_Type *) p_ctrl->p_reg;
579     /** Transmit interrupts must be disabled to start with. */
580     HW_SCI_UartTransmitIrqDisable(p_sci_reg);
581 
582     /** Save data to transmit to the control block. It will be transmitted in the TXI ISR. */
583     p_ctrl->p_tx_src = p_src;
584     p_ctrl->tx_src_bytes = bytes;
585 
586     /** If a transfer instance is used for transmission, reset the transfer instance to transmit the requested
587      * data. */
588     if (NULL != p_ctrl->p_transfer_tx)
589     {
590         err = r_sci_uart_write_transfer_setup(p_ctrl, p_src, bytes);
591         if (SSP_SUCCESS != err)
592         {
593             /** Clear the Driver Enable pin in RS485 half duplex mode to enable reception in error conditions*/
594             r_sci_uart_rs485_de_pin_cfg(p_ctrl);
595             SSP_ERROR_LOG((err), (&g_module_name[0]), (&module_version));
596             return err;
597         }
598     }
599 
600     /** Trigger a TXI interrupt. This triggers the transfer instance or a TXI interrupt if the transfer instance is
601      * not used. */
602     R_BSP_IrqStatusClear(p_ctrl->txi_irq);
603     NVIC_ClearPendingIRQ(p_ctrl->txi_irq);
604     if (0U != p_ctrl->fifo_depth)
605     {
606         NVIC_EnableIRQ(p_ctrl->txi_irq);
607     }
608     HW_SCI_UartTransmitterEnable(p_sci_reg);
609     if (0U == p_ctrl->fifo_depth)
610     {
611         /* On channels with no FIFO, the first byte is sent from this function to trigger the first TXI event.  This
612          * method is used instead of setting TE and TIE at the same time as recommended in the hardware manual to avoid
613          * the one frame delay that occurs when the TE bit is set. */
614         r_sci_uart_write_no_transfer(p_ctrl);
615         NVIC_EnableIRQ(p_ctrl->txi_irq);
616     }
617 
618     return SSP_SUCCESS;
619 #else
620     SSP_PARAMETER_NOT_USED(p_api_ctrl);
621     SSP_PARAMETER_NOT_USED(p_src);
622     SSP_PARAMETER_NOT_USED(bytes);
623     return SSP_ERR_UNSUPPORTED;
624 #endif /* if (SCI_UART_CFG_TX_ENABLE) */
625 }  /* End of function R_SCI_UartWrite() */
626 
627 /*******************************************************************************************************************//**
628  * Updates the baud rate.
629  *
630  * @warning This terminates any in-progress transmission.
631  *
632  * @retval  SSP_SUCCESS                  Baud rate was successfully changed.
633  * @retval  SSP_ERR_ASSERTION            Pointer to UART control block is NULL or the UART is not configured to use the
634  *                                       internal clock.
635  * @retval  SSP_ERR_INVALID_ARGUMENT     Illegal baud rate value is specified.
636  * @retval  SSP_ERR_NOT_OPEN             The control block has not been opened
637  **********************************************************************************************************************/
R_SCI_UartBaudSet(uart_ctrl_t * const p_api_ctrl,uint32_t const baudrate)638 ssp_err_t R_SCI_UartBaudSet (uart_ctrl_t * const p_api_ctrl,
639                              uint32_t      const baudrate)
640 {
641     sci_uart_instance_ctrl_t * p_ctrl = (sci_uart_instance_ctrl_t *) p_api_ctrl;
642     ssp_err_t     err = SSP_SUCCESS;
643     sci_clk_src_t clk_src = SCI_CLK_SRC_INT;
644     R_SCI0_Type * p_sci_reg;
645 
646 #if (SCI_UART_CFG_PARAM_CHECKING_ENABLE)
647     SSP_ASSERT(p_ctrl);
648     SCI_UART_ERROR_RETURN(SCI_UART_OPEN == p_ctrl->open, SSP_ERR_NOT_OPEN);
649 #endif
650 
651     p_sci_reg = (R_SCI0_Type *) p_ctrl->p_reg;
652     SSP_ASSERT(HW_SCI_IsBaudRateInternalClkSelected(p_sci_reg));
653 
654     /** Calculate new baud rate register settings. */
655     uint8_t brr = 0U;
656     baud_setting_t const * p_baud_setting = NULL;
657     uint32_t mddr = 0U;
658     uint32_t * p_mddr = NULL;
659     if (1U == p_ctrl->bitrate_modulation)
660     {
661         p_mddr = &mddr;
662     }
663     err = r_sci_uart_baud_calculate(clk_src, baudrate, &brr, &p_baud_setting, p_mddr, p_ctrl->baud_rate_error_x_1000);
664     SCI_UART_ERROR_RETURN(SSP_SUCCESS == err, err);
665 
666     /** Disables transmitter and receiver. This terminates any in-progress transmission. */
667     HW_SCI_UartTransmitterReceiverDisable(p_sci_reg);
668     p_ctrl->p_tx_src = NULL;
669 
670     /** Apply new baud rate register settings. */
671     r_sci_uart_baud_set(p_sci_reg, clk_src, brr, p_baud_setting, p_mddr);
672 
673 #if (SCI_UART_CFG_RX_ENABLE)
674     /** Enable receiver. */
675     HW_SCI_UartReceiverEnable(p_sci_reg);
676 #endif
677 
678     return err;
679 }  /* End of function R_SCI_UartBaudSet() */
680 
681 /*******************************************************************************************************************//**
682  * Provides the driver information, including the maximum number of bytes that can be received or transmitted at a time.
683  *
684  * @retval  SSP_SUCCESS                  Information stored in provided p_info.
685  * @retval  SSP_ERR_ASSERTION            Pointer to UART control block is NULL.
686  * @retval  SSP_ERR_NOT_OPEN             The control block has not been opened
687  **********************************************************************************************************************/
R_SCI_UartInfoGet(uart_ctrl_t * const p_api_ctrl,uart_info_t * const p_info)688 ssp_err_t R_SCI_UartInfoGet (uart_ctrl_t * const p_api_ctrl,
689                              uart_info_t * const p_info)
690 {
691     sci_uart_instance_ctrl_t * p_ctrl = (sci_uart_instance_ctrl_t *) p_api_ctrl;
692 
693 #if (SCI_UART_CFG_PARAM_CHECKING_ENABLE)
694     SSP_ASSERT(p_ctrl);
695     SSP_ASSERT(p_info);
696     SCI_UART_ERROR_RETURN(SCI_UART_OPEN == p_ctrl->open, SSP_ERR_NOT_OPEN);
697 #endif
698 
699     p_info->read_bytes_max = 0U;
700     p_info->write_bytes_max = 0U;
701 
702 #if (SCI_UART_CFG_RX_ENABLE)
703     /** Store number of bytes that can be read at a time. */
704     if (NULL != p_ctrl->p_transfer_rx)
705     {
706         transfer_properties_t properties = {0U};
707         p_ctrl->p_transfer_rx->p_api->infoGet(p_ctrl->p_transfer_rx->p_ctrl, &properties);
708         p_info->read_bytes_max = properties.transfer_length_max * p_ctrl->data_bytes;
709     }
710     else
711     {
712         /* No limit to number of bytes to read. */
713         p_info->read_bytes_max = SCI_UART_MAX_READ_WRITE_NO_DTC;
714     }
715 #endif
716 
717 #if (SCI_UART_CFG_TX_ENABLE)
718     /** Store number of bytes that can be written at a time. */
719     if (NULL != p_ctrl->p_transfer_tx)
720     {
721         transfer_properties_t properties = {0U};
722         p_ctrl->p_transfer_tx->p_api->infoGet(p_ctrl->p_transfer_tx->p_ctrl, &properties);
723         p_info->write_bytes_max = properties.transfer_length_max * p_ctrl->data_bytes;
724     }
725     else
726     {
727         /* No limit to number of bytes to write. */
728         p_info->write_bytes_max = SCI_UART_MAX_READ_WRITE_NO_DTC;
729     }
730 #endif
731 
732     return SSP_SUCCESS;
733 }  /* End of function R_SCI_UartInfoGet() */
734 
735 /*******************************************************************************************************************//**
736  * Provides API and code version in the user provided pointer.
737  *
738  * @param[in] p_version   Version number set here
739  *
740  * @retval  SSP_SUCCESS                  Version information stored in provided p_version.
741  * @retval  SSP_ERR_ASSERTION            p_version is NULL.
742  **********************************************************************************************************************/
R_SCI_UartVersionGet(ssp_version_t * p_version)743 ssp_err_t R_SCI_UartVersionGet (ssp_version_t * p_version)
744 {
745 #if (SCI_UART_CFG_PARAM_CHECKING_ENABLE)
746     SSP_ASSERT(p_version);
747 #endif
748 
749     *p_version = module_version;
750 
751     return SSP_SUCCESS;
752 } /* End of function R_SCI_UartVersionGet() */
753 
754 /*******************************************************************************************************************//**
755  * Provides API to abort ongoing transfer. Transmission is aborted after the current character is transmitted.
756  * Reception is still enabled after abort(). Any characters received after abort() and before the transfer
757  * is reset in the next call to read(), will arrive via the callback function with event UART_EVENT_RX_CHAR.
758  *
759  * @retval  SSP_SUCCESS                  UART transaction aborted successfully.
760  * @retval  SSP_ERR_ASSERTION            Pointer to UART control block is NULL.
761  * @retval  SSP_ERR_NOT_OPEN             The control block has not been opened.
762  * @retval  SSP_ERR_UNSUPPORTED          The requested Abort direction is unsupported.
763  *
764  * @return                       See @ref Common_Error_Codes or functions called by this function for other possible
765  *                               return codes. This function calls:
766  *                                   * transfer_api_t::disable
767  **********************************************************************************************************************/
R_SCI_UartAbort(uart_ctrl_t * const p_api_ctrl,uart_dir_t communication_to_abort)768 ssp_err_t R_SCI_UartAbort (uart_ctrl_t   * const p_api_ctrl, uart_dir_t communication_to_abort)
769 {
770     sci_uart_instance_ctrl_t * p_ctrl = (sci_uart_instance_ctrl_t *) p_api_ctrl;
771     ssp_err_t err        = SSP_ERR_UNSUPPORTED;
772 
773 #if (SCI_UART_CFG_PARAM_CHECKING_ENABLE)
774     SSP_ASSERT(p_ctrl);
775     SCI_UART_ERROR_RETURN(SCI_UART_OPEN == p_ctrl->open, SSP_ERR_NOT_OPEN);
776 #endif
777 
778 #if (SCI_UART_CFG_TX_ENABLE)
779     if ((UART_DIR_RX_TX == communication_to_abort) || (UART_DIR_TX == communication_to_abort))
780     {
781         err = r_sci_uart_abort_tx(p_ctrl);
782         SCI_UART_ERROR_RETURN(SSP_SUCCESS == err, err);
783     }
784 #endif
785 #if (SCI_UART_CFG_RX_ENABLE)
786     if ((UART_DIR_RX_TX == communication_to_abort) || (UART_DIR_RX == communication_to_abort))
787     {
788         err = r_sci_uart_abort_rx(p_ctrl);
789         SCI_UART_ERROR_RETURN(SSP_SUCCESS == err, err);
790     }
791 #endif
792     return err;
793 }  /* End of function R_SCI_UartAbort() */
794 
795 /*******************************************************************************************************************//**
796  * @} (end addtogroup UARTonSCI)
797  **********************************************************************************************************************/
798 
799 /***********************************************************************************************************************
800  * Private Functions
801  **********************************************************************************************************************/
802 
803 #if (SCI_UART_CFG_PARAM_CHECKING_ENABLE)
804 /*******************************************************************************************************************//**
805  * Parameter error check function for open.
806  *
807  * @param[in] p_ctrl   Pointer to the control block for the channel
808  * @param[in] p_cfg    Pointer to the configuration structure specific to UART mode
809  *
810  * @retval  SSP_SUCCESS                  No parameter error found
811  * @retval  SSP_ERR_ASSERTION            Pointer to UART control block or configuration structure is NULL
812  * @retval  SSP_ERR_IN_USE               Control block has already been opened
813  **********************************************************************************************************************/
r_sci_uart_open_param_check(sci_uart_instance_ctrl_t const * const p_ctrl,uart_cfg_t const * const p_cfg)814 static ssp_err_t r_sci_uart_open_param_check  (sci_uart_instance_ctrl_t const * const p_ctrl,
815                                                uart_cfg_t               const * const p_cfg)
816 {
817     SSP_ASSERT(p_ctrl);
818     SSP_ASSERT(p_cfg);
819     SCI_UART_ERROR_RETURN(SCI_UART_OPEN != p_ctrl->open, SSP_ERR_IN_USE);
820     return SSP_SUCCESS;
821 }  /* End of function r_sci_uart_open_param_check() */
822 
823 /*******************************************************************************************************************//**
824  * Parameter error check function for read/write.
825  *
826  * @param[in] p_ctrl Pointer to the control block for the channel
827  * @param[in] addr   Pointer to the buffer
828  * @param[in] bytes  Number of bytes to read or write
829  *
830  * @retval  SSP_SUCCESS              No parameter error found
831  * @retval  SSP_ERR_NOT_OPEN         The control block has not been opened
832  * @retval  SSP_ERR_ASSERTION        Pointer to UART control block or configuration structure is NULL
833  * @retval  SSP_ERR_INVALID_ARGUMENT Address is not aligned to 2-byte boundary or size is the odd number when the data
834  *                                   length is 9-bit
835  **********************************************************************************************************************/
r_sci_read_write_param_check(sci_uart_instance_ctrl_t const * const p_ctrl,uint8_t const * const addr,uint32_t const bytes)836 static ssp_err_t r_sci_read_write_param_check (sci_uart_instance_ctrl_t const * const p_ctrl,
837                                                uint8_t const * const     addr,
838                                                uint32_t const            bytes)
839 {
840     SSP_ASSERT(p_ctrl);
841     SSP_ASSERT(addr);
842     SSP_ASSERT(0U != bytes);
843     SCI_UART_ERROR_RETURN(SCI_UART_OPEN == p_ctrl->open, SSP_ERR_NOT_OPEN);
844 
845     if (SCI_UART_DATA_SIZE_2_BYTES == p_ctrl->data_bytes)
846     {
847         /** Do not allow odd buffer address if data length is 9 bits. */
848         SCI_UART_ERROR_RETURN((0U == ((uint32_t) addr & SCI_UART_ALIGN_2_BYTES)), SSP_ERR_INVALID_ARGUMENT);
849 
850         /** Do not allow odd number of data bytes if data length is 9 bits. */
851         SCI_UART_ERROR_RETURN((0U == (bytes & SCI_UART_ALIGN_2_BYTES)), SSP_ERR_INVALID_ARGUMENT);
852     }
853 
854     return SSP_SUCCESS;
855 }  /* End of function r_sci_read_write_param_check() */
856 #endif /* if (SCI_UART_CFG_PARAM_CHECKING_ENABLE) */
857 
858 /*******************************************************************************************************************//**
859  * Subroutine to apply common UART transfer settings.
860  *
861  * @param[in]     p_cfg           Pointer to UART specific configuration structure
862  * @param[in]     p_transfer      Pointer to transfer instance to configure
863  * @param[in]     signal          Signal to used to activate the transfer instance
864  * @param[in]     p_transfer_cfg  Pointer to transfer configuration structure
865  *
866  * @retval        SSP_SUCCESS        UART transfer drivers successfully configured
867  * @retval        SSP_ERR_ASSERTION  Invalid pointer or required interrupt not enabled in vector table
868  **********************************************************************************************************************/
r_sci_uart_transfer_configure(uart_cfg_t const * const p_cfg,transfer_instance_t const * p_transfer,ssp_signal_t signal,transfer_cfg_t * p_transfer_cfg)869 static ssp_err_t r_sci_uart_transfer_configure (uart_cfg_t          const * const p_cfg,
870                                                 transfer_instance_t const *       p_transfer,
871                                                 ssp_signal_t                      signal,
872                                                 transfer_cfg_t            *       p_transfer_cfg)
873 {
874     /** Configure the transfer instance, if enabled. */
875 #if (SCI_UART_CFG_PARAM_CHECKING_ENABLE)
876     SSP_ASSERT(NULL != p_transfer->p_api);
877     SSP_ASSERT(NULL != p_transfer->p_ctrl);
878     SSP_ASSERT(NULL != p_transfer->p_cfg);
879     SSP_ASSERT(NULL != p_transfer->p_cfg->p_info);
880 #endif
881     transfer_info_t * p_info = p_transfer->p_cfg->p_info;
882     p_info->mode = TRANSFER_MODE_NORMAL;
883     p_info->irq = TRANSFER_IRQ_END;
884     if (UART_DATA_BITS_9 == p_cfg->data_bits)
885     {
886         p_info->size = TRANSFER_SIZE_2_BYTE;
887     }
888     else
889     {
890         p_info->size = TRANSFER_SIZE_1_BYTE;
891     }
892     fmi_event_info_t event_info = {(IRQn_Type) 0U};
893     ssp_feature_t ssp_feature = {{(ssp_ip_t) 0U}};
894     ssp_feature.channel = p_cfg->channel;
895     ssp_feature.unit = 0U;
896     ssp_feature.id = SSP_IP_SCI;
897     g_fmi_on_fmi.eventInfoGet(&ssp_feature, signal, &event_info);
898 #if (SCI_UART_CFG_PARAM_CHECKING_ENABLE)
899     /* Check to make sure the interrupt is enabled. */
900     SSP_ASSERT(SSP_INVALID_VECTOR != event_info.irq);
901 #endif
902     p_transfer_cfg->activation_source = event_info.event;
903     p_transfer_cfg->auto_enable = false;
904 
905     return SSP_SUCCESS;
906 }
907 
908 /*******************************************************************************************************************//**
909  * Configures UART related transfer drivers (if enabled).
910  *
911  * @param[in]     p_ctrl  Pointer to UART control structure
912  * @param[in]     p_cfg   Pointer to UART specific configuration structure
913  *
914  * @retval        SSP_SUCCESS        UART transfer drivers successfully configured
915  * @retval        SSP_ERR_ASSERTION  Invalid pointer or required interrupt not enabled in vector table
916  *
917  * @return                       See @ref Common_Error_Codes or functions called by this function for other possible
918  *                               return codes. This function calls:
919  *                                   * transfer_api_t::open
920  **********************************************************************************************************************/
r_sci_uart_transfer_open(sci_uart_instance_ctrl_t * const p_ctrl,uart_cfg_t const * const p_cfg)921 static ssp_err_t r_sci_uart_transfer_open (sci_uart_instance_ctrl_t * const p_ctrl,
922                                            uart_cfg_t         const * const p_cfg)
923 {
924     ssp_err_t err;
925     p_ctrl->data_bytes = 1U;
926     if (UART_DATA_BITS_9 == p_cfg->data_bits)
927     {
928         p_ctrl->data_bytes = SCI_UART_DATA_SIZE_2_BYTES;
929     }
930 #if (SCI_UART_CFG_RX_ENABLE)
931     /** If a transfer instance is used for reception, apply UART specific settings and open the transfer instance. */
932     if (NULL != p_cfg->p_transfer_rx)
933     {
934         transfer_cfg_t cfg = *(p_cfg->p_transfer_rx->p_cfg);
935         err = r_sci_uart_transfer_configure(p_cfg, p_cfg->p_transfer_rx, SSP_SIGNAL_SCI_RXI, &cfg);
936         SCI_UART_ERROR_RETURN(SSP_SUCCESS == err, err);
937         transfer_info_t * p_info = p_cfg->p_transfer_rx->p_cfg->p_info;
938         if (p_ctrl->fifo_depth > 0U)
939         {
940             p_info->p_src = HW_SCI_ReadAddrGet(p_ctrl->p_reg, p_ctrl->data_bytes);
941         }
942         else
943         {
944             p_info->p_src = HW_SCI_Non_FIFO_ReadAddrGet(p_ctrl->p_reg, p_ctrl->data_bytes);
945         }
946         p_info->dest_addr_mode = TRANSFER_ADDR_MODE_INCREMENTED;
947         p_info->src_addr_mode = TRANSFER_ADDR_MODE_FIXED;
948         err = p_cfg->p_transfer_rx->p_api->open(p_cfg->p_transfer_rx->p_ctrl, &cfg);
949         SCI_UART_ERROR_RETURN(SSP_SUCCESS == err, err);
950     }
951 #endif
952 #if (SCI_UART_CFG_TX_ENABLE)
953     /** If a transfer instance is used for transmission, apply UART specific settings and open the transfer instance. */
954     if (NULL != p_cfg->p_transfer_tx)
955     {
956         transfer_cfg_t cfg = *(p_cfg->p_transfer_tx->p_cfg);
957         err = r_sci_uart_transfer_configure(p_cfg, p_cfg->p_transfer_tx, SSP_SIGNAL_SCI_TXI, &cfg);
958         SCI_UART_ERROR_RETURN(SSP_SUCCESS == err, err);
959         transfer_info_t * p_info = p_cfg->p_transfer_tx->p_cfg->p_info;
960         if (p_ctrl->fifo_depth > 0U)
961         {
962             p_info->p_dest = HW_SCI_WriteAddrGet(p_ctrl->p_reg, p_ctrl->data_bytes);
963         }
964         else
965         {
966             p_info->p_dest = HW_SCI_Non_FIFO_WriteAddrGet(p_ctrl->p_reg, p_ctrl->data_bytes);
967         }
968         p_info->dest_addr_mode = TRANSFER_ADDR_MODE_FIXED;
969         p_info->src_addr_mode = TRANSFER_ADDR_MODE_INCREMENTED;
970         err = p_cfg->p_transfer_tx->p_api->open(p_cfg->p_transfer_tx->p_ctrl, &cfg);
971         SCI_UART_ERROR_RETURN(SSP_SUCCESS == err, err);
972     }
973 #endif
974     return SSP_SUCCESS;
975 }
976 
977 /*******************************************************************************************************************//**
978  * Configures Driver enable pin based on user configuration of supported communication modes.
979  *
980  * @param[in,out]     p_ctrl  Pointer to UART control structure
981  **********************************************************************************************************************/
r_sci_uart_rs485_de_pin_cfg(sci_uart_instance_ctrl_t * const p_ctrl)982 static void r_sci_uart_rs485_de_pin_cfg (sci_uart_instance_ctrl_t * const p_ctrl)
983 {
984     /** Configure the Driver Enable pin accordingly for rs485 communication modes */
985     if (UART_MODE_RS485 == p_ctrl->uart_comm_mode)
986     {
987         if (UART_RS485_HD == p_ctrl->uart_rs485_mode)
988         {
989             /** For RS485 Half duplex mode, the Driver Enable should be low to be able to receive asynchronously */
990             g_ioport_on_ioport.pinWrite (p_ctrl->rs485_de_pin, IOPORT_LEVEL_LOW);
991         }
992         else
993         {
994             g_ioport_on_ioport.pinWrite (p_ctrl->rs485_de_pin, IOPORT_LEVEL_HIGH);
995         }
996     }
997 }
998 
999 /*******************************************************************************************************************//**
1000  * Configures UART related registers based on user configurations.
1001  *
1002  * @param[in]     p_ctrl  Pointer to UART control structure
1003  * @param[in]     p_cfg   Pointer to UART specific configuration structure
1004  **********************************************************************************************************************/
r_sci_uart_config_set(sci_uart_instance_ctrl_t * const p_ctrl,uart_cfg_t const * const p_cfg)1005 static void r_sci_uart_config_set (sci_uart_instance_ctrl_t * const p_ctrl,
1006                                    uart_cfg_t         const * const p_cfg)
1007 {
1008     /** Configure FIFO related registers. */
1009     r_sci_uart_fifo_cfg(p_ctrl, p_cfg);
1010 
1011     /** Configure parity. */
1012     R_SCI0_Type * p_sci_reg = (R_SCI0_Type *) p_ctrl->p_reg;
1013     HW_SCI_ParitySet(p_sci_reg, p_cfg->parity);
1014 
1015     /** Configure data size. */
1016     if (UART_DATA_BITS_7 == p_cfg->data_bits)
1017     {
1018         HW_SCI_DataBits7bitsSelect(p_sci_reg);
1019     }
1020     else if (UART_DATA_BITS_9 == p_cfg->data_bits)
1021     {
1022         HW_SCI_DataBits9bitsSelect(p_sci_reg);
1023     }
1024     else
1025     {
1026         /* Do nothing.  Default is 8-bit mode. */
1027     }
1028 
1029     /** Configure stop bits. */
1030     HW_SCI_StopBitsSelect(p_sci_reg, p_cfg->stop_bits);
1031 
1032     /** Configure CTS flow control if CTS/RTS flow control is enabled. */
1033     if (p_cfg->ctsrts_en)
1034     {
1035         HW_SCI_CtsInEnable(p_sci_reg);
1036     }
1037 
1038     uart_on_sci_cfg_t * p_extend = (uart_on_sci_cfg_t *) p_cfg->p_extend;
1039     if (NULL != p_extend)
1040     {
1041         /** Starts reception on falling edge of RXD if enabled in extension (otherwise reception starts at low level
1042          * of RXD). */
1043         HW_SCI_StartBitSet(p_sci_reg, p_extend->rx_edge_start);
1044 
1045         /** Enables the noise cancellation, fixed to the minimum level, if enabled in the extension. */
1046         HW_SCI_NoiseFilterSet(p_sci_reg, p_extend->noisecancel_en);
1047 
1048         /** Enables Baud clock output if configured in the extension. */
1049         HW_SCI_BaudClkOutputEnable(p_sci_reg, p_extend->baudclk_out);
1050     }
1051 }  /* End of function r_sci_uart_config_set() */
1052 
1053 /*******************************************************************************************************************//**
1054  * This function enables external RTS operation (using a GPIO).
1055  *
1056  * @param[in] p_ctrl  Pointer to UART instance control
1057  * @param[in] p_cfg   Pointer to UART configuration structure
1058  **********************************************************************************************************************/
1059 #if (SCI_UART_CFG_EXTERNAL_RTS_OPERATION)
r_sci_uart_external_rts_operation_enable(sci_uart_instance_ctrl_t * const p_ctrl,uart_cfg_t const * const p_cfg)1060 static void r_sci_uart_external_rts_operation_enable (sci_uart_instance_ctrl_t * const p_ctrl,
1061                                                       uart_cfg_t         const * const p_cfg)
1062 {
1063     uart_on_sci_cfg_t * p_extend = (uart_on_sci_cfg_t *) p_cfg->p_extend;
1064     if (NULL != p_extend)
1065     {
1066         p_ctrl->p_extpin_ctrl = p_extend->p_extpin_ctrl;
1067 
1068         /** If CTS/RTS flow control is enabled and an RTS flow control callback is provided, call the RTS flow control
1069          * callback to assert the user GPIO RTS pin. */
1070         if ((p_cfg->ctsrts_en) && (p_ctrl->p_extpin_ctrl))
1071         {
1072             p_ctrl->p_extpin_ctrl(p_cfg->channel, 0);
1073         }
1074     }
1075 }  /* End of function r_sci_uart_external_rts_operation_enable () */
1076 #endif /* if (SCI_UART_CFG_EXTERNAL_RTS_OPERATION) */
1077 
1078 /*******************************************************************************************************************//**
1079  * Resets FIFO related registers.
1080  *
1081  * @param[in] p_ctrl  Pointer to UART instance control
1082  * @param[in] p_cfg   Pointer to UART configuration structure
1083  **********************************************************************************************************************/
r_sci_uart_fifo_cfg(sci_uart_instance_ctrl_t * const p_ctrl,uart_cfg_t const * const p_cfg)1084 static void r_sci_uart_fifo_cfg (sci_uart_instance_ctrl_t * const p_ctrl,
1085                                  uart_cfg_t         const * const p_cfg)
1086 {
1087     R_SCI0_Type * p_sci_reg = (R_SCI0_Type *) p_ctrl->p_reg;
1088 
1089     if (0U != p_ctrl->fifo_depth)
1090     {
1091         HW_SCI_FifoEnable(p_sci_reg);
1092 #if (SCI_UART_CFG_RX_ENABLE)
1093         /** Reset receive FIFO. */
1094         HW_SCI_ReceiveFifoReset(p_sci_reg);
1095 
1096         if (NULL != p_cfg->p_transfer_rx)
1097         {
1098             /** Set receive trigger number to 0 if DTC is used. */
1099             HW_SCI_RxTriggerNumberSet(p_sci_reg, 0);
1100         }
1101         else
1102         {
1103             /** Otherwise, set receive trigger number as configured by the user. */
1104             uint16_t fifo_trigger_mask = (uint16_t) (p_ctrl->fifo_depth - 1U);
1105             uart_on_sci_cfg_t const * p_extend = p_cfg->p_extend;
1106             if (NULL != p_extend)
1107             {
1108                 uint16_t rx_fifo_setting = (uint16_t) (fifo_trigger_mask & (uint16_t) p_extend->rx_fifo_trigger);
1109                 HW_SCI_RxTriggerNumberSet(p_sci_reg, rx_fifo_setting);
1110             }
1111             else
1112             {
1113                 /** Default is largest setting to reduce number of interrupts. */
1114                 HW_SCI_RxTriggerNumberSet(p_sci_reg, fifo_trigger_mask);
1115             }
1116         }
1117         HW_SCI_RTSTriggerNumberSet(p_sci_reg, (uint16_t) (p_ctrl->fifo_depth - 1U));
1118 #else
1119         SSP_PARAMETER_NOT_USED(p_cfg);
1120 #endif
1121 #if (SCI_UART_CFG_TX_ENABLE)
1122         /** Resets transmit FIFO. */
1123         HW_SCI_TransmitFifoReset(p_sci_reg);
1124 
1125         /** Set FIFO trigger to trigger when the FIFO is empty. */
1126         HW_SCI_TxTriggerNumberSet(p_sci_reg, 0U);
1127 #endif
1128     }
1129 }  /* End of function r_sci_uart_fifo_cfg() */
1130 
1131 /*******************************************************************************************************************//**
1132  * Sets interrupt priority and initializes vector info.
1133  *
1134  * @param[in]     p_feature  SSP feature
1135  * @param[in]     signal     SSP signal ID
1136  * @param[in]     ipl        Interrupt priority level
1137  * @param[in]     p_ctrl     Pointer to driver control block
1138  * @param[out]    p_irq      Pointer to IRQ for this signal, set here
1139  *
1140  * @retval        SSP_SUCCESS               Interrupt enabled
1141  * @retval        SSP_ERR_IRQ_BSP_DISABLED  Interrupt does not exist in the vector table
1142  *
1143  * @return                       See @ref Common_Error_Codes or functions called by this function for other possible
1144  *                               return codes. This function calls:
1145  *                                   * fmi_api_t::eventInfoGet
1146  **********************************************************************************************************************/
r_sci_irq_cfg(ssp_feature_t * const p_feature,ssp_signal_t const signal,uint8_t const ipl,void * const p_ctrl,IRQn_Type * const p_irq)1147 static ssp_err_t r_sci_irq_cfg(ssp_feature_t * const p_feature,
1148                                ssp_signal_t    const signal,
1149                                uint8_t         const ipl,
1150                                void          * const p_ctrl,
1151                                IRQn_Type     * const p_irq)
1152 {
1153     /** Look up interrupt number. */
1154     fmi_event_info_t event_info = {(IRQn_Type) 0U};
1155     ssp_vector_info_t * p_vector_info;
1156     ssp_err_t err = g_fmi_on_fmi.eventInfoGet(p_feature, signal, &event_info);
1157     IRQn_Type irq = event_info.irq;
1158     *p_irq = irq;
1159 
1160     /** If interrupt is registered in the vector table, disable interrupts, set priority, and store control block in
1161      * the vector information so it can be accessed from the callback. */
1162     if (SSP_SUCCESS == err)
1163     {
1164         NVIC_DisableIRQ(irq);
1165         R_BSP_IrqStatusClear(irq);
1166         NVIC_SetPriority(irq, ipl);
1167         R_SSP_VectorInfoGet(irq, &p_vector_info);
1168         *(p_vector_info->pp_ctrl) = p_ctrl;
1169     }
1170 
1171     return err;
1172 }
1173 
1174 /*******************************************************************************************************************//**
1175  * Sets interrupt priority and initializes vector info for all interrupts.
1176  *
1177  * @param[in]     p_feature  SSP feature
1178  * @param[in]     p_ctrl     Pointer to UART instance control block
1179  * @param[in]     p_cfg      Pointer to UART specific configuration structure
1180  *
1181  * @retval        SSP_SUCCESS               Interrupt enabled
1182  * @retval        SSP_ERR_IRQ_BSP_DISABLED  Interrupt does not exist in the vector table
1183  *
1184  * @return                       See @ref Common_Error_Codes or functions called by this function for other possible
1185  *                               return codes. This function calls:
1186  *                                   * fmi_api_t::eventInfoGet
1187  **********************************************************************************************************************/
r_sci_irqs_cfg(ssp_feature_t * const p_feature,sci_uart_instance_ctrl_t * const p_ctrl,uart_cfg_t const * const p_cfg)1188 static ssp_err_t r_sci_irqs_cfg(ssp_feature_t            * const p_feature,
1189                                 sci_uart_instance_ctrl_t * const p_ctrl,
1190                                 uart_cfg_t         const * const p_cfg)
1191 {
1192     ssp_err_t err;
1193 #if (SCI_UART_CFG_RX_ENABLE)
1194     /* ERI is optional. */
1195     r_sci_irq_cfg(p_feature, SSP_SIGNAL_SCI_ERI, p_cfg->eri_ipl, p_ctrl, &p_ctrl->eri_irq);
1196     err = r_sci_irq_cfg(p_feature, SSP_SIGNAL_SCI_RXI, p_cfg->rxi_ipl, p_ctrl, &p_ctrl->rxi_irq);
1197     SCI_UART_ERROR_RETURN(SSP_SUCCESS == err, err);
1198 #endif
1199 #if (SCI_UART_CFG_TX_ENABLE)
1200     err = r_sci_irq_cfg(p_feature, SSP_SIGNAL_SCI_TXI, p_cfg->txi_ipl, p_ctrl, &p_ctrl->txi_irq);
1201     SCI_UART_ERROR_RETURN(SSP_SUCCESS == err, err);
1202 
1203     err = r_sci_irq_cfg(p_feature, SSP_SIGNAL_SCI_TEI, p_cfg->tei_ipl, p_ctrl, &p_ctrl->tei_irq);
1204     SCI_UART_ERROR_RETURN(SSP_SUCCESS == err, err);
1205 #endif
1206     return SSP_SUCCESS;
1207 }
1208 
1209 /*******************************************************************************************************************//**
1210  * Closes transfer interfaces.
1211  *
1212  * @param[in]     p_ctrl     Pointer to UART instance control block
1213  **********************************************************************************************************************/
r_sci_uart_transfer_close(sci_uart_instance_ctrl_t * p_ctrl)1214 static void r_sci_uart_transfer_close (sci_uart_instance_ctrl_t * p_ctrl)
1215 {
1216 #if (SCI_UART_CFG_RX_ENABLE)
1217     if ((NULL != p_ctrl->p_transfer_rx) && (NULL != p_ctrl->p_transfer_rx->p_api))
1218     {
1219         p_ctrl->p_transfer_rx->p_api->close(p_ctrl->p_transfer_rx->p_ctrl);
1220     }
1221 #endif
1222 #if (SCI_UART_CFG_TX_ENABLE)
1223     if ((NULL != p_ctrl->p_transfer_tx) && (NULL != p_ctrl->p_transfer_tx->p_api))
1224     {
1225         p_ctrl->p_transfer_tx->p_api->close(p_ctrl->p_transfer_tx->p_ctrl);
1226     }
1227 #endif
1228 }
1229 
1230 /*******************************************************************************************************************//**
1231  * Calculates baud rate register settings based on internal clock frequency. Evaluates and determines the best possible
1232  * settings set to the baud rate related registers.  Parameter checking must be done before this function is called.
1233  *
1234  * @param[in]  freq_hz                             The source clock frequency for the SCI internal clock
1235  * @param[in]  baudrate                            Baud rate[bps] e.g. 19200, 57600, 115200, etc.
1236  * @param[out] p_brr_value                         Bit rate register value stored here if successful
1237  * @param[out] pp_baud_setting                     Baud setting information stored here if successful
1238  * @param[out] p_mddr                              MDDR register value stored here if successful
1239  * @param[out] select_16_base_clk_cycles           If True; Only find solutions for when abcs and abcse are equal to 0
1240  *
1241  * @return  bit error (percent * 1000, or percent to 3 decimal places)
1242  **********************************************************************************************************************/
r_sci_uart_brr_mddr_calculate(uint32_t freq_hz,uint32_t baudrate,uint8_t * p_brr_value,baud_setting_t const ** pp_baud_setting,uint32_t * p_mddr,bool select_16_base_clk_cycles)1243 static int32_t r_sci_uart_brr_mddr_calculate(uint32_t                freq_hz,
1244                                              uint32_t                baudrate,
1245                                              uint8_t               * p_brr_value,
1246                                              baud_setting_t const ** pp_baud_setting,
1247                                              uint32_t              * p_mddr,
1248                                              bool                    select_16_base_clk_cycles)
1249 {
1250     /** Find the best BRR (bit rate register) value.
1251      *  In table async_baud, divisor values are stored for BGDM, ABCS, ABCSE and N values.  Each set of divisors
1252      *  is tried, and the settings with the lowest bit rate error are stored. The formula to calculate BRR is as
1253      *  follows and it must be 255 or less:
1254      *  BRR = (PCLK / (div_coefficient * baud)) - 1
1255      */
1256     baud_setting_t const * p_baudinfo = &async_baud[0];
1257     int32_t  hit_bit_err = SCI_UART_100_PERCENT_X_1000;
1258     uint32_t hit_mddr = 0U;
1259     uint32_t divisor = 0U;
1260     for (uint32_t i = 0U; i < SCI_UART_NUM_DIVISORS_ASYNC; i++)
1261     {
1262         /** if select_16_base_clk_cycles == true:  Skip this calculation for divisors that are not acheivable with 16 base clk cycles per bit.
1263          *  if select_16_base_clk_cycles == false: Skip this calculation for divisors that are only acheivable without 16 base clk cycles per bit.
1264          */
1265         if ((!select_16_base_clk_cycles) ^ (p_baudinfo[i].abcs | p_baudinfo[i].abcse))
1266         {
1267             continue;
1268         }
1269 
1270         divisor = (uint32_t) p_baudinfo[i].div_coefficient * baudrate;
1271         uint32_t temp_brr = freq_hz / divisor;
1272 
1273         if (temp_brr <= (SCI_UART_BRR_MAX + 1U))
1274         {
1275             while (temp_brr > 0U)
1276             {
1277                 temp_brr -= 1U;
1278 
1279                 /** Calculate the bit rate error. The formula is as follows:
1280                  *  bit rate error[%] = {(PCLK / (baud * div_coefficient * (BRR + 1)) - 1} x 100
1281                  *  calculates bit rate error[%] to three decimal places
1282                  */
1283                 int32_t err_divisor = (int32_t) (divisor * (temp_brr + 1U));
1284 
1285                 /* Promoting to 64 bits for calculation, but the final value can never be more than 32 bits, as
1286                  * described below, so this cast is safe.
1287                  *    1. (temp_brr + 1) can be off by an upper limit of 1 due to rounding from the calculation:
1288                  *       freq_hz / divisor, or:
1289                  *       freq_hz / divisor <= (temp_brr + 1) < (freq_hz / divisor) + 1
1290                  *    2. Solving for err_divisor:
1291                  *       freq_hz <= err_divisor < freq_hz + divisor
1292                  *    3. Solving for bit_err:
1293                  *       0 >= bit_err >= (freq_hz * 100000 / (freq_hz + divisor)) - 100000
1294                  *    4. freq_hz >= divisor (or temp_brr would be -1 and we would never enter this while loop), so:
1295                  *       0 >= bit_err >= 100000 / freq_hz - 100000
1296                  *    5. Larger frequencies yield larger bit errors (absolute value).  As the frequency grows,
1297                  *       the bit_err approaches -100000, so:
1298                  *       0 >= bit_err >= -100000
1299                  *    6. bit_err is between -100000 and 0.  This entire range fits in an int32_t type, so the cast
1300                  *       to (int32_t) is safe.
1301                  */
1302                 int32_t bit_err   = (int32_t) (((((int64_t) freq_hz) * SCI_UART_100_PERCENT_X_1000) /
1303                                     err_divisor) - SCI_UART_100_PERCENT_X_1000);
1304 
1305                 uint32_t mddr = 0U;
1306                 if (NULL != p_mddr)
1307                 {
1308                     /** Calculate the MDDR (M) value if bit rate modulation is enabled,
1309                      * The formula to calculate MBBR (from the M and N relationship given in the hardware manual) is as follows
1310                      * and it must be between 128 and 256.
1311                      * MDDR = ((div_coefficient * baud * 256) * (BRR + 1)) / PCLK */
1312                     mddr = (uint32_t) err_divisor / (freq_hz / SCI_UART_MDDR_MAX);
1313 
1314                     /* The maximum value that could result from the calculation above is 256, which is a valid MDDR
1315                      * value, so only the lower bound is checked. */
1316                     if (mddr < SCI_UART_MDDR_MIN)
1317                     {
1318                         break;
1319                     }
1320 
1321                     /** Adjust bit rate error for bit rate modulation. The following formula is used:
1322                      *  bit rate error [%] = ((bit rate error [%, no modulation] + 100) * MDDR / 256) - 100
1323                      */
1324                     bit_err = (((bit_err + SCI_UART_100_PERCENT_X_1000) * (int32_t) mddr) /
1325                               SCI_UART_MDDR_DIVISOR) - SCI_UART_100_PERCENT_X_1000;
1326                 }
1327 
1328                 /** Take the absolute value of the bit rate error. */
1329                 if (bit_err < 0)
1330                 {
1331                     bit_err = -bit_err;
1332                 }
1333 
1334                 /** If the absolute value of the bit rate error is less than the previous lowest absolute value of
1335                  *  bit rate error, then store these settings as the best value.
1336                  */
1337                 if (bit_err < hit_bit_err)
1338                 {
1339                     *pp_baud_setting = &p_baudinfo[i];
1340                     *p_brr_value     = (uint8_t) temp_brr;
1341                     hit_bit_err      = bit_err;
1342                     hit_mddr         = mddr;
1343                 }
1344                 if (NULL == p_mddr)
1345                 {
1346                     break;
1347                 }
1348                 else
1349                 {
1350                     *p_mddr = hit_mddr;
1351                 }
1352             }
1353         }
1354     }
1355 
1356     return hit_bit_err;
1357 }
1358 
1359 /*******************************************************************************************************************//**
1360  * Calculates baud rate register settings. Evaluates and determines the best possible settings set to the baud rate
1361  * related registers.
1362  *
1363  * @param[in]  clk_src               A clock source for SCI module
1364  * @param[in]  baudrate              Baud rate[bps] e.g. 19200, 57600, 115200, etc.
1365  * @param[out] p_brr_value           Bit rate register value stored here if successful
1366  * @param[out] pp_baud_setting       Baud setting information stored here if successful
1367  * @param[out] p_mddr                MDDR register value stored here if successful
1368  * @param[in]  baud_rate_error_x_1000 \<baud_rate_percent_error\> x 1000 required for module to function. Absolute max baud_rate_error is 15000(15%).
1369  *
1370  * @retval  SSP_SUCCESS                  Baud rate is set successfully
1371  * @retval  SSP_ERR_INVALID_ARGUMENT     Baud rate is '0', source clock frequency could not be read, or error in
1372  *                                       calculated baud rate is larger than 10%.
1373  *
1374  * @return                       See @ref Common_Error_Codes or functions called by this function for other possible
1375  *                               return codes. This function calls:
1376  *                                   * cgc_api_t::systemClockFreqGet
1377  **********************************************************************************************************************/
r_sci_uart_baud_calculate(sci_clk_src_t clk_src,uint32_t baudrate,uint8_t * p_brr_value,baud_setting_t const ** pp_baud_setting,uint32_t * p_mddr,uint32_t baud_rate_error_x_1000)1378 static ssp_err_t r_sci_uart_baud_calculate(sci_clk_src_t           clk_src,
1379                                            uint32_t                baudrate,
1380                                            uint8_t               * p_brr_value,
1381                                            baud_setting_t const ** pp_baud_setting,
1382                                            uint32_t              * p_mddr,
1383                                            uint32_t                baud_rate_error_x_1000)
1384 {
1385     *p_brr_value     = SCI_UART_BRR_MAX;
1386     *pp_baud_setting = &async_baud[0];
1387 
1388     if (SCI_CLK_SRC_INT == clk_src)
1389     {
1390 #if (SCI_UART_CFG_PARAM_CHECKING_ENABLE)
1391         SCI_UART_ERROR_RETURN(SCI_UART_MAX_BAUD_RATE_ERROR_X_1000 > baud_rate_error_x_1000, SSP_ERR_INVALID_ARGUMENT);
1392         SCI_UART_ERROR_RETURN((0U != baudrate), SSP_ERR_INVALID_ARGUMENT);
1393 #endif
1394 
1395         bsp_feature_sci_t sci_feature = {0U};
1396         R_BSP_FeatureSciGet(&sci_feature);
1397         uint32_t freq_hz = 0U;
1398         ssp_err_t err = g_cgc_on_cgc.systemClockFreqGet((cgc_system_clocks_t) sci_feature.clock, &freq_hz);
1399         SCI_UART_ERROR_RETURN(SSP_SUCCESS == err, SSP_ERR_INVALID_ARGUMENT);
1400 
1401         /** Try to get accurate baudrate using 16 base clk cycles per bit */
1402         int32_t  hit_bit_err = r_sci_uart_brr_mddr_calculate(freq_hz, baudrate, p_brr_value, pp_baud_setting, p_mddr, true);
1403 
1404         /** If the clock is not accurate enough, try with different base clk cycles per bit */
1405         if (hit_bit_err > ((int32_t) baud_rate_error_x_1000))
1406         {
1407             hit_bit_err = r_sci_uart_brr_mddr_calculate(freq_hz, baudrate, p_brr_value, pp_baud_setting, p_mddr, false);
1408         }
1409 
1410         /** Return an error if the percent error is larger than the maximum percent error allowed for this instance */
1411         SCI_UART_ERROR_RETURN((hit_bit_err <= (int32_t) baud_rate_error_x_1000), SSP_ERR_INVALID_ARGUMENT);
1412     }
1413 
1414     return SSP_SUCCESS;
1415 }
1416 
1417 /*******************************************************************************************************************//**
1418  * Changes baud rate based on predetermined register settings.
1419  *
1420  * @param[in] p_sci_reg       Base pointer for SCI registers
1421  * @param[in] clk_src         A clock source for SCI module
1422  * @param[in] brr             Bit rate register setting
1423  * @param[in] p_baud_setting  Pointer to other divisor related settings
1424  * @param[in] p_mddr          Pointer to bit rate modulation register setting, NULL if not used.
1425  *
1426  * @note   The transmitter and receiver (TE and RE bits in SCR) must be disabled prior to calling this function.
1427  **********************************************************************************************************************/
r_sci_uart_baud_set(R_SCI0_Type * p_sci_reg,sci_clk_src_t const clk_src,uint8_t const brr,baud_setting_t const * const p_baud_setting,uint32_t const * const p_mddr)1428 static void r_sci_uart_baud_set (R_SCI0_Type          *       p_sci_reg,
1429                                  sci_clk_src_t          const clk_src,
1430                                  uint8_t                const brr,
1431                                  baud_setting_t const * const p_baud_setting,
1432                                  uint32_t       const * const p_mddr)
1433 {
1434     if (SCI_CLK_SRC_INT == clk_src)
1435     {
1436         HW_SCI_BaudRateGenInternalClkSelect(p_sci_reg);
1437 
1438         HW_SCI_UartBitRateSet(p_sci_reg, brr, p_baud_setting);
1439 
1440         /* Check Bitrate Modulation function is enabled or not.
1441          * If it is enabled,set the MDDR register to correct the bit rate generated by the on-chip baud rate generator */
1442         if (NULL != p_mddr)
1443         {
1444             /* Set MDDR register only for values between 128 and 256, do not set otherwise */
1445             uint32_t mddr = *p_mddr;
1446             if (mddr < SCI_UART_MDDR_MAX)
1447             {
1448                 HW_SCI_BitRateModulationEnable(p_sci_reg, true);
1449                 HW_SCI_UartBitRateModulationSet(p_sci_reg, (uint8_t) mddr);
1450             }
1451             else
1452             {
1453                 HW_SCI_BitRateModulationEnable(p_sci_reg, false);
1454             }
1455         }
1456     }
1457     else
1458     {
1459         HW_SCI_BitRateDefaultSet(p_sci_reg);
1460 
1461         HW_SCI_BaudRateGenExternalClkSelect(p_sci_reg);
1462 
1463         if (SCI_CLK_SRC_EXT8X == clk_src)
1464         {
1465             HW_SCI_BaudRateGenExternalClkDivideBy8(p_sci_reg);
1466         }
1467     }
1468 }  /* End of function r_sci_uart_baud_set() */
1469 
1470 #if (SCI_UART_CFG_TX_ENABLE)
1471 /*******************************************************************************************************************//**
1472  * Set up the Uart Write if DTC is selected.
1473  *
1474  * @param[in] p_ctrl   Pointer to the control block for the channel
1475  * @param[in] p_src    Source to transfer data
1476  * @param[in] bytes    Number of bytes to transfer
1477  **********************************************************************************************************************/
r_sci_uart_write_transfer_setup(sci_uart_instance_ctrl_t * const p_ctrl,uint8_t const * const p_src,uint32_t const bytes)1478 static ssp_err_t r_sci_uart_write_transfer_setup(sci_uart_instance_ctrl_t * const p_ctrl,
1479                                                  uint8_t             const * const p_src,
1480                                                  uint32_t                    const bytes)
1481 {
1482     ssp_err_t err = SSP_SUCCESS;
1483     uint32_t data_bytes = p_ctrl->data_bytes;
1484     p_ctrl->tx_src_bytes = 0U;
1485     uint32_t num_transfers =  bytes >> (data_bytes - 1);
1486 #if (SCI_UART_CFG_PARAM_CHECKING_ENABLE)
1487     transfer_properties_t transfer_max = {0U};
1488     p_ctrl->p_transfer_tx->p_api->infoGet(p_ctrl->p_transfer_tx->p_ctrl, &transfer_max);
1489     SSP_ASSERT(num_transfers <= transfer_max.transfer_length_max);
1490 #endif
1491     void const * p_transfer_src = p_src;
1492     bool do_not_reset = false;
1493     if (0U == p_ctrl->fifo_depth)
1494     {
1495         /* If the channel has no FIFO, the first byte is sent later in this function to trigger the TXI event to
1496          * start the DTC, so skip the first byte when configuring the transfer. */
1497         p_ctrl->tx_src_bytes = data_bytes;
1498         p_transfer_src = (void const *) ((uint32_t) p_src + data_bytes);
1499         num_transfers--;
1500         if (0U == num_transfers)
1501         {
1502             do_not_reset = true;
1503         }
1504     }
1505     if (!do_not_reset)
1506     {
1507         err = p_ctrl->p_transfer_tx->p_api->reset(p_ctrl->p_transfer_tx->p_ctrl, p_transfer_src,
1508                                                   NULL, (uint16_t) num_transfers);
1509         SCI_UART_ERROR_RETURN(SSP_SUCCESS == err, err);
1510     }
1511     return err;
1512 }
1513 
1514 /*******************************************************************************************************************//**
1515  * Writes the next byte (or 2 bytes if 9-bit mode is selected) of data to the transmit register.
1516  *
1517  * @param[in] p_ctrl   Pointer to the control block for the channel
1518  **********************************************************************************************************************/
r_sci_uart_write_no_transfer(sci_uart_instance_ctrl_t * const p_ctrl)1519 void r_sci_uart_write_no_transfer(sci_uart_instance_ctrl_t * const p_ctrl)
1520 {
1521     if (0U == p_ctrl->tx_src_bytes)
1522     {
1523         /* Nothing to write. */
1524         return;
1525     }
1526 
1527     /** Locate next data to transmit (2 bytes for 9-bit mode, 1 byte otherwise). */
1528     uint16_t data = 0U;
1529     if (SCI_UART_DATA_SIZE_2_BYTES == p_ctrl->data_bytes)
1530     {
1531         data = (uint16_t) *((uint16_t *) p_ctrl->p_tx_src);
1532     }
1533     else
1534     {
1535         data = (uint16_t) *(p_ctrl->p_tx_src);
1536     }
1537 
1538     /** Write the data to the FIFO if the channel has a FIFO.  Otherwise write data based on size to the transmit
1539      * register.  Write to 16-bit TDRHL for 9-bit data, or 8-bit TDR otherwise. */
1540     R_SCI0_Type * p_sci_reg = (R_SCI0_Type *) p_ctrl->p_reg;
1541     if (p_ctrl->fifo_depth > 0U)
1542     {
1543         HW_SCI_WriteFIFO(p_sci_reg, data);
1544     }
1545     else
1546     {
1547         if (SCI_UART_DATA_SIZE_2_BYTES == p_ctrl->data_bytes)
1548         {
1549             HW_SCI_Write9bits (p_sci_reg, data);
1550         }
1551         else
1552         {
1553             HW_SCI_Write (p_sci_reg, (uint8_t) data);
1554         }
1555     }
1556 
1557     /** Update pointer to the next data and number of remaining bytes in the control block. */
1558     p_ctrl->tx_src_bytes -= p_ctrl->data_bytes;
1559     p_ctrl->p_tx_src += p_ctrl->data_bytes;
1560 }
1561 #endif /* if (SCI_UART_CFG_TX_ENABLE) */
1562 
1563 #if (SCI_UART_CFG_RX_ENABLE)
1564 /*******************************************************************************************************************//**
1565  * Reads the requested number of data (2 bytes for 9-bit mode, 1 byte otherwise) and calls the user callback with event
1566  * UART_EVENT_RX_CHAR for each.
1567  *
1568  * @param[in]  p_ctrl   Pointer to the control block for the channel
1569  * @param[out] p_data   Data read from SCI stored here
1570  **********************************************************************************************************************/
r_sci_uart_read_data(sci_uart_instance_ctrl_t * const p_ctrl,uint32_t * const p_data)1571 void r_sci_uart_read_data(sci_uart_instance_ctrl_t * const p_ctrl,
1572                           uint32_t                 * const p_data)
1573 {
1574     R_SCI0_Type * p_sci_reg = (R_SCI0_Type *) p_ctrl->p_reg;
1575     if (p_ctrl->fifo_depth > 0U)
1576     {
1577         *p_data = HW_SCI_ReadFIFO(p_sci_reg);
1578     }
1579     else
1580     {
1581         if (SCI_UART_DATA_SIZE_2_BYTES == p_ctrl->data_bytes)
1582         {
1583             *p_data = HW_SCI_Read9bits (p_sci_reg);
1584         }
1585         else
1586         {
1587             *p_data = HW_SCI_Read (p_sci_reg);
1588         }
1589     }
1590 }
1591 #endif /* if (SCI_UART_CFG_RX_ENABLE) */
1592 
1593 #if (SCI_UART_CFG_RX_ENABLE)
1594 /*******************************************************************************************************************//**
1595  * Reads the requested number of data (2 bytes for 9-bit mode, 1 byte otherwise) and calls the user callback with event
1596  * UART_EVENT_RX_CHAR for each.
1597  *
1598  * @param[in] p_ctrl   Pointer to the control block for the channel
1599  **********************************************************************************************************************/
r_sci_uart_rxi_read_no_transfer(sci_uart_instance_ctrl_t * const p_ctrl)1600 void r_sci_uart_rxi_read_no_transfer(sci_uart_instance_ctrl_t * const p_ctrl)
1601 {
1602     /** Determine how much data to read based on how many slots of the read FIFO are filled. */
1603     R_SCI0_Type * p_sci_reg = (R_SCI0_Type *) p_ctrl->p_reg;
1604     uint32_t data = 0;
1605 
1606     if (p_ctrl->fifo_depth > 0U)
1607     {
1608         do{
1609             /** Clear Receive Data Ready Flag (DR) */
1610             HW_SCI_DRClear(p_sci_reg);
1611 
1612             /** Read all the FIFO data when callback is configured */
1613             if (NULL != p_ctrl->p_callback)
1614             {
1615                 /** Read all data in the FIFO or receive register. */
1616                 while (HW_SCI_FIFO_ReadCount(p_sci_reg) > 0U)
1617                 {
1618                     data = HW_SCI_ReadFIFO(p_sci_reg);
1619                     r_sci_uart_rxi_read_no_transfer_eventset(p_ctrl, data);
1620                 }
1621             }
1622 
1623             else
1624             {
1625                 /** Dummy read to flush the FIFO when callback is not configured */
1626                 while (HW_SCI_FIFO_ReadCount(p_sci_reg) > 0U)
1627                 {
1628                     HW_SCI_ReadFIFO(p_sci_reg);
1629                 }
1630             }
1631             /** Clear receive FIFO data full flag (RDF) */
1632             HW_SCI_RDFClear(p_sci_reg);
1633             /* Read receive data from FIFO, until DR flag become zero.*/
1634         }while(HW_SCI_DRBitGet(p_sci_reg));
1635     }
1636     else
1637     {
1638         r_sci_uart_read_data(p_ctrl, &data);
1639         /** Call user callback with the data. */
1640         if (NULL != p_ctrl->p_callback)
1641         {
1642             r_sci_uart_rxi_read_no_transfer_eventset(p_ctrl, data);
1643         }
1644     }
1645 }
1646 #endif /* if (SCI_UART_CFG_RX_ENABLE) */
1647 
1648 #if (SCI_UART_CFG_RX_ENABLE)
1649 /*******************************************************************************************************************//**
1650  * Calls the user callback with event.
1651  * When read API called --> invokes callback with UART_EVENT_RX_COMPLETE event after receiving the expected bytes.
1652  * When callback is used to receive data --> invokes callback with UART_EVENT_RX_CHAR event after each byte.
1653  * @param[in] p_ctrl   Pointer to the control block for the channel
1654  * @param[out] data   Data read from SCI stored here
1655  **********************************************************************************************************************/
r_sci_uart_rxi_read_no_transfer_eventset(sci_uart_instance_ctrl_t * const p_ctrl,uint32_t const data)1656 void r_sci_uart_rxi_read_no_transfer_eventset(sci_uart_instance_ctrl_t * const p_ctrl,
1657                                               uint32_t                   const data)
1658 {
1659     uart_callback_args_t args;
1660 
1661     /** Initialize the immutable data fields **/
1662     args.channel = p_ctrl->channel;
1663     args.p_context = p_ctrl->p_context;
1664     args.event = UART_EVENT_RX_CHAR;
1665 
1666     /* If read API is not called then invoke callback with UART_EVENT_RX_CHAR event for each byte */
1667     if(p_ctrl->rx_dst_bytes == 0U)
1668     {
1669         args.data = data;
1670         args.event = UART_EVENT_RX_CHAR;
1671         p_ctrl->p_callback(&args);
1672     }
1673     /* If read API is called then invoke callback with UART_EVENT_RX_COMPLETE event after receiving the expected bytes.*/
1674     else if(p_ctrl->rx_bytes_count < p_ctrl->rx_dst_bytes)
1675     {
1676         if (SCI_UART_DATA_SIZE_2_BYTES == p_ctrl->data_bytes)
1677         {   /* 9 bit data mode of operation */
1678             p_ctrl->rx_bytes_count += p_ctrl->data_bytes;
1679             *(p_ctrl->p_rx_dst) = data & 0xFF;
1680             p_ctrl->p_rx_dst += 1;
1681             *(p_ctrl->p_rx_dst) = (data >> 8) & 0xFF;
1682             p_ctrl->p_rx_dst += 1;
1683         }
1684         else
1685         {
1686             /* 7 or 8 bit data mode of operation */
1687             p_ctrl->rx_bytes_count += p_ctrl->data_bytes;
1688             *(p_ctrl->p_rx_dst) = data & 0xFF;
1689             p_ctrl->p_rx_dst += 1;
1690         }
1691 
1692         if(p_ctrl->rx_bytes_count == p_ctrl->rx_dst_bytes)
1693         {
1694             /* Invoke callback with UART_EVENT_RX_COMPLETE event once the expected bytes are received*/
1695             args.data = 0U;
1696             args.event = UART_EVENT_RX_COMPLETE;
1697             p_ctrl->rx_bytes_count = 0U;
1698             p_ctrl->rx_dst_bytes = 0U;
1699             p_ctrl->p_callback(&args);
1700         }
1701     }
1702 }
1703 #endif /* if (SCI_UART_CFG_RX_ENABLE) */
1704 
1705 #if (SCI_UART_CFG_TX_ENABLE)
1706 /*******************************************************************************************************************//**
1707  * Abort ongoing transmission by disabling irq and DTC, Reset the FIFO
1708  *
1709  * @param[in] p_ctrl              Pointer to UART instance control
1710  *
1711  * @retval  SSP_SUCCESS           Transmission aborted successfully
1712  *
1713  * @return                       See @ref Common_Error_Codes or functions called by this function for other possible
1714  *                               return codes. This function calls:
1715  *                                   * transfer_api_t::disable
1716  **********************************************************************************************************************/
r_sci_uart_abort_tx(sci_uart_instance_ctrl_t * p_ctrl)1717 static ssp_err_t r_sci_uart_abort_tx(sci_uart_instance_ctrl_t * p_ctrl)
1718 {
1719     ssp_err_t err = SSP_SUCCESS;
1720     HW_SCI_UartTransmitIrqDisable(p_ctrl->p_reg);
1721     R_BSP_IrqStatusClear(p_ctrl->txi_irq);
1722     NVIC_DisableIRQ(p_ctrl->txi_irq);
1723     NVIC_ClearPendingIRQ(p_ctrl->txi_irq);
1724     R_BSP_IrqStatusClear(p_ctrl->tei_irq);
1725     NVIC_DisableIRQ(p_ctrl->tei_irq);
1726     NVIC_ClearPendingIRQ(p_ctrl->tei_irq);
1727     if (NULL != p_ctrl->p_transfer_tx)
1728     {
1729         err = p_ctrl->p_transfer_tx->p_api->disable(p_ctrl->p_transfer_tx->p_ctrl);
1730     }
1731     if (0U != p_ctrl->fifo_depth)
1732     {
1733         HW_SCI_TransmitFifoReset(p_ctrl->p_reg);
1734     }
1735     p_ctrl->p_tx_src = NULL;
1736     p_ctrl->tx_src_bytes = 0U;
1737     /** Clear the Driver Enable pin in RS485 half duplex mode to enable reception */
1738     r_sci_uart_rs485_de_pin_cfg(p_ctrl);
1739     return err;
1740 }
1741 #endif
1742 
1743 #if (SCI_UART_CFG_RX_ENABLE)
1744 /*******************************************************************************************************************//**
1745  * Abort ongoing reception by disabling DTC and Reset the FIFO
1746  *
1747  * @param[in] p_ctrl                 Pointer to UART instance control
1748  *
1749  * @retval  SSP_SUCCESS              Reception aborted successfully
1750  *
1751  * @return                       See @ref Common_Error_Codes or functions called by this function for other possible
1752  *                               return codes. This function calls:
1753  *                                   * transfer_api_t::disable
1754  **********************************************************************************************************************/
r_sci_uart_abort_rx(sci_uart_instance_ctrl_t * p_ctrl)1755 static ssp_err_t r_sci_uart_abort_rx(sci_uart_instance_ctrl_t * p_ctrl)
1756 {
1757     ssp_err_t err = SSP_SUCCESS;
1758     if (NULL != p_ctrl->p_transfer_rx)
1759     {
1760         p_ctrl->rx_transfer_in_progress = 0U;
1761         err = p_ctrl->p_transfer_rx->p_api->disable(p_ctrl->p_transfer_rx->p_ctrl);
1762     }
1763     else
1764     {
1765         /* Clear byte count and bytes when ongoing UART reception is aborted */
1766         p_ctrl->rx_bytes_count = 0U;
1767         p_ctrl->rx_dst_bytes = 0U;
1768 
1769     }
1770     if (0U != p_ctrl->fifo_depth)
1771     {
1772         HW_SCI_ReceiveFifoReset(p_ctrl->p_reg);
1773     }
1774     return err;
1775 }
1776 #endif
1777 
1778 #if (SCI_UART_CFG_TX_ENABLE)
1779 /*******************************************************************************************************************//**
1780  * TXI interrupt processing for UART mode. TXI interrupt fires when the data in the data register or FIFO register has
1781  * been transferred to the data shift register, and the next data can be written.  This interrupt writes the next data.
1782  * After the last data byte is written, this interrupt disables the TXI interrupt and enables the TEI (transmit end)
1783  * interrupt.
1784  **********************************************************************************************************************/
sci_uart_txi_isr(void)1785 void sci_uart_txi_isr (void)
1786 {
1787     /* Save context if RTOS is used */
1788     SF_CONTEXT_SAVE;
1789 
1790     /** Clear pending IRQ to make sure it doesn't fire again after exiting */
1791     R_BSP_IrqStatusClear(R_SSP_CurrentIrqGet());
1792 
1793     ssp_vector_info_t * p_vector_info = NULL;
1794     R_SSP_VectorInfoGet(R_SSP_CurrentIrqGet(), &p_vector_info);
1795     sci_uart_instance_ctrl_t * p_ctrl = (sci_uart_instance_ctrl_t *) *(p_vector_info->pp_ctrl);
1796 
1797     if (NULL != p_ctrl)
1798     {
1799         R_SCI0_Type * p_sci_reg = (R_SCI0_Type *) p_ctrl->p_reg;
1800 
1801         if (NULL == p_ctrl->p_transfer_tx)
1802         {
1803             /** If transfer is not used, write data until FIFO is full. */
1804             if (0U == p_ctrl->fifo_depth)
1805             {
1806                 r_sci_uart_write_no_transfer(p_ctrl);
1807             }
1808             else
1809             {
1810                 uint32_t fifo_filled = HW_SCI_FIFO_WriteCount(p_sci_reg);
1811                 int32_t fifo_open = (int32_t) p_ctrl->fifo_depth - (int32_t) fifo_filled;
1812                 for (int32_t cnt = 0; cnt < fifo_open; cnt++)
1813                 {
1814                     r_sci_uart_write_no_transfer(p_ctrl);
1815                 }
1816                 HW_SCI_TDFEClear(p_sci_reg);
1817             }
1818         }
1819         if (0U == p_ctrl->tx_src_bytes)
1820         {
1821             /** After all data has been transmitted, disable transmit interrupts and enable the transmit end interrupt. */
1822             HW_SCI_TeIrqEnable(p_sci_reg, p_ctrl);
1823             p_ctrl->p_tx_src = NULL;
1824             uart_callback_args_t args;
1825             if (NULL != p_ctrl->p_callback)
1826             {
1827                 args.channel   = p_ctrl->channel;
1828                 args.data      = 0U;
1829                 args.event     = UART_EVENT_TX_DATA_EMPTY;
1830                 args.p_context = p_ctrl->p_context;
1831                 p_ctrl->p_callback(&args);
1832             }
1833         }
1834     }
1835 
1836     /* Restore context if RTOS is used */
1837     SF_CONTEXT_RESTORE;
1838 }  /* End of function sci_uart_txi_isr() */
1839 #endif /* if (SCI_UART_CFG_TX_ENABLE) */
1840 
1841 #if (SCI_UART_CFG_RX_ENABLE)
1842 /*******************************************************************************************************************//**
1843  * RXI interrupt processing for UART mode. RXI interrupt happens when data arrives to the data register or the FIFO
1844  * register.  This function calls callback function when it meets conditions below.
1845  *  - UART_EVENT_RX_COMPLETE: The number of data which has been read reaches to the number specified in R_SCI_UartRead()
1846  *    if a transfer instance is used for reception.
1847  *  - UART_EVENT_RX_CHAR: Data is received asynchronously (read has not been called) or the transfer interface is not
1848  *    being used for reception.
1849  *
1850  * This interrupt also calls the callback function for RTS pin control if it is registered in R_SCI_UartOpen(). This is
1851  * special functionality to expand SCI hardware capability and make RTS/CTS hardware flow control possible. If macro
1852  * 'SCI_UART_CFG_EXTERNAL_RTS_OPERATION' is set, it is called at the beginning in this function to set the RTS pin high,
1853  * then it is it is called again just before leaving this function to set the RTS pin low.
1854  * @retval    none
1855  **********************************************************************************************************************/
sci_uart_rxi_isr(void)1856 void sci_uart_rxi_isr (void)
1857 {
1858     /* Save context if RTOS is used */
1859     SF_CONTEXT_SAVE;
1860 
1861     /** Clear pending IRQ to make sure it doesn't fire again after exiting */
1862     R_BSP_IrqStatusClear(R_SSP_CurrentIrqGet());
1863 
1864     ssp_vector_info_t * p_vector_info = NULL;
1865     R_SSP_VectorInfoGet(R_SSP_CurrentIrqGet(), &p_vector_info);
1866     sci_uart_instance_ctrl_t * p_ctrl = (sci_uart_instance_ctrl_t *) *(p_vector_info->pp_ctrl);
1867 
1868     if (NULL != p_ctrl)
1869     {
1870         uint8_t channel = p_ctrl->channel;
1871 
1872 #if (SCI_UART_CFG_EXTERNAL_RTS_OPERATION)
1873         /** If an external RTS callback is provided, call it to deassert RTS GPIO pin. */
1874         if (p_ctrl->p_extpin_ctrl)
1875         {
1876             p_ctrl->p_extpin_ctrl(channel, 1);
1877         }
1878 #endif
1879 
1880         if (1U == p_ctrl->rx_transfer_in_progress)
1881         {
1882             /** If a transfer has completed, call callback with event UART_EVENT_RX_COMPLETE. */
1883             p_ctrl->rx_transfer_in_progress = 0U;
1884 
1885             /* Do callback if available */
1886             if (NULL != p_ctrl->p_callback)
1887             {
1888                 uart_callback_args_t args;
1889                 args.channel        = channel;
1890                 args.data           = 0U;
1891                 args.p_context      = p_ctrl->p_context;
1892                 args.event = UART_EVENT_RX_COMPLETE;
1893                 p_ctrl->p_callback(&args);
1894             }
1895         }
1896         else
1897         {
1898             /** If a character is received outside a transfer, call callback with event UART_EVENT_RX_CHAR. */
1899             r_sci_uart_rxi_read_no_transfer(p_ctrl);
1900         }
1901 #if (SCI_UART_CFG_EXTERNAL_RTS_OPERATION)
1902         /** If an external RTS callback is provided, call it to assert the RTS GPIO pin. */
1903         if (p_ctrl->p_extpin_ctrl)
1904         {
1905             p_ctrl->p_extpin_ctrl(channel, 0);         /** user definition function call to control GPIO */
1906         }
1907 #endif
1908     }
1909 
1910     /* Restore context if RTOS is used */
1911     SF_CONTEXT_RESTORE;
1912 }  /* End of function sci_uart_rxi_isr () */
1913 #endif /* if (SCI_UART_CFG_RX_ENABLE) */
1914 
1915 #if (SCI_UART_CFG_TX_ENABLE)
1916 /*******************************************************************************************************************//**
1917  * TEI interrupt processing for UART mode. The TEI interrupt fires after the last byte is transmitted on the TX pin.
1918  * The user callback function is called with the UART_EVENT_TX_COMPLETE event code (if it is registered in
1919  * R_SCI_UartOpen()).
1920  **********************************************************************************************************************/
sci_uart_tei_isr(void)1921 void sci_uart_tei_isr (void)
1922 {
1923     /* Save context if RTOS is used */
1924     SF_CONTEXT_SAVE;
1925 
1926     ssp_vector_info_t * p_vector_info = NULL;
1927     R_SSP_VectorInfoGet(R_SSP_CurrentIrqGet(), &p_vector_info);
1928     sci_uart_instance_ctrl_t * p_ctrl = (sci_uart_instance_ctrl_t *) *(p_vector_info->pp_ctrl);
1929 
1930     if (NULL != p_ctrl)
1931     {
1932         uint8_t channel = p_ctrl->channel;
1933         R_SCI0_Type * p_sci_reg = (R_SCI0_Type *) p_ctrl->p_reg;
1934         uart_callback_args_t args;
1935 
1936         /** Receiving TEI(transmit end interrupt) means the completion of transmission, so call callback function here. */
1937         HW_SCI_UartTransmitIrqDisable(p_sci_reg);
1938         NVIC_DisableIRQ(p_ctrl->tei_irq);
1939         if (NULL != p_ctrl->p_callback)
1940         {
1941             args.channel   = channel;
1942             args.data      = 0U;
1943             args.event     = UART_EVENT_TX_COMPLETE;
1944             args.p_context = p_ctrl->p_context;
1945             p_ctrl->p_callback(&args);
1946         }
1947     }
1948 
1949     /** Clear pending IRQ to make sure it doesn't fire again after exiting */
1950     R_BSP_IrqStatusClear(R_SSP_CurrentIrqGet());
1951 
1952     /** Clear the Driver Enable pin in RS485 half duplex mode to enable reception */
1953     r_sci_uart_rs485_de_pin_cfg(p_ctrl);
1954 
1955     /* Restore context if RTOS is used */
1956     SF_CONTEXT_RESTORE;
1957 }  /* End of function sci_uart_tei_isr () */
1958 #endif /* if (SCI_UART_CFG_TX_ENABLE) */
1959 
1960 #if (SCI_UART_CFG_RX_ENABLE)
1961 /*******************************************************************************************************************//**
1962  * ERI interrupt processing for UART mode. When an ERI interrupt fires, the user callback function is called if it is
1963  * registered in R_SCI_UartOpen() with the event code that triggered the interrupt.
1964  **********************************************************************************************************************/
sci_uart_eri_isr(void)1965 void sci_uart_eri_isr (void)
1966 {
1967     /* Save context if RTOS is used */
1968     SF_CONTEXT_SAVE;
1969 
1970     ssp_vector_info_t * p_vector_info = NULL;
1971     R_SSP_VectorInfoGet(R_SSP_CurrentIrqGet(), &p_vector_info);
1972     sci_uart_instance_ctrl_t * p_ctrl = (sci_uart_instance_ctrl_t *) *(p_vector_info->pp_ctrl);
1973 
1974     if (NULL != p_ctrl)
1975     {
1976         uint8_t channel = p_ctrl->channel;
1977         R_SCI0_Type * p_sci_reg = (R_SCI0_Type *) p_ctrl->p_reg;
1978         uint32_t             data = 0U;
1979         uart_callback_args_t args = {0U};
1980 
1981         /** Read data. */
1982         r_sci_uart_read_data(p_ctrl, &data);
1983 
1984         /** Determine cause of error. */
1985         if (HW_SCI_OverRunErrorCheck(p_sci_reg))
1986         {
1987             args.event = UART_EVENT_ERR_OVERFLOW;
1988         }
1989         else if (HW_SCI_FramingErrorCheck(p_sci_reg))
1990         {
1991             if (HW_SCI_BreakDetectionCheck(p_sci_reg))
1992             {
1993                 args.event = UART_EVENT_BREAK_DETECT;
1994             }
1995             else
1996             {
1997                 args.event = UART_EVENT_ERR_FRAMING;
1998             }
1999         }
2000         else
2001         {
2002             args.event = UART_EVENT_ERR_PARITY;
2003         }
2004 
2005         /** Clear error condition. */
2006         HW_SCI_ErrorConditionClear (p_sci_reg);
2007 
2008         /** Call callback if available. */
2009         if (NULL != p_ctrl->p_callback)
2010         {
2011             args.channel   = channel;
2012             args.data      = data;
2013             args.p_context = p_ctrl->p_context;
2014             p_ctrl->p_callback(&args);
2015         }
2016     }
2017 
2018     /** Clear pending IRQ to make sure it doesn't fire again after exiting */
2019     R_BSP_IrqStatusClear(R_SSP_CurrentIrqGet());
2020 
2021     /* Restore context if RTOS is used */
2022     SF_CONTEXT_RESTORE;
2023 }  /* End of function sci_uart_eri_isr () */
2024 #endif /* if (SCI_UART_CFG_RX_ENABLE) */
2025