AT32 USART — 智能卡模式

AT32 AT32F403A_407_Firmware_Library V2.2.2 USART 智能卡模式 示例教学

USART — 智能卡模式

固件库: AT32F403A_407_Firmware_Library V2.2.2
芯片: AT32
源文件: AT32/AT32F403A_407_Firmware_Library_V2.2.2/project/at_start_f403a/examples/usart/smartcard/src/main.c


功能简介

本示例演示 USART 串口通信。串口是最基本的通信接口,几乎每个嵌入式项目都会用到。

硬件准备

  • USB 转串口模块(如 CH340、CP2102)
  • 连接:开发板 TX → 模块 RX,开发板 RX → 模块 TX,共地
  • 电脑端打开串口助手(如 SSCOM、XCOM),波特率与代码一致

完整代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include "at32f403a_407_board.h"
#include "at32f403a_407_clock.h"
#include "smartcard_config.h"
#define T0_PROTOCOL                      0x00  /* t0 protocol */
#define SETUP_LENGTH                     20
#define HIST_LENGTH                      20
#define SC_RECEIVE_TIMEOUT               0xA000  /* direction to reader */
#define SC_USART_DIV_VAL                 20      /* ISO 7816-3 protocol: SC_CLOCK_FREQ(PCLK/(2*USART_DIV_VAL)) is between 1 and 5 MHz */
#define SC_F_DIV_D                       372     /* ISO 7816-3 protocol: F/D = 372 */
typedef struct

int main(void)
{
  uint32_t index = 0;
  system_clock_config();
  at32_board_init();
  usart_configuration();

  /* loop while no smartcard is detected */
  while(card_inserted == 0)
  {
  }

  /* read smartcard atr response */
  for(index = 0; index < 40; index++, counter = 0)
  {
    while((usart_flag_get(SC_USART, USART_RDBF_FLAG) == RESET) && (counter != SC_RECEIVE_TIMEOUT))
    {
      counter++;
    }

    if(counter != SC_RECEIVE_TIMEOUT)
    {
      dst_buffer[index] = usart_data_receive(SC_USART);
    }
  }

  /* decode atr */
  card_protocol = sc_response_decode(dst_buffer);

  /* test if the inserted card is iso7816-3 t=0 compatible */
  if(card_protocol == 0)
  {
    /* inserted card is iso7816-3 t=0 compatible */
    atr_decode_status = SUCCESS;
  }
  else
  {
    /* inserted smartcard is not iso7816-3 t=0 compatible */
    atr_decode_status = ERROR;
  }

  /* judge whether the result is correct */
  if(atr_decode_status == SUCCESS)
  {
    /* trun on the led */
    at32_led_on(LED2);
    at32_led_on(LED3);
    at32_led_on(LED4);
  }

  while(1)
  {
  }
}

代码讲解

系统时钟初始化:配置 MCU 的主频和时钟树。不同芯片的时钟配置不同,一般由工具生成。

板级初始化:初始化开发板上的 LED、按键等基础外设。

实验现象

  • 串口助手收到开发板发送的数据
  • 发送数据后开发板原样返回(回显)

注意事项

  • 串口助手波特率必须与代码一致
  • 检查 TX/RX 是否交叉连接
  • 共地是必须的
世界是你们
使用 Hugo 构建
主题 StackJimmy 设计