]> git.donarmstrong.com Git - qmk_firmware.git/blob - tmk_core/tool/mbed/mbed-sdk/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_STM32F0/stm32f0xx_hal_smartcard.c
Merge commit '1fe4406f374291ab2e86e95a97341fd9c475fcb8'
[qmk_firmware.git] / tmk_core / tool / mbed / mbed-sdk / libraries / mbed / targets / cmsis / TARGET_STM / TARGET_STM32F0 / stm32f0xx_hal_smartcard.c
1 /**
2   ******************************************************************************
3   * @file    stm32f0xx_hal_smartcard.c
4   * @author  MCD Application Team
5   * @version V1.2.0
6   * @date    11-December-2014
7   * @brief   SMARTCARD HAL module driver.
8   *          This file provides firmware functions to manage the following 
9   *          functionalities of the SMARTCARD peripheral:
10   *           + Initialization and de-initialization functions
11   *           + IO operation functions
12   *           + Peripheral State and Errors functions
13   *           + Peripheral Control functions
14   *
15   @verbatim       
16  ===============================================================================
17                         ##### How to use this driver #####
18  ===============================================================================
19     [..]
20     The SMARTCARD HAL driver can be used as follows:
21     
22     (#) Declare a SMARTCARD_HandleTypeDef handle structure.
23     (#) Initialize the SMARTCARD low level resources by implementing the HAL_SMARTCARD_MspInit ()API:
24         (++) Enable the USARTx interface clock.
25         (++) SMARTCARD pins configuration:
26             (+++) Enable the clock for the SMARTCARD GPIOs.
27             (+++) Configure these SMARTCARD pins as alternate function pull-up.
28         (++) NVIC configuration if you need to use interrupt process (HAL_SMARTCARD_Transmit_IT()
29              and HAL_SMARTCARD_Receive_IT() APIs):
30             (+++) Configure the USARTx interrupt priority.
31             (+++) Enable the NVIC USART IRQ handle.
32         (++) DMA Configuration if you need to use DMA process (HAL_SMARTCARD_Transmit_DMA()
33              and HAL_SMARTCARD_Receive_DMA() APIs):
34             (+++) Declare a DMA handle structure for the Tx/Rx channel.
35             (+++) Enable the DMAx interface clock.
36             (+++) Configure the declared DMA handle structure with the required Tx/Rx parameters.                
37             (+++) Configure the DMA Tx/Rx channel.
38             (+++) Associate the initialized DMA handle to the SMARTCARD DMA Tx/Rx handle.
39             (+++) Configure the priority and enable the NVIC for the transfer complete interrupt on the DMA Tx/Rx channel.
40
41     (#) Program the Baud Rate, Parity, Mode(Receiver/Transmitter), clock enabling/disabling and accordingly,
42         the clock parameters (parity, phase, last bit), prescaler value, guard time and NACK on transmission
43         error enabling or disabling in the hsmartcard Init structure.
44         
45     (#) If required, program SMARTCARD advanced features (TX/RX pins swap, TimeOut, auto-retry counter,...)
46         in the hsmartcard AdvancedInit structure.
47
48     (#) Initialize the SMARTCARD associated USART registers by calling the HAL_SMARTCARD_Init() API:                                 
49         (++) This API configures also the low level Hardware GPIO, CLOCK, CORTEX...etc) by 
50              calling the customed HAL_SMARTCARD_MspInit() API.
51     
52         -@@- The specific SMARTCARD interrupts (Transmission complete interrupt, 
53              RXNE interrupt and Error Interrupts) will be managed using the macros
54              __HAL_SMARTCARD_ENABLE_IT() and __HAL_SMARTCARD_DISABLE_IT() inside the transmit and receive process.
55
56     (#) Three operation modes are available within this driver :
57  
58      *** Polling mode IO operation ***
59      =================================
60      [..]    
61        (+) Send an amount of data in blocking mode using HAL_SMARTCARD_Transmit() 
62        (+) Receive an amount of data in blocking mode using HAL_SMARTCARD_Receive()
63        
64      *** Interrupt mode IO operation ***    
65      ===================================
66      [..]    
67        (+) Send an amount of data in non blocking mode using HAL_SMARTCARD_Transmit_IT() 
68        (+) At transmission end of transfer HAL_SMARTCARD_TxCpltCallback is executed and user can 
69             add his own code by customization of function pointer HAL_SMARTCARD_TxCpltCallback
70        (+) Receive an amount of data in non blocking mode using HAL_SMARTCARD_Receive_IT() 
71        (+) At reception end of transfer HAL_SMARTCARD_RxCpltCallback is executed and user can 
72             add his own code by customization of function pointer HAL_SMARTCARD_RxCpltCallback                                      
73        (+) In case of transfer Error, HAL_SMARTCARD_ErrorCallback() function is executed and user can 
74             add his own code by customization of function pointer HAL_SMARTCARD_ErrorCallback
75
76      *** DMA mode IO operation ***    
77      ==============================
78      [..] 
79        (+) Send an amount of data in non blocking mode (DMA) using HAL_SMARTCARD_Transmit_DMA() 
80        (+) At transmission end of transfer HAL_SMARTCARD_TxCpltCallback is executed and user can 
81             add his own code by customization of function pointer HAL_SMARTCARD_TxCpltCallback
82        (+) Receive an amount of data in non blocking mode (DMA) using HAL_SMARTCARD_Receive_DMA() 
83        (+) At reception end of transfer HAL_SMARTCARD_RxCpltCallback is executed and user can 
84             add his own code by customization of function pointer HAL_SMARTCARD_RxCpltCallback                                      
85        (+) In case of transfer Error, HAL_SMARTCARD_ErrorCallback() function is executed and user can 
86             add his own code by customization of function pointer HAL_SMARTCARD_ErrorCallback
87
88      *** SMARTCARD HAL driver macros list ***
89      ========================================
90      [..]
91        Below the list of most used macros in SMARTCARD HAL driver.
92        
93        (+) __HAL_SMARTCARD_ENABLE: Enable the SMARTCARD peripheral 
94        (+) __HAL_SMARTCARD_DISABLE: Disable the SMARTCARD peripheral     
95        (+) __HAL_SMARTCARD_GET_FLAG : Check whether the specified SMARTCARD flag is set or not
96        (+) __HAL_SMARTCARD_CLEAR_FLAG : Clear the specified SMARTCARD pending flag
97        (+) __HAL_SMARTCARD_ENABLE_IT: Enable the specified SMARTCARD interrupt
98        (+) __HAL_SMARTCARD_DISABLE_IT: Disable the specified SMARTCARD interrupt
99       
100      [..] 
101        (@) You can refer to the SMARTCARD HAL driver header file for more useful macros
102
103   @endverbatim
104   ******************************************************************************
105   * @attention
106   *
107   * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
108   *
109   * Redistribution and use in source and binary forms, with or without modification,
110   * are permitted provided that the following conditions are met:
111   *   1. Redistributions of source code must retain the above copyright notice,
112   *      this list of conditions and the following disclaimer.
113   *   2. Redistributions in binary form must reproduce the above copyright notice,
114   *      this list of conditions and the following disclaimer in the documentation
115   *      and/or other materials provided with the distribution.
116   *   3. Neither the name of STMicroelectronics nor the names of its contributors
117   *      may be used to endorse or promote products derived from this software
118   *      without specific prior written permission.
119   *
120   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
121   * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
122   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
123   * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
124   * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
125   * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
126   * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
127   * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
128   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
129   * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
130   *
131   ******************************************************************************  
132   */
133
134 /* Includes ------------------------------------------------------------------*/
135 #include "stm32f0xx_hal.h"
136
137 #ifdef HAL_SMARTCARD_MODULE_ENABLED
138
139 #if !defined(STM32F030x6) && !defined(STM32F030x8) && !defined(STM32F070x6) && !defined(STM32F070xB) && !defined(STM32F030xC) 
140
141 /** @addtogroup STM32F0xx_HAL_Driver
142   * @{
143   */
144
145 /** @defgroup SMARTCARD SMARTCARD HAL module driver
146   * @brief HAL SMARTCARD module driver
147   * @{
148   */
149
150 /* Private typedef -----------------------------------------------------------*/
151 /* Private define ------------------------------------------------------------*/
152 /** @defgroup SMARTCARD_Private_Constants   SMARTCARD Private Constants
153   * @{
154   */
155 #define TEACK_REACK_TIMEOUT               1000
156 #define SMARTCARD_TXDMA_TIMEOUTVALUE      22000
157 #define SMARTCARD_TIMEOUT_VALUE           22000
158 #define USART_CR1_FIELDS      ((uint32_t)(USART_CR1_M | USART_CR1_PCE | USART_CR1_PS | \
159                                      USART_CR1_TE | USART_CR1_RE | USART_CR1_OVER8))
160 #define USART_CR2_CLK_FIELDS  ((uint32_t)(USART_CR2_CLKEN|USART_CR2_CPOL|USART_CR2_CPHA|USART_CR2_LBCL))   
161 #define USART_CR2_FIELDS      ((uint32_t)(USART_CR2_RTOEN|USART_CR2_CLK_FIELDS|USART_CR2_STOP))
162 #define USART_CR3_FIELDS      ((uint32_t)(USART_CR3_ONEBIT|USART_CR3_NACK|USART_CR3_SCARCNT))  
163 /**
164   * @}
165   */
166   
167 /* Private macro -------------------------------------------------------------*/
168 /* Private variables ---------------------------------------------------------*/
169 /* Private function prototypes -----------------------------------------------*/
170 /** @addtogroup SMARTCARD_Private_Functions   SMARTCARD Private Functions
171   * @{
172   */
173 static void SMARTCARD_DMATransmitCplt(DMA_HandleTypeDef *hdma);
174 static void SMARTCARD_DMAReceiveCplt(DMA_HandleTypeDef *hdma);
175 static void SMARTCARD_DMAError(DMA_HandleTypeDef *hdma); 
176 static HAL_StatusTypeDef SMARTCARD_SetConfig(SMARTCARD_HandleTypeDef *hsmartcard);
177 static HAL_StatusTypeDef SMARTCARD_WaitOnFlagUntilTimeout(SMARTCARD_HandleTypeDef *hsmartcard, uint32_t Flag, FlagStatus Status, uint32_t Timeout);
178 static HAL_StatusTypeDef SMARTCARD_CheckIdleState(SMARTCARD_HandleTypeDef *hsmartcard);
179 static HAL_StatusTypeDef SMARTCARD_Transmit_IT(SMARTCARD_HandleTypeDef *hsmartcard);
180 static HAL_StatusTypeDef SMARTCARD_EndTransmit_IT(SMARTCARD_HandleTypeDef *hsmartcard);
181 static HAL_StatusTypeDef SMARTCARD_Receive_IT(SMARTCARD_HandleTypeDef *hsmartcard);
182 static void SMARTCARD_AdvFeatureConfig(SMARTCARD_HandleTypeDef *hsmartcard);
183 /**
184   * @}
185   */
186
187 /* Exported functions ---------------------------------------------------------*/
188
189 /** @defgroup SMARTCARD_Exported_Functions SMARTCARD Exported Functions
190   * @{
191   */
192
193 /** @defgroup SMARTCARD_Exported_Functions_Group1 Initialization and de-initialization functions 
194   *  @brief    Initialization and Configuration functions 
195   *
196 @verbatim    
197 ===============================================================================
198             ##### Initialization and Configuration functions #####
199  ===============================================================================  
200     [..]
201   This subsection provides a set of functions allowing to initialize the USART 
202   in Smartcard mode.
203   [..]
204   The Smartcard interface is designed to support asynchronous protocol Smartcards as
205   defined in the ISO 7816-3 standard.
206   [..]
207   The USART can provide a clock to the smartcard through the SCLK output.
208   In smartcard mode, SCLK is not associated to the communication but is simply derived 
209   from the internal peripheral input clock through a 5-bit prescaler.
210   [..]
211   (+) For the Smartcard mode only these parameters can be configured: 
212         (++) Baud Rate
213         (++) Parity: parity should be enabled,
214              Frame Length is fixed to 8 bits plus parity:
215              the USART frame format is given in the following table:
216    +---------------------------------------------------------------+     
217    |    M bit  |  PCE bit  |            USART frame                |
218    |---------------------|-----------------------------------------| 
219    |     1     |    1      |    | SB | 8 bit data | PB | STB |     |
220    +---------------------------------------------------------------+ 
221    or
222    +---------------------------------------------------------------+ 
223    | M1M0 bits |  PCE bit  |            USART frame                |
224    |-----------------------|---------------------------------------|
225    |     01    |    1      |    | SB | 8 bit data | PB | STB |     |
226    +---------------------------------------------------------------+                    
227
228         (++) Receiver/transmitter modes
229         (++) Synchronous mode (and if enabled, phase, polarity and last bit parameters)
230         (++) Prescaler value
231         (++) Guard bit time 
232         (++) NACK enabling or disabling on transmission error               
233
234       (+) The following advanced features can be configured as well:
235         (++) TX and/or RX pin level inversion
236         (++) data logical level inversion
237         (++) RX and TX pins swap
238         (++) RX overrun detection disabling
239         (++) DMA disabling on RX error
240         (++) MSB first on communication line
241         (++) Time out enabling (and if activated, timeout value)
242         (++) Block length
243         (++) Auto-retry counter       
244         
245     [..]                                                  
246     The HAL_SMARTCARD_Init() API follow respectively the USART (a)synchronous configuration procedures 
247     (details for the procedures are available in reference manual).
248
249 @endverbatim
250   * @{
251   */
252
253 /**
254   * @brief Initializes the SMARTCARD mode according to the specified
255   *         parameters in the SMARTCARD_InitTypeDef and creates the associated handle .
256   * @param hsmartcard: SMARTCARD handle
257   * @retval HAL status
258   */
259 HAL_StatusTypeDef HAL_SMARTCARD_Init(SMARTCARD_HandleTypeDef *hsmartcard)
260 {
261   /* Check the SMARTCARD handle allocation */
262   if(hsmartcard == NULL)
263   {
264     return HAL_ERROR;
265   }
266   
267   /* Check the USART associated to the SmartCard */
268   assert_param(IS_SMARTCARD_INSTANCE(hsmartcard->Instance));
269   
270   if(hsmartcard->State == HAL_SMARTCARD_STATE_RESET)
271   {   
272     /* Init the low level hardware : GPIO, CLOCK */
273     HAL_SMARTCARD_MspInit(hsmartcard);
274   }
275   
276   hsmartcard->State = HAL_SMARTCARD_STATE_BUSY;
277   
278   /* Disable the Peripheral */
279   __HAL_SMARTCARD_DISABLE(hsmartcard);
280   
281   /* Set the SMARTCARD Communication parameters */
282   if (SMARTCARD_SetConfig(hsmartcard) == HAL_ERROR)
283   {
284     return HAL_ERROR;
285   }  
286   
287   if (hsmartcard->AdvancedInit.AdvFeatureInit != SMARTCARD_ADVFEATURE_NO_INIT)
288   {
289     SMARTCARD_AdvFeatureConfig(hsmartcard);
290   }
291   
292   /* In SmartCard mode, the following bits must be kept cleared: 
293   - LINEN in the USART_CR2 register,
294   - HDSEL and IREN  bits in the USART_CR3 register.*/
295   hsmartcard->Instance->CR2 &= ~(USART_CR2_LINEN); 
296   hsmartcard->Instance->CR3 &= ~(USART_CR3_HDSEL | USART_CR3_IREN); 
297   
298   /* set the USART in SMARTCARD mode */ 
299   hsmartcard->Instance->CR3 |= USART_CR3_SCEN; 
300       
301   /* Enable the Peripheral */
302   __HAL_SMARTCARD_ENABLE(hsmartcard);
303   
304   /* TEACK and/or REACK to check before moving hsmartcard->State to Ready */
305   return (SMARTCARD_CheckIdleState(hsmartcard));
306 }
307
308
309 /**
310   * @brief DeInitializes the SMARTCARD peripheral 
311   * @param hsmartcard: SMARTCARD handle
312   * @retval HAL status
313   */
314 HAL_StatusTypeDef HAL_SMARTCARD_DeInit(SMARTCARD_HandleTypeDef *hsmartcard)
315 {
316   /* Check the SMARTCARD handle allocation */
317   if(hsmartcard == NULL)
318   {
319     return HAL_ERROR;
320   }
321   
322   /* Check the parameters */
323   assert_param(IS_SMARTCARD_INSTANCE(hsmartcard->Instance));
324
325   hsmartcard->State = HAL_SMARTCARD_STATE_BUSY;
326   
327   /* Disable the Peripheral */
328   __HAL_SMARTCARD_DISABLE(hsmartcard);
329   
330   hsmartcard->Instance->CR1 = 0x0;
331   hsmartcard->Instance->CR2 = 0x0;
332   hsmartcard->Instance->CR3 = 0x0;
333   hsmartcard->Instance->RTOR = 0x0;
334   hsmartcard->Instance->GTPR = 0x0;
335   
336   /* DeInit the low level hardware */
337   HAL_SMARTCARD_MspDeInit(hsmartcard);
338
339   hsmartcard->ErrorCode = HAL_SMARTCARD_ERROR_NONE;
340   hsmartcard->State = HAL_SMARTCARD_STATE_RESET;
341   
342   /* Process Unlock */
343   __HAL_UNLOCK(hsmartcard);
344   
345   return HAL_OK;
346 }
347
348 /**
349   * @brief SMARTCARD MSP Init
350   * @param hsmartcard: SMARTCARD handle
351   * @retval None
352   */
353  __weak void HAL_SMARTCARD_MspInit(SMARTCARD_HandleTypeDef *hsmartcard)
354 {
355   /* NOTE : This function should not be modified, when the callback is needed,
356             the HAL_SMARTCARD_MspInit can be implemented in the user file
357    */ 
358 }
359
360 /**
361   * @brief SMARTCARD MSP DeInit
362   * @param hsmartcard: SMARTCARD handle
363   * @retval None
364   */
365  __weak void HAL_SMARTCARD_MspDeInit(SMARTCARD_HandleTypeDef *hsmartcard)
366 {
367   /* NOTE : This function should not be modified, when the callback is needed,
368             the HAL_SMARTCARD_MspDeInit can be implemented in the user file
369    */ 
370 }
371
372 /**
373   * @}
374   */
375
376 /** @defgroup SMARTCARD_Exported_Functions_Group2 IO operation functions 
377   *  @brief   SMARTCARD Transmit and Receive functions 
378   *
379 @verbatim   
380  ===============================================================================
381                       ##### IO operation functions #####
382  ===============================================================================  
383   [..]
384     This subsection provides a set of functions allowing to manage the SMARTCARD data transfers.
385
386   [..]
387     Smartcard is a single wire half duplex communication protocol. 
388     The Smartcard interface is designed to support asynchronous protocol Smartcards as
389     defined in the ISO 7816-3 standard. The USART should be configured as:
390     - 8 bits plus parity: where M=1 and PCE=1 in the USART_CR1 register
391     - 1.5 stop bits when transmitting and receiving: where STOP=11 in the USART_CR2 register.
392
393     (#) There are two modes of transfer:
394        (++) Blocking mode: The communication is performed in polling mode. 
395             The HAL status of all data processing is returned by the same function 
396             after finishing transfer.  
397        (++) No-Blocking mode: The communication is performed using Interrupts 
398            or DMA, These API s return the HAL status.
399            The end of the data processing will be indicated through the 
400            dedicated SMARTCARD IRQ when using Interrupt mode or the DMA IRQ when 
401            using DMA mode.
402            The HAL_SMARTCARD_TxCpltCallback(), HAL_SMARTCARD_RxCpltCallback() user callbacks 
403            will be executed respectivelly at the end of the transmit or Receive process
404            The HAL_SMARTCARD_ErrorCallback()user callback will be executed when a communication error is detected
405
406     (#) Blocking mode API s are :
407         (++) HAL_SMARTCARD_Transmit()
408         (++) HAL_SMARTCARD_Receive() 
409         
410     (#) Non Blocking mode API s with Interrupt are :
411         (++) HAL_SMARTCARD_Transmit_IT()
412         (++) HAL_SMARTCARD_Receive_IT()
413         (++) HAL_SMARTCARD_IRQHandler()
414
415     (#) Non Blocking mode functions with DMA are :
416         (++) HAL_SMARTCARD_Transmit_DMA()
417         (++) HAL_SMARTCARD_Receive_DMA()
418
419     (#) A set of Transfer Complete Callbacks are provided in non Blocking mode:
420         (++) HAL_SMARTCARD_TxCpltCallback()
421         (++) HAL_SMARTCARD_RxCpltCallback()
422         (++) HAL_SMARTCARD_ErrorCallback()
423       
424 @endverbatim
425   * @{
426   */
427
428 /**
429   * @brief Send an amount of data in blocking mode 
430   * @param hsmartcard: SMARTCARD handle
431   * @param pData: pointer to data buffer
432   * @param Size: amount of data to be sent
433   * @param Timeout : Timeout duration
434   * @retval HAL status
435   */
436 HAL_StatusTypeDef HAL_SMARTCARD_Transmit(SMARTCARD_HandleTypeDef *hsmartcard, uint8_t *pData, uint16_t Size, uint32_t Timeout)
437 {
438   if ((hsmartcard->State == HAL_SMARTCARD_STATE_READY) || (hsmartcard->State == HAL_SMARTCARD_STATE_BUSY_RX))
439   {
440     if((pData == NULL) || (Size == 0)) 
441     {
442       return  HAL_ERROR;
443     }
444     
445     /* Process Locked */
446     __HAL_LOCK(hsmartcard);
447     hsmartcard->ErrorCode = HAL_SMARTCARD_ERROR_NONE;    
448     /* Check if a non-blocking receive process is ongoing or not */
449     if(hsmartcard->State == HAL_SMARTCARD_STATE_BUSY_RX) 
450     {
451       hsmartcard->State = HAL_SMARTCARD_STATE_BUSY_TX_RX;
452     }
453     else
454     {
455       hsmartcard->State = HAL_SMARTCARD_STATE_BUSY_TX;
456     }
457     
458     hsmartcard->TxXferSize = Size;
459     hsmartcard->TxXferCount = Size;
460     while(hsmartcard->TxXferCount > 0)
461     {
462       hsmartcard->TxXferCount--;      
463       if(SMARTCARD_WaitOnFlagUntilTimeout(hsmartcard, SMARTCARD_FLAG_TXE, RESET, Timeout) != HAL_OK)  
464       { 
465         return HAL_TIMEOUT;
466       }        
467       hsmartcard->Instance->TDR = (*pData++ & (uint8_t)0xFF);     
468     }
469     if(SMARTCARD_WaitOnFlagUntilTimeout(hsmartcard, SMARTCARD_FLAG_TC, RESET, Timeout) != HAL_OK)  
470     { 
471       return HAL_TIMEOUT;
472     }
473     /* Check if a non-blocking receive Process is ongoing or not */
474     if(hsmartcard->State == HAL_SMARTCARD_STATE_BUSY_TX_RX) 
475     {
476       hsmartcard->State = HAL_SMARTCARD_STATE_BUSY_RX;
477     }
478     else
479     {
480       hsmartcard->State = HAL_SMARTCARD_STATE_READY;
481     }
482           
483     /* Process Unlocked */
484     __HAL_UNLOCK(hsmartcard);
485     
486     return HAL_OK;
487   }
488   else
489   {
490     return HAL_BUSY;   
491   }
492 }
493
494 /**
495   * @brief Receive an amount of data in blocking mode 
496   * @param hsmartcard: SMARTCARD handle
497   * @param pData: pointer to data buffer
498   * @param Size: amount of data to be received
499   * @param Timeout : Timeout duration
500   * @retval HAL status
501   */
502 HAL_StatusTypeDef HAL_SMARTCARD_Receive(SMARTCARD_HandleTypeDef *hsmartcard, uint8_t *pData, uint16_t Size, uint32_t Timeout)
503
504   if ((hsmartcard->State == HAL_SMARTCARD_STATE_READY) || (hsmartcard->State == HAL_SMARTCARD_STATE_BUSY_TX))
505   { 
506     if((pData == NULL) || (Size == 0)) 
507     {
508       return  HAL_ERROR;                                    
509     }
510     
511     /* Process Locked */
512     __HAL_LOCK(hsmartcard);
513     
514     hsmartcard->ErrorCode = HAL_SMARTCARD_ERROR_NONE;
515     /* Check if a non-blocking transmit process is ongoing or not */
516     if(hsmartcard->State == HAL_SMARTCARD_STATE_BUSY_TX) 
517     {
518       hsmartcard->State = HAL_SMARTCARD_STATE_BUSY_TX_RX;
519     }
520     else
521     {
522       hsmartcard->State = HAL_SMARTCARD_STATE_BUSY_RX;
523     }    
524     
525     hsmartcard->RxXferSize = Size; 
526     hsmartcard->RxXferCount = Size;
527     /* Check the remain data to be received */
528     while(hsmartcard->RxXferCount > 0)
529     {
530       hsmartcard->RxXferCount--;    
531       if(SMARTCARD_WaitOnFlagUntilTimeout(hsmartcard, SMARTCARD_FLAG_RXNE, RESET, Timeout) != HAL_OK)  
532       { 
533         return HAL_TIMEOUT;
534       }          
535       *pData++ = (uint8_t)(hsmartcard->Instance->RDR & (uint8_t)0x00FF);              
536     }
537     
538     /* Check if a non-blocking transmit Process is ongoing or not */
539     if(hsmartcard->State == HAL_SMARTCARD_STATE_BUSY_TX_RX) 
540     {
541       hsmartcard->State = HAL_SMARTCARD_STATE_BUSY_TX;
542     }
543     else
544     {
545       hsmartcard->State = HAL_SMARTCARD_STATE_READY;
546     }    
547    
548     /* Process Unlocked */
549     __HAL_UNLOCK(hsmartcard);
550     
551     return HAL_OK;
552   }
553   else
554   {
555     return HAL_BUSY;   
556   }
557 }
558
559 /**
560   * @brief Send an amount of data in interrupt mode 
561   * @param hsmartcard: SMARTCARD handle
562   * @param pData: pointer to data buffer
563   * @param Size: amount of data to be sent
564   * @retval HAL status
565   */
566 HAL_StatusTypeDef HAL_SMARTCARD_Transmit_IT(SMARTCARD_HandleTypeDef *hsmartcard, uint8_t *pData, uint16_t Size)
567 {
568   if ((hsmartcard->State == HAL_SMARTCARD_STATE_READY) || (hsmartcard->State == HAL_SMARTCARD_STATE_BUSY_RX))
569   {
570     if((pData == NULL) || (Size == 0)) 
571     {
572       return HAL_ERROR;                                    
573     }
574     
575     /* Process Locked */
576     __HAL_LOCK(hsmartcard);
577     
578     hsmartcard->pTxBuffPtr = pData;
579     hsmartcard->TxXferSize = Size;
580     hsmartcard->TxXferCount = Size;
581     
582     hsmartcard->ErrorCode = HAL_SMARTCARD_ERROR_NONE;
583     /* Check if a receive process is ongoing or not */
584     if(hsmartcard->State == HAL_SMARTCARD_STATE_BUSY_RX) 
585     {
586       hsmartcard->State = HAL_SMARTCARD_STATE_BUSY_TX_RX;
587     }
588     else
589     {
590       hsmartcard->State = HAL_SMARTCARD_STATE_BUSY_TX;
591     }    
592     
593     /* Enable the SMARTCARD Error Interrupt: (Frame error, noise error, overrun error) */
594     __HAL_SMARTCARD_ENABLE_IT(hsmartcard, SMARTCARD_IT_ERR);
595     
596     /* Process Unlocked */
597     __HAL_UNLOCK(hsmartcard);    
598     
599     /* Enable the SMARTCARD Transmit Data Register Empty Interrupt */
600     __HAL_SMARTCARD_ENABLE_IT(hsmartcard, SMARTCARD_IT_TXE);
601     
602     return HAL_OK;
603   }
604   else
605   {
606     return HAL_BUSY;   
607   }
608 }
609
610 /**
611   * @brief Receive an amount of data in interrupt mode 
612   * @param hsmartcard: SMARTCARD handle
613   * @param pData: pointer to data buffer
614   * @param Size: amount of data to be received
615   * @retval HAL status
616   */
617 HAL_StatusTypeDef HAL_SMARTCARD_Receive_IT(SMARTCARD_HandleTypeDef *hsmartcard, uint8_t *pData, uint16_t Size)
618 {
619   if ((hsmartcard->State == HAL_SMARTCARD_STATE_READY) || (hsmartcard->State == HAL_SMARTCARD_STATE_BUSY_TX))
620   {
621     if((pData == NULL) || (Size == 0)) 
622     {
623       return HAL_ERROR;                                    
624     }
625     
626     /* Process Locked */
627   __HAL_LOCK(hsmartcard);
628   
629     hsmartcard->pRxBuffPtr = pData;
630     hsmartcard->RxXferSize = Size;
631     hsmartcard->RxXferCount = Size;
632     
633     hsmartcard->ErrorCode = HAL_SMARTCARD_ERROR_NONE; 
634     /* Check if a transmit process is ongoing or not */
635     if(hsmartcard->State == HAL_SMARTCARD_STATE_BUSY_TX) 
636     {
637       hsmartcard->State = HAL_SMARTCARD_STATE_BUSY_TX_RX;
638     }
639     else
640     {
641       hsmartcard->State = HAL_SMARTCARD_STATE_BUSY_RX;
642     }    
643     
644     /* Enable the SMARTCARD Parity Error Interrupt */
645     __HAL_SMARTCARD_ENABLE_IT(hsmartcard, SMARTCARD_IT_PE);
646     
647     /* Enable the SMARTCARD Error Interrupt: (Frame error, noise error, overrun error) */
648     __HAL_SMARTCARD_ENABLE_IT(hsmartcard, SMARTCARD_IT_ERR);
649     
650     /* Process Unlocked */
651     __HAL_UNLOCK(hsmartcard);
652     
653     /* Enable the SMARTCARD Data Register not empty Interrupt */
654     __HAL_SMARTCARD_ENABLE_IT(hsmartcard, SMARTCARD_IT_RXNE);
655     
656     return HAL_OK;
657   }
658   else
659   {
660     return HAL_BUSY; 
661   }
662 }
663
664 /**
665   * @brief Send an amount of data in DMA mode 
666   * @param hsmartcard: SMARTCARD handle
667   * @param pData: pointer to data buffer
668   * @param Size: amount of data to be sent
669   * @retval HAL status
670   */
671 HAL_StatusTypeDef HAL_SMARTCARD_Transmit_DMA(SMARTCARD_HandleTypeDef *hsmartcard, uint8_t *pData, uint16_t Size)
672 {
673   uint32_t *tmp;
674   
675   if ((hsmartcard->State == HAL_SMARTCARD_STATE_READY) || (hsmartcard->State == HAL_SMARTCARD_STATE_BUSY_RX))
676   {
677     if((pData == NULL) || (Size == 0)) 
678     {
679       return HAL_ERROR;                                    
680     }
681     
682     /* Process Locked */
683     __HAL_LOCK(hsmartcard);
684     
685     hsmartcard->pTxBuffPtr = pData;
686     hsmartcard->TxXferSize = Size;
687     hsmartcard->TxXferCount = Size; 
688   
689     hsmartcard->ErrorCode = HAL_SMARTCARD_ERROR_NONE;  
690     /* Check if a receive process is ongoing or not */
691     if(hsmartcard->State == HAL_SMARTCARD_STATE_BUSY_RX) 
692     {
693       hsmartcard->State = HAL_SMARTCARD_STATE_BUSY_TX_RX;
694     }
695     else
696     {
697       hsmartcard->State = HAL_SMARTCARD_STATE_BUSY_TX;
698     }
699     
700     /* Set the SMARTCARD DMA transfer complete callback */
701     hsmartcard->hdmatx->XferCpltCallback = SMARTCARD_DMATransmitCplt;
702     
703     /* Set the SMARTCARD error callback */
704     hsmartcard->hdmatx->XferErrorCallback = SMARTCARD_DMAError;
705
706     /* Enable the SMARTCARD transmit DMA channel */
707     tmp = (uint32_t*)&pData;
708     HAL_DMA_Start_IT(hsmartcard->hdmatx, *(uint32_t*)tmp, (uint32_t)&hsmartcard->Instance->TDR, Size);
709     
710     /* Enable the DMA transfer for transmit request by setting the DMAT bit
711        in the SMARTCARD associated USART CR3 register */
712     hsmartcard->Instance->CR3 |= USART_CR3_DMAT;
713     
714     /* Process Unlocked */
715     __HAL_UNLOCK(hsmartcard);
716     
717     return HAL_OK;
718   }
719   else
720   {
721     return HAL_BUSY;   
722   }
723 }
724
725 /**
726   * @brief Receive an amount of data in DMA mode 
727   * @param hsmartcard: SMARTCARD handle
728   * @param pData: pointer to data buffer
729   * @param Size: amount of data to be received
730   * @note   The SMARTCARD-associated USART parity is enabled (PCE = 1), 
731   *         the received data contain the parity bit (MSB position)   
732   * @retval HAL status
733   */
734 HAL_StatusTypeDef HAL_SMARTCARD_Receive_DMA(SMARTCARD_HandleTypeDef *hsmartcard, uint8_t *pData, uint16_t Size)
735 {
736   uint32_t *tmp;
737   
738   if ((hsmartcard->State == HAL_SMARTCARD_STATE_READY) || (hsmartcard->State == HAL_SMARTCARD_STATE_BUSY_TX))
739   {
740     if((pData == NULL) || (Size == 0)) 
741     {
742       return HAL_ERROR;                                    
743     }
744     
745     /* Process Locked */
746     __HAL_LOCK(hsmartcard);
747     
748     hsmartcard->pRxBuffPtr = pData;
749     hsmartcard->RxXferSize = Size;
750
751     hsmartcard->ErrorCode = HAL_SMARTCARD_ERROR_NONE;
752     /* Check if a transmit rocess is ongoing or not */
753     if(hsmartcard->State == HAL_SMARTCARD_STATE_BUSY_TX) 
754     {
755       hsmartcard->State = HAL_SMARTCARD_STATE_BUSY_TX_RX;
756     }
757     else
758     {
759       hsmartcard->State = HAL_SMARTCARD_STATE_BUSY_RX;
760     }    
761     
762     /* Set the SMARTCARD DMA transfer complete callback */
763     hsmartcard->hdmarx->XferCpltCallback = SMARTCARD_DMAReceiveCplt;
764     
765     /* Set the SMARTCARD DMA error callback */
766     hsmartcard->hdmarx->XferErrorCallback = SMARTCARD_DMAError;
767
768     /* Enable the DMA channel */
769     tmp = (uint32_t*)&pData;
770     HAL_DMA_Start_IT(hsmartcard->hdmarx, (uint32_t)&hsmartcard->Instance->RDR, *(uint32_t*)tmp, Size);
771
772     /* Enable the DMA transfer for the receiver request by setting the DMAR bit 
773        in the SMARTCARD associated USART CR3 register */
774      hsmartcard->Instance->CR3 |= USART_CR3_DMAR;
775     
776      /* Process Unlocked */
777      __HAL_UNLOCK(hsmartcard);
778      
779     return HAL_OK;
780   }
781   else
782   {
783     return HAL_BUSY; 
784   }
785 }
786     
787 /**
788   * @brief SMARTCARD interrupt requests handling.
789   * @param hsmartcard: SMARTCARD handle
790   * @retval None
791   */
792 void HAL_SMARTCARD_IRQHandler(SMARTCARD_HandleTypeDef *hsmartcard)
793 {
794   /* SMARTCARD parity error interrupt occurred -------------------------------------*/
795   if((__HAL_SMARTCARD_GET_IT(hsmartcard, SMARTCARD_IT_PE) != RESET) && (__HAL_SMARTCARD_GET_IT_SOURCE(hsmartcard, SMARTCARD_IT_PE) != RESET))
796   { 
797     __HAL_SMARTCARD_CLEAR_IT(hsmartcard, SMARTCARD_CLEAR_PEF);
798     hsmartcard->ErrorCode |= HAL_SMARTCARD_ERROR_PE;
799     /* Set the SMARTCARD state ready to be able to start again the process */
800     hsmartcard->State = HAL_SMARTCARD_STATE_READY;
801   }
802   
803   /* SMARTCARD frame error interrupt occured --------------------------------------*/
804   if((__HAL_SMARTCARD_GET_IT(hsmartcard, SMARTCARD_IT_FE) != RESET) && (__HAL_SMARTCARD_GET_IT_SOURCE(hsmartcard, SMARTCARD_IT_ERR) != RESET))
805   { 
806     __HAL_SMARTCARD_CLEAR_IT(hsmartcard, SMARTCARD_CLEAR_FEF);
807     hsmartcard->ErrorCode |= HAL_SMARTCARD_ERROR_FE;
808     /* Set the SMARTCARD state ready to be able to start again the process */
809     hsmartcard->State = HAL_SMARTCARD_STATE_READY;
810   }
811   
812   /* SMARTCARD noise error interrupt occured --------------------------------------*/
813   if((__HAL_SMARTCARD_GET_IT(hsmartcard, SMARTCARD_IT_NE) != RESET) && (__HAL_SMARTCARD_GET_IT_SOURCE(hsmartcard, SMARTCARD_IT_ERR) != RESET))
814   { 
815     __HAL_SMARTCARD_CLEAR_IT(hsmartcard, SMARTCARD_CLEAR_NEF);
816     hsmartcard->ErrorCode |= HAL_SMARTCARD_ERROR_NE; 
817     /* Set the SMARTCARD state ready to be able to start again the process */
818     hsmartcard->State = HAL_SMARTCARD_STATE_READY;
819   }
820   
821   /* SMARTCARD Over-Run interrupt occured -----------------------------------------*/
822   if((__HAL_SMARTCARD_GET_IT(hsmartcard, SMARTCARD_IT_ORE) != RESET) && (__HAL_SMARTCARD_GET_IT_SOURCE(hsmartcard, SMARTCARD_IT_ERR) != RESET))
823   { 
824     __HAL_SMARTCARD_CLEAR_IT(hsmartcard, SMARTCARD_CLEAR_OREF);
825     hsmartcard->ErrorCode |= HAL_SMARTCARD_ERROR_ORE; 
826     /* Set the SMARTCARD state ready to be able to start again the process */
827     hsmartcard->State = HAL_SMARTCARD_STATE_READY;
828   }
829   
830   /* SMARTCARD receiver timeout interrupt occured -----------------------------------------*/
831   if((__HAL_SMARTCARD_GET_IT(hsmartcard, SMARTCARD_IT_RTO) != RESET) && (__HAL_SMARTCARD_GET_IT_SOURCE(hsmartcard, SMARTCARD_IT_RTO) != RESET))
832   { 
833     __HAL_SMARTCARD_CLEAR_IT(hsmartcard, SMARTCARD_CLEAR_RTOF);
834     hsmartcard->ErrorCode |= HAL_SMARTCARD_ERROR_RTO; 
835     /* Set the SMARTCARD state ready to be able to start again the process */
836     hsmartcard->State = HAL_SMARTCARD_STATE_READY;
837   }
838
839   /* Call SMARTCARD Error Call back function if need be --------------------------*/
840   if(hsmartcard->ErrorCode != HAL_SMARTCARD_ERROR_NONE)
841   {
842     HAL_SMARTCARD_ErrorCallback(hsmartcard);
843   } 
844   
845   /* SMARTCARD in mode Receiver ---------------------------------------------------*/
846   if((__HAL_SMARTCARD_GET_IT(hsmartcard, SMARTCARD_IT_RXNE) != RESET) && (__HAL_SMARTCARD_GET_IT_SOURCE(hsmartcard, SMARTCARD_IT_RXNE) != RESET))
847   { 
848     SMARTCARD_Receive_IT(hsmartcard);
849     /* Clear RXNE interrupt flag */
850     __HAL_SMARTCARD_SEND_REQ(hsmartcard, SMARTCARD_RXDATA_FLUSH_REQUEST);
851   }
852   
853   /* SMARTCARD in mode Receiver, end of block interruption ------------------------*/
854   if((__HAL_SMARTCARD_GET_IT(hsmartcard, SMARTCARD_IT_EOB) != RESET) && (__HAL_SMARTCARD_GET_IT_SOURCE(hsmartcard, SMARTCARD_IT_EOB) != RESET))
855   { 
856     hsmartcard->State = HAL_SMARTCARD_STATE_READY;
857     __HAL_UNLOCK(hsmartcard);   
858     HAL_SMARTCARD_RxCpltCallback(hsmartcard);
859     /* Clear EOBF interrupt after HAL_SMARTCARD_RxCpltCallback() call for the End of Block information
860      * to be available during HAL_SMARTCARD_RxCpltCallback() processing */
861     __HAL_SMARTCARD_CLEAR_IT(hsmartcard, SMARTCARD_CLEAR_EOBF);
862   }  
863
864   /* SMARTCARD in mode Transmitter ------------------------------------------------*/
865  if((__HAL_SMARTCARD_GET_IT(hsmartcard, SMARTCARD_IT_TXE) != RESET) &&(__HAL_SMARTCARD_GET_IT_SOURCE(hsmartcard, SMARTCARD_IT_TXE) != RESET))
866   {
867     SMARTCARD_Transmit_IT(hsmartcard);
868   } 
869   
870   /* SMARTCARD in mode Transmitter (transmission end) ------------------------*/
871  if((__HAL_SMARTCARD_GET_IT(hsmartcard, SMARTCARD_IT_TC) != RESET) &&(__HAL_SMARTCARD_GET_IT_SOURCE(hsmartcard, SMARTCARD_IT_TC) != RESET))
872   {
873     SMARTCARD_EndTransmit_IT(hsmartcard);
874   } 
875
876
877 /**
878   * @brief Tx Transfer completed callbacks
879   * @param hsmartcard: SMARTCARD handle
880   * @retval None
881   */
882  __weak void HAL_SMARTCARD_TxCpltCallback(SMARTCARD_HandleTypeDef *hsmartcard)
883 {
884   /* NOTE : This function should not be modified, when the callback is needed,
885             the HAL_SMARTCARD_TxCpltCallback can be implemented in the user file
886    */ 
887 }
888
889 /**
890   * @brief Rx Transfer completed callbacks
891   * @param hsmartcard: SMARTCARD handle
892   * @retval None
893   */
894 __weak void HAL_SMARTCARD_RxCpltCallback(SMARTCARD_HandleTypeDef *hsmartcard)
895 {
896   /* NOTE : This function should not be modified, when the callback is needed,
897             the HAL_SMARTCARD_TxCpltCallback can be implemented in the user file
898    */
899 }
900
901 /**
902   * @brief SMARTCARD error callbacks
903   * @param hsmartcard: SMARTCARD handle
904   * @retval None
905   */
906  __weak void HAL_SMARTCARD_ErrorCallback(SMARTCARD_HandleTypeDef *hsmartcard)
907 {
908   /* NOTE : This function should not be modified, when the callback is needed,
909             the HAL_SMARTCARD_ErrorCallback can be implemented in the user file
910    */ 
911 }
912
913 /**
914   * @}
915   */
916  
917 /** @defgroup SMARTCARD_Exported_Functions_Group3 Peripheral State and Errors functions 
918   *  @brief   SMARTCARD State and Errors functions 
919   *
920 @verbatim   
921   ==============================================================================
922                   ##### Peripheral State and Errors functions #####
923   ==============================================================================  
924     [..]
925     This subsection provides a set of functions allowing to return the State of SmartCard
926     communication process and also return Peripheral Errors occurred during communication process
927      (+) HAL_SMARTCARD_GetState() API can be helpful to check in run-time the state of the SMARTCARD peripheral 
928      (+) HAL_SMARTCARD_GetError() check in run-time errors that could be occurred during 
929          communication.     
930      
931      (+) SMARTCARD_SetConfig() API configures the SMARTCARD peripheral 
932      (+) SMARTCARD_AdvFeatureConfig() API optionally configures the SMARTCARD advanced features          
933      (+) SMARTCARD_CheckIdleState() API ensures that TEACK and/or REACK are set after initialization                                
934 @endverbatim
935   * @{
936   */
937
938 /**
939   * @brief return the SMARTCARD state
940   * @param hsmartcard: SMARTCARD handle
941   * @retval HAL state
942   */
943 HAL_SMARTCARD_StateTypeDef HAL_SMARTCARD_GetState(SMARTCARD_HandleTypeDef *hsmartcard)
944 {
945   return hsmartcard->State;
946 }
947
948 /**
949 * @brief  Return the SMARTCARD error code
950 * @param  hsmartcard : pointer to a SMARTCARD_HandleTypeDef structure that contains
951   *              the configuration information for the specified SMARTCARD.
952 * @retval SMARTCARD Error Code
953 */
954 uint32_t HAL_SMARTCARD_GetError(SMARTCARD_HandleTypeDef *hsmartcard)
955 {
956   return hsmartcard->ErrorCode;
957 }
958
959 /**
960   * @}
961   */
962   
963 /**
964   * @}
965   */ 
966
967 /** @defgroup SMARTCARD_Private_Functions   SMARTCARD Private Functions
968   * @{
969   */
970   
971 /**
972   * @brief  This function handles SMARTCARD Communication Timeout.
973   * @param  hsmartcard: SMARTCARD handle
974   * @param  Flag: specifies the SMARTCARD flag to check.
975   * @param  Status: The new Flag status (SET or RESET).
976   * @param  Timeout: Timeout duration
977   * @retval HAL status
978   */
979 static HAL_StatusTypeDef SMARTCARD_WaitOnFlagUntilTimeout(SMARTCARD_HandleTypeDef *hsmartcard, uint32_t Flag, FlagStatus Status, uint32_t Timeout)  
980 {
981   uint32_t tickstart = HAL_GetTick();
982   
983   /* Wait until flag is set */
984   if(Status == RESET)
985   {    
986     while(__HAL_SMARTCARD_GET_FLAG(hsmartcard, Flag) == RESET)
987     {
988       /* Check for the Timeout */
989       if(Timeout != HAL_MAX_DELAY)
990       {    
991         if((Timeout == 0) || ((HAL_GetTick() - tickstart) > Timeout))
992         {
993           /* Disable TXE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts for the interrupt process */
994           __HAL_SMARTCARD_DISABLE_IT(hsmartcard, SMARTCARD_IT_TXE);
995           __HAL_SMARTCARD_DISABLE_IT(hsmartcard, SMARTCARD_IT_RXNE);
996           __HAL_SMARTCARD_DISABLE_IT(hsmartcard, SMARTCARD_IT_PE);
997           __HAL_SMARTCARD_DISABLE_IT(hsmartcard, SMARTCARD_IT_ERR);
998           
999           hsmartcard->State= HAL_SMARTCARD_STATE_READY;
1000           
1001           /* Process Unlocked */
1002           __HAL_UNLOCK(hsmartcard);
1003           
1004           return HAL_TIMEOUT;
1005         }
1006       }
1007     }
1008   }
1009   else
1010   {
1011     while(__HAL_SMARTCARD_GET_FLAG(hsmartcard, Flag) != RESET)
1012     {
1013       /* Check for the Timeout */
1014       if(Timeout != HAL_MAX_DELAY)
1015       {    
1016         if((Timeout == 0) || ((HAL_GetTick() - tickstart) > Timeout))
1017         {
1018           /* Disable TXE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts for the interrupt process */
1019           __HAL_SMARTCARD_DISABLE_IT(hsmartcard, SMARTCARD_IT_TXE);
1020           __HAL_SMARTCARD_DISABLE_IT(hsmartcard, SMARTCARD_IT_RXNE);
1021           __HAL_SMARTCARD_DISABLE_IT(hsmartcard, SMARTCARD_IT_PE);
1022           __HAL_SMARTCARD_DISABLE_IT(hsmartcard, SMARTCARD_IT_ERR);
1023   
1024           hsmartcard->State= HAL_SMARTCARD_STATE_READY;
1025           
1026           /* Process Unlocked */
1027           __HAL_UNLOCK(hsmartcard);
1028           
1029           return HAL_TIMEOUT;
1030         }
1031       }
1032     }
1033   }
1034   return HAL_OK;      
1035 }
1036
1037 /**
1038   * @brief  DMA SMARTCARD transmit process complete callback. 
1039   * @param  hdma: Pointer to a DMA_HandleTypeDef structure that contains
1040   *               the configuration information for the specified DMA module.
1041   * @retval None
1042   */
1043 static void SMARTCARD_DMATransmitCplt(DMA_HandleTypeDef *hdma)     
1044 {
1045   SMARTCARD_HandleTypeDef* hsmartcard = ( SMARTCARD_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
1046   hsmartcard->TxXferCount = 0;
1047   
1048   /* Disable the DMA transfer for transmit request by resetting the DMAT bit
1049   in the SMARTCARD associated USART CR3 register */
1050   hsmartcard->Instance->CR3 &= (uint16_t)~((uint16_t)USART_CR3_DMAT);
1051   
1052   /* Enable the SMARTCARD Transmit Complete Interrupt */    
1053   __HAL_SMARTCARD_ENABLE_IT(hsmartcard, SMARTCARD_IT_TC);
1054 }
1055
1056 /**
1057   * @brief  DMA SMARTCARD receive process complete callback. 
1058   * @param  hdma: Pointer to a DMA_HandleTypeDef structure that contains
1059   *               the configuration information for the specified DMA module.
1060   * @retval None
1061   */
1062 static void SMARTCARD_DMAReceiveCplt(DMA_HandleTypeDef *hdma)  
1063 {
1064   SMARTCARD_HandleTypeDef* hsmartcard = ( SMARTCARD_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
1065   hsmartcard->RxXferCount = 0;
1066   
1067   /* Disable the DMA transfer for the receiver request by resetting the DMAR bit 
1068      in the SMARTCARD associated USART CR3 register */
1069   hsmartcard->Instance->CR3 &= (uint16_t)~((uint16_t)USART_CR3_DMAR);
1070   
1071   /* Check if a transmit Process is ongoing or not */
1072   if(hsmartcard->State == HAL_SMARTCARD_STATE_BUSY_TX_RX) 
1073   {
1074     hsmartcard->State = HAL_SMARTCARD_STATE_BUSY_TX;
1075   }
1076   else
1077   {
1078     hsmartcard->State = HAL_SMARTCARD_STATE_READY;
1079   }
1080   
1081   HAL_SMARTCARD_RxCpltCallback(hsmartcard);
1082 }
1083
1084 /**
1085   * @brief  DMA SMARTCARD communication error callback. 
1086   * @param  hdma: Pointer to a DMA_HandleTypeDef structure that contains
1087   *               the configuration information for the specified DMA module.
1088   * @retval None
1089   */
1090 static void SMARTCARD_DMAError(DMA_HandleTypeDef *hdma)   
1091 {
1092   SMARTCARD_HandleTypeDef* hsmartcard = ( SMARTCARD_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
1093   hsmartcard->RxXferCount = 0;
1094   hsmartcard->TxXferCount = 0;
1095   hsmartcard->State= HAL_SMARTCARD_STATE_READY;
1096   hsmartcard->ErrorCode |= HAL_SMARTCARD_ERROR_DMA;
1097   HAL_SMARTCARD_ErrorCallback(hsmartcard);
1098 }
1099
1100 /**
1101   * @brief Send an amount of data in non blocking mode 
1102   * @param hsmartcard: SMARTCARD handle.
1103   *         Function called under interruption only, once
1104   *         interruptions have been enabled by HAL_SMARTCARD_Transmit_IT()      
1105   * @retval HAL status
1106   */
1107 static HAL_StatusTypeDef SMARTCARD_Transmit_IT(SMARTCARD_HandleTypeDef *hsmartcard)
1108 {
1109   if ((hsmartcard->State == HAL_SMARTCARD_STATE_BUSY_TX) || (hsmartcard->State == HAL_SMARTCARD_STATE_BUSY_TX_RX)) 
1110   {
1111  
1112     if(hsmartcard->TxXferCount == 0)
1113     {
1114       /* Disable the SMARTCARD Transmit Data Register Empty Interrupt */
1115       __HAL_SMARTCARD_DISABLE_IT(hsmartcard, SMARTCARD_IT_TXE);
1116
1117       /* Enable the SMARTCARD Transmit Complete Interrupt */    
1118       __HAL_SMARTCARD_ENABLE_IT(hsmartcard, SMARTCARD_IT_TC);
1119       
1120       return HAL_OK;
1121     }
1122     else
1123     {    
1124       hsmartcard->Instance->TDR = (*hsmartcard->pTxBuffPtr++ & (uint8_t)0xFF);     
1125       hsmartcard->TxXferCount--;
1126   
1127       return HAL_OK;
1128     }
1129   }
1130   else
1131   {
1132     return HAL_BUSY;   
1133   }
1134 }
1135
1136
1137 /**
1138   * @brief  Wraps up transmission in non blocking mode.
1139   * @param  hsmartcard: pointer to a SMARTCARD_HandleTypeDef structure that contains
1140   *                the configuration information for the specified SMARTCARD module.
1141   * @retval HAL status
1142   */
1143 static HAL_StatusTypeDef SMARTCARD_EndTransmit_IT(SMARTCARD_HandleTypeDef *hsmartcard)
1144 {
1145   /* Disable the SMARTCARD Transmit Complete Interrupt */    
1146   __HAL_SMARTCARD_DISABLE_IT(hsmartcard, SMARTCARD_IT_TC);
1147   
1148   /* Check if a receive process is ongoing or not */
1149   if(hsmartcard->State == HAL_SMARTCARD_STATE_BUSY_TX_RX) 
1150   {
1151     hsmartcard->State = HAL_SMARTCARD_STATE_BUSY_RX;
1152   }
1153   else
1154   {
1155     /* Disable the SMARTCARD Error Interrupt: (Frame error, noise error, overrun error) */
1156     __HAL_SMARTCARD_DISABLE_IT(hsmartcard, SMARTCARD_IT_ERR);
1157     
1158     hsmartcard->State = HAL_SMARTCARD_STATE_READY;
1159   }
1160   
1161   HAL_SMARTCARD_TxCpltCallback(hsmartcard);
1162   
1163   return HAL_OK;
1164 }
1165
1166
1167 /**
1168   * @brief Receive an amount of data in non blocking mode 
1169   * @param hsmartcard: SMARTCARD handle.
1170   *         Function called under interruption only, once
1171   *         interruptions have been enabled by HAL_SMARTCARD_Receive_IT()      
1172   * @retval HAL status
1173   */
1174 static HAL_StatusTypeDef SMARTCARD_Receive_IT(SMARTCARD_HandleTypeDef *hsmartcard)
1175 {
1176   if ((hsmartcard->State == HAL_SMARTCARD_STATE_BUSY_RX) || (hsmartcard->State == HAL_SMARTCARD_STATE_BUSY_TX_RX))
1177   {
1178        
1179     *hsmartcard->pRxBuffPtr++ = (uint8_t)(hsmartcard->Instance->RDR & (uint8_t)0xFF);  
1180     
1181     if(--hsmartcard->RxXferCount == 0)
1182     {
1183       __HAL_SMARTCARD_DISABLE_IT(hsmartcard, SMARTCARD_IT_RXNE);
1184       
1185       /* Check if a transmit Process is ongoing or not */
1186       if(hsmartcard->State == HAL_SMARTCARD_STATE_BUSY_TX_RX) 
1187       {
1188         hsmartcard->State = HAL_SMARTCARD_STATE_BUSY_TX;
1189       }
1190       else
1191       {
1192         /* Disable the SMARTCARD Parity Error Interrupt */
1193         __HAL_SMARTCARD_DISABLE_IT(hsmartcard, SMARTCARD_IT_PE);
1194          
1195         /* Disable the SMARTCARD Error Interrupt: (Frame error, noise error, overrun error) */
1196         __HAL_SMARTCARD_DISABLE_IT(hsmartcard, SMARTCARD_IT_ERR);
1197         
1198         hsmartcard->State = HAL_SMARTCARD_STATE_READY;
1199       }
1200       
1201       HAL_SMARTCARD_RxCpltCallback(hsmartcard);
1202       
1203       return HAL_OK;
1204     }
1205     
1206     return HAL_OK;
1207   }
1208   else
1209   {
1210     return HAL_BUSY; 
1211   }
1212 }  
1213    
1214 /**
1215   * @brief Configure the SMARTCARD associated USART peripheral 
1216   * @param hsmartcard: SMARTCARD handle
1217   * @retval None
1218   */
1219 static HAL_StatusTypeDef SMARTCARD_SetConfig(SMARTCARD_HandleTypeDef *hsmartcard)
1220 {
1221   uint32_t tmpreg                          = 0x00000000;
1222   SMARTCARD_ClockSourceTypeDef clocksource = SMARTCARD_CLOCKSOURCE_UNDEFINED;
1223   HAL_StatusTypeDef ret                    = HAL_OK;    
1224   
1225   /* Check the parameters */ 
1226   assert_param(IS_SMARTCARD_INSTANCE(hsmartcard->Instance));
1227   assert_param(IS_SMARTCARD_BAUDRATE(hsmartcard->Init.BaudRate)); 
1228   assert_param(IS_SMARTCARD_WORD_LENGTH(hsmartcard->Init.WordLength));  
1229   assert_param(IS_SMARTCARD_STOPBITS(hsmartcard->Init.StopBits));   
1230   assert_param(IS_SMARTCARD_PARITY(hsmartcard->Init.Parity));
1231   assert_param(IS_SMARTCARD_MODE(hsmartcard->Init.Mode));
1232   assert_param(IS_SMARTCARD_POLARITY(hsmartcard->Init.CLKPolarity));
1233   assert_param(IS_SMARTCARD_PHASE(hsmartcard->Init.CLKPhase));
1234   assert_param(IS_SMARTCARD_LASTBIT(hsmartcard->Init.CLKLastBit));    
1235   assert_param(IS_SMARTCARD_ONEBIT_SAMPLING(hsmartcard->Init.OneBitSampling));
1236   assert_param(IS_SMARTCARD_NACK(hsmartcard->Init.NACKEnable));
1237   assert_param(IS_SMARTCARD_TIMEOUT(hsmartcard->Init.TimeOutEnable));
1238   assert_param(IS_SMARTCARD_AUTORETRY_COUNT(hsmartcard->Init.AutoRetryCount)); 
1239
1240   /*-------------------------- USART CR1 Configuration -----------------------*/
1241   /* In SmartCard mode, M and PCE are forced to 1 (8 bits + parity).
1242    * Oversampling is forced to 16 (OVER8 = 0).
1243    * Configure the Parity and Mode: 
1244    *  set PS bit according to hsmartcard->Init.Parity value
1245    *  set TE and RE bits according to hsmartcard->Init.Mode value */
1246   tmpreg = (uint32_t) hsmartcard->Init.Parity | hsmartcard->Init.Mode;
1247   /* in case of TX-only mode, if NACK is enabled, the USART must be able to monitor 
1248      the bidirectional line to detect a NACK signal in case of parity error. 
1249      Therefore, the receiver block must be enabled as well (RE bit must be set). */
1250   if ((hsmartcard->Init.Mode == SMARTCARD_MODE_TX)
1251    && (hsmartcard->Init.NACKEnable == SMARTCARD_NACK_ENABLED))
1252   {
1253     tmpreg |= USART_CR1_RE;   
1254   }
1255   tmpreg |= (uint32_t) hsmartcard->Init.WordLength;
1256   MODIFY_REG(hsmartcard->Instance->CR1, USART_CR1_FIELDS, tmpreg);
1257
1258   /*-------------------------- USART CR2 Configuration -----------------------*/
1259   /* Stop bits are forced to 1.5 (STOP = 11) */
1260   tmpreg = hsmartcard->Init.StopBits;
1261   /* Synchronous mode is activated by default */
1262   tmpreg |= (uint32_t) USART_CR2_CLKEN | hsmartcard->Init.CLKPolarity; 
1263   tmpreg |= (uint32_t) hsmartcard->Init.CLKPhase | hsmartcard->Init.CLKLastBit;
1264   tmpreg |= (uint32_t) hsmartcard->Init.TimeOutEnable;
1265   MODIFY_REG(hsmartcard->Instance->CR2, USART_CR2_FIELDS, tmpreg); 
1266     
1267   /*-------------------------- USART CR3 Configuration -----------------------*/    
1268   /* Configure 
1269    * - one-bit sampling method versus three samples' majority rule 
1270    *   according to hsmartcard->Init.OneBitSampling 
1271    * - NACK transmission in case of parity error according 
1272    *   to hsmartcard->Init.NACKEnable   
1273    * - autoretry counter according to hsmartcard->Init.AutoRetryCount     */
1274   tmpreg =  (uint32_t) hsmartcard->Init.OneBitSampling | hsmartcard->Init.NACKEnable;
1275   tmpreg |= ((uint32_t)hsmartcard->Init.AutoRetryCount << SMARTCARD_CR3_SCARCNT_LSB_POS);
1276   MODIFY_REG(hsmartcard->Instance-> CR3,USART_CR3_FIELDS, tmpreg);
1277   
1278   /*-------------------------- USART GTPR Configuration ----------------------*/
1279   tmpreg = (hsmartcard->Init.Prescaler | ((uint32_t)hsmartcard->Init.GuardTime << SMARTCARD_GTPR_GT_LSB_POS));
1280   MODIFY_REG(hsmartcard->Instance->GTPR, (USART_GTPR_GT|USART_GTPR_PSC), tmpreg); 
1281   
1282   /*-------------------------- USART RTOR Configuration ----------------------*/ 
1283   tmpreg = ((uint32_t)hsmartcard->Init.BlockLength << SMARTCARD_RTOR_BLEN_LSB_POS);
1284   if (hsmartcard->Init.TimeOutEnable == SMARTCARD_TIMEOUT_ENABLED)
1285   {
1286     assert_param(IS_SMARTCARD_TIMEOUT_VALUE(hsmartcard->Init.TimeOutValue));
1287     tmpreg |=  (uint32_t) hsmartcard->Init.TimeOutValue;
1288   }
1289   MODIFY_REG(hsmartcard->Instance->RTOR, (USART_RTOR_RTO|USART_RTOR_BLEN), tmpreg);
1290   
1291   /*-------------------------- USART BRR Configuration -----------------------*/  
1292   __HAL_SMARTCARD_GETCLOCKSOURCE(hsmartcard, clocksource);
1293   switch (clocksource)
1294   {
1295     case SMARTCARD_CLOCKSOURCE_PCLK1: 
1296       hsmartcard->Instance->BRR = (uint16_t)(HAL_RCC_GetPCLK1Freq() / hsmartcard->Init.BaudRate);
1297       break;
1298     case SMARTCARD_CLOCKSOURCE_HSI: 
1299       hsmartcard->Instance->BRR = (uint16_t)(HSI_VALUE / hsmartcard->Init.BaudRate); 
1300       break; 
1301     case SMARTCARD_CLOCKSOURCE_SYSCLK:  
1302       hsmartcard->Instance->BRR = (uint16_t)(HAL_RCC_GetSysClockFreq() / hsmartcard->Init.BaudRate);
1303       break;  
1304     case SMARTCARD_CLOCKSOURCE_LSE:                
1305       hsmartcard->Instance->BRR = (uint16_t)(LSE_VALUE / hsmartcard->Init.BaudRate); 
1306       break;
1307     case SMARTCARD_CLOCKSOURCE_UNDEFINED: 
1308     default:               
1309       ret = HAL_ERROR; 
1310       break;             
1311   }
1312   
1313   return ret;  
1314 }
1315   
1316 /**
1317   * @brief Check the SMARTCARD Idle State
1318   * @param hsmartcard: SMARTCARD handle
1319   * @retval HAL status
1320   */
1321 static HAL_StatusTypeDef SMARTCARD_CheckIdleState(SMARTCARD_HandleTypeDef *hsmartcard)
1322 {
1323   
1324   /* Initialize the SMARTCARD ErrorCode */
1325   hsmartcard->ErrorCode = HAL_SMARTCARD_ERROR_NONE;
1326
1327   /* Check if the Transmitter is enabled */
1328   if((hsmartcard->Instance->CR1 & USART_CR1_TE) == USART_CR1_TE)
1329   {
1330     /* Wait until TEACK flag is set */
1331     if(SMARTCARD_WaitOnFlagUntilTimeout(hsmartcard, USART_ISR_TEACK, RESET, TEACK_REACK_TIMEOUT) != HAL_OK)  
1332     { 
1333       return HAL_TIMEOUT;
1334     } 
1335   }
1336   /* Check if the Receiver is enabled */
1337   if((hsmartcard->Instance->CR1 & USART_CR1_RE) == USART_CR1_RE)
1338   {
1339     /* Wait until REACK flag is set */
1340     if(SMARTCARD_WaitOnFlagUntilTimeout(hsmartcard, USART_ISR_REACK, RESET, TEACK_REACK_TIMEOUT) != HAL_OK)  
1341     { 
1342       return HAL_TIMEOUT;
1343     }
1344   }
1345   
1346   /* Initialize the SMARTCARD state*/
1347   hsmartcard->State= HAL_SMARTCARD_STATE_READY;
1348   
1349   /* Process Unlocked */
1350   __HAL_UNLOCK(hsmartcard);
1351   
1352   return HAL_OK;
1353 }
1354     
1355 /**
1356   * @brief Configure the SMARTCARD associated USART peripheral advanced feautures 
1357   * @param hsmartcard: SMARTCARD handle  
1358   * @retval None
1359   */
1360 static void SMARTCARD_AdvFeatureConfig(SMARTCARD_HandleTypeDef *hsmartcard)
1361 {  
1362   /* Check whether the set of advanced features to configure is properly set */ 
1363   assert_param(IS_SMARTCARD_ADVFEATURE_INIT(hsmartcard->AdvancedInit.AdvFeatureInit));
1364   
1365   /* if required, configure TX pin active level inversion */
1366   if (HAL_IS_BIT_SET(hsmartcard->AdvancedInit.AdvFeatureInit, SMARTCARD_ADVFEATURE_TXINVERT_INIT))
1367   {
1368     assert_param(IS_SMARTCARD_ADVFEATURE_TXINV(hsmartcard->AdvancedInit.TxPinLevelInvert));
1369     MODIFY_REG(hsmartcard->Instance->CR2, USART_CR2_TXINV, hsmartcard->AdvancedInit.TxPinLevelInvert);
1370   }
1371   
1372   /* if required, configure RX pin active level inversion */
1373   if (HAL_IS_BIT_SET(hsmartcard->AdvancedInit.AdvFeatureInit, SMARTCARD_ADVFEATURE_RXINVERT_INIT))
1374   {
1375     assert_param(IS_SMARTCARD_ADVFEATURE_RXINV(hsmartcard->AdvancedInit.RxPinLevelInvert));
1376     MODIFY_REG(hsmartcard->Instance->CR2, USART_CR2_RXINV, hsmartcard->AdvancedInit.RxPinLevelInvert);
1377   }
1378   
1379   /* if required, configure data inversion */
1380   if (HAL_IS_BIT_SET(hsmartcard->AdvancedInit.AdvFeatureInit, SMARTCARD_ADVFEATURE_DATAINVERT_INIT))
1381   {
1382     assert_param(IS_SMARTCARD_ADVFEATURE_DATAINV(hsmartcard->AdvancedInit.DataInvert));
1383     MODIFY_REG(hsmartcard->Instance->CR2, USART_CR2_DATAINV, hsmartcard->AdvancedInit.DataInvert);
1384   }
1385   
1386   /* if required, configure RX/TX pins swap */
1387   if (HAL_IS_BIT_SET(hsmartcard->AdvancedInit.AdvFeatureInit, SMARTCARD_ADVFEATURE_SWAP_INIT))
1388   {
1389     assert_param(IS_SMARTCARD_ADVFEATURE_SWAP(hsmartcard->AdvancedInit.Swap));
1390     MODIFY_REG(hsmartcard->Instance->CR2, USART_CR2_SWAP, hsmartcard->AdvancedInit.Swap);
1391   }
1392   
1393   /* if required, configure RX overrun detection disabling */
1394   if (HAL_IS_BIT_SET(hsmartcard->AdvancedInit.AdvFeatureInit, SMARTCARD_ADVFEATURE_RXOVERRUNDISABLE_INIT))
1395   {
1396     assert_param(IS_SMARTCARD_OVERRUN(hsmartcard->AdvancedInit.OverrunDisable));  
1397     MODIFY_REG(hsmartcard->Instance->CR3, USART_CR3_OVRDIS, hsmartcard->AdvancedInit.OverrunDisable);
1398   }
1399   
1400   /* if required, configure DMA disabling on reception error */
1401   if (HAL_IS_BIT_SET(hsmartcard->AdvancedInit.AdvFeatureInit, SMARTCARD_ADVFEATURE_DMADISABLEONERROR_INIT))
1402   {
1403     assert_param(IS_SMARTCARD_ADVFEATURE_DMAONRXERROR(hsmartcard->AdvancedInit.DMADisableonRxError));   
1404     MODIFY_REG(hsmartcard->Instance->CR3, USART_CR3_DDRE, hsmartcard->AdvancedInit.DMADisableonRxError);
1405   }
1406   
1407   /* if required, configure MSB first on communication line */  
1408   if (HAL_IS_BIT_SET(hsmartcard->AdvancedInit.AdvFeatureInit, SMARTCARD_ADVFEATURE_MSBFIRST_INIT))
1409   {
1410     assert_param(IS_SMARTCARD_ADVFEATURE_MSBFIRST(hsmartcard->AdvancedInit.MSBFirst));   
1411     MODIFY_REG(hsmartcard->Instance->CR2, USART_CR2_MSBFIRST, hsmartcard->AdvancedInit.MSBFirst);
1412   } 
1413 }
1414
1415 /**
1416   * @}
1417   */
1418
1419 /**
1420   * @}
1421   */
1422
1423 /**
1424   * @}
1425   */
1426
1427 #endif /* !defined(STM32F030x6) && !defined(STM32F030x8)&& !defined(STM32F070x6) && !defined(STM32F070xB) && !defined(STM32F030xC) */    
1428
1429 #endif /* HAL_SMARTCARD_MODULE_ENABLED */
1430
1431 /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/