/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file : main.c
* @brief : Main program body
******************************************************************************
* @attention
*
* Copyright (c) 2025 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "stdio.h"
#include "rc522.h"
#include "string.h"
/* USER CODE END Includes */
/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
uint8_t readCard(uint8_t *readUid,void(*funCallBack)(void))
{
uint8_t Temp[5];
if (PCD_Request(0x52, Temp) == 0)
{
if (PCD_Anticoll(readUid) == 0)
{
if(funCallBack!=NULL)
funCallBack();
return 0;
}
}
return 1;
}
/* USER CODE END PTD */
/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */
/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */
/* USER CODE END PM */
/* Private variables ---------------------------------------------------------*/
SPI_HandleTypeDef hspi2;
UART_HandleTypeDef huart1;
/* USER CODE BEGIN PV */
// ? ?
int fputc(int ch,FILE *f){
uint8_t temp[1]={ch};
HAL_UART_Transmit(&huart1,temp,1,2);
return ch;
}
/* USER CODE END PV */
/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_SPI2_Init(void);
static void MX_USART1_UART_Init(void);
/* USER CODE BEGIN PFP */
/* USER CODE END PFP */
/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
/* USER CODE END 0 */
/**
* @brief The application entry point.
* @retval int
*/
int main(void)
{
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/* MCU Configuration--------------------------------------------------------*/
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* USER CODE BEGIN Init */
/* USER CODE END Init */
/* Configure the system clock */
SystemClock_Config();
/* USER CODE BEGIN SysInit */
/* USER CODE END SysInit */
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_SPI2_Init();
MX_USART1_UART_Init();
/* USER CODE BEGIN 2 */
uint8_t readUid[5];
PCD_Init();
PCD_Reset();
printf("RC522初始化完成\n");
uint8_t card_type[2] = {0}; // 存储卡类型
uint8_t card_sn[4] = {0}; // 存储4字节卡号
char status;
uint8_t block_data[16] = {0}; // 存储读取的16字节数据
uint8_t target_block = 63; // 要读取的目标块(扇区0的块1,可修改为0~63)
// 标记是否已打印当前卡号和数据,避免重复输出
uint8_t card_printed = 0;
uint8_t last_card_sn[4] = {0};
// 定义默认密码(Mifare S50默认A密码)
uint8_t default_keyA[6] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
HAL_Delay(120);
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
// if(!readCard(readUid,NULL)){
// printf("%x-%x-%x-%x\r\n",readUid[0],readUid[1],readUid[2],readUid[3]);
// }
// 检测并复位SPI2错误(新增:解决SPI通讯异常)
if(__HAL_SPI_GET_FLAG(&hspi2, SPI_FLAG_OVR | SPI_FLAG_MODF | SPI_FLAG_CRCERR))
{
//__HAL_SPI_CLEAR_FLAG(&hspi2, SPI_FLAG_OVR | SPI_FLAG_MODF | SPI_FLAG_CRCERR);
HAL_SPI_Abort(&hspi2);
}
// 1. 寻卡(寻所有卡)
status = PCD_Request(PICC_REQALL, card_type);
if (status == PCD_OK)
{
// 仅首次检测到卡片/换卡时打印,避免重复输出
if (memcmp(card_sn, last_card_sn, 4) != 0 || card_printed == 0)
{
printf("寻卡成功,卡类型:0x%02X%02X\r\n", card_type[0], card_type[1]);
// 2. 防冲突获取卡号
status = PCD_Anticoll(card_sn);
if (status == PCD_OK)
{
// 更新上一次的卡号
memcpy(last_card_sn, card_sn, 4);
// 打印4字节卡号
printf("卡号:0x%02X%02X%02X%02X\r\n", card_sn[0], card_sn[1], card_sn[2], card_sn[3]);
// 3. 选卡(增加重试机制,最多3次)
uint8_t select_retry = 0;
uint8_t select_status = PCD_ERR;
while (select_retry < 3 && select_status != PCD_OK)
{
HAL_Delay(10);
select_status = PCD_Select(card_sn);
select_retry++;
}
if (select_status == PCD_OK)
{
printf("选卡成功(重试%d次)\r\n", select_retry-1);
// 4. 验证A密码(读取数据块前必须验证对应扇区的密码)
status = PCD_AuthState(PICC_AUTHENT1A, target_block, default_keyA, card_sn);
if (status == PCD_OK)
{
printf("密码验证成功\r\n");
// 5. 读取指定数据块
status = PCD_ReadBlock(target_block, block_data);
if (status == PCD_OK)
{
// 打印读取到的数据
printf("读取块%d数据成功:\r\n", target_block);
printf("十六进制:");
for (int i = 0; i < 16; i++)
{
printf("%02X ", block_data[i]);
if ((i+1) % 8 == 0) printf("\r\n "); // 每8个字节换行,排版更清晰
}
printf("\r\nASCII字符:");
for (int i = 0; i < 16; i++)
{
// 只显示可打印ASCII字符(0x20~0x7E),否则显示'.'
printf("%c", (block_data[i] >= 0x20 && block_data[i] <= 0x7E) ? block_data[i] : '.');
}
printf("\r\n=====================\r\n");
}
else
{
printf("读取块%d数据失败!\r\n", target_block);
}
}
else
{
printf("密码验证失败!(确认扇区A密码是否为默认0xFFFFFF)\r\n");
}
}
else
{
printf("选卡失败(已重试3次)!\r\n");
}
// 标记已打印,避免重复输出
card_printed = 1;
// 命令卡片休眠,减少重复检测
PCD_Halt();
}
else
{
printf("防冲突失败\r\n");
card_printed = 0;
memset(last_card_sn, 0, 4);
}
}
}
else
{
// 无卡时重置标记
card_printed = 0;
memset(last_card_sn, 0, 4);
}
HAL_Delay(500); // 500ms? ?
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
}
/* USER CODE END 3 */
}
/**
* @brief System Clock Configuration
* @retval None
*/
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
/** Initializes the RCC Oscillators according to the specified parameters
* in the RCC_OscInitTypeDef structure.
*/
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
RCC_OscInitStruct.HSEState = RCC_HSE_ON;
RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
RCC_OscInitStruct.HSIState = RCC_HSI_ON;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
{
Error_Handler();
}
/** Initializes the CPU, AHB and APB buses clocks
*/
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
|RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
{
Error_Handler();
}
}
/**
* @brief SPI2 Initialization Function
* @param None
* @retval None
*/
static void MX_SPI2_Init(void)
{
/* USER CODE BEGIN SPI2_Init 0 */
/* USER CODE END SPI2_Init 0 */
/* USER CODE BEGIN SPI2_Init 1 */
/* USER CODE END SPI2_Init 1 */
/* SPI2 parameter configuration*/
hspi2.Instance = SPI2;
hspi2.Init.Mode = SPI_MODE_MASTER;
hspi2.Init.Direction = SPI_DIRECTION_2LINES;
hspi2.Init.DataSize = SPI_DATASIZE_8BIT;
hspi2.Init.CLKPolarity = SPI_POLARITY_LOW;
hspi2.Init.CLKPhase = SPI_PHASE_1EDGE;
hspi2.Init.NSS = SPI_NSS_SOFT;
hspi2.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_64;
hspi2.Init.FirstBit = SPI_FIRSTBIT_MSB;
hspi2.Init.TIMode = SPI_TIMODE_DISABLE;
hspi2.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;
hspi2.Init.CRCPolynomial = 10;
if (HAL_SPI_Init(&hspi2) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN SPI2_Init 2 */
/* USER CODE END SPI2_Init 2 */
}
/**
* @brief USART1 Initialization Function
* @param None
* @retval None
*/
static void MX_USART1_UART_Init(void)
{
/* USER CODE BEGIN USART1_Init 0 */
/* USER CODE END USART1_Init 0 */
/* USER CODE BEGIN USART1_Init 1 */
/* USER CODE END USART1_Init 1 */
huart1.Instance = USART1;
huart1.Init.BaudRate = 115200;
huart1.Init.WordLength = UART_WORDLENGTH_8B;
huart1.Init.StopBits = UART_STOPBITS_1;
huart1.Init.Parity = UART_PARITY_NONE;
huart1.Init.Mode = UART_MODE_TX_RX;
huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart1.Init.OverSampling = UART_OVERSAMPLING_16;
if (HAL_UART_Init(&huart1) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN USART1_Init 2 */
/* USER CODE END USART1_Init 2 */
}
/**
* @brief GPIO Initialization Function
* @param None
* @retval None
*/
static void MX_GPIO_Init(void)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
/* USER CODE BEGIN MX_GPIO_Init_1 */
/* USER CODE END MX_GPIO_Init_1 */
/* GPIO Ports Clock Enable */
__HAL_RCC_GPIOD_CLK_ENABLE();
__HAL_RCC_GPIOB_CLK_ENABLE();
__HAL_RCC_GPIOA_CLK_ENABLE();
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(GPIOB, RC522_RST_Pin|RC522_CS_Pin, GPIO_PIN_SET);
/*Configure GPIO pins : RC522_RST_Pin RC522_CS_Pin */
GPIO_InitStruct.Pin = RC522_RST_Pin|RC522_CS_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_PULLUP;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
/* USER CODE BEGIN MX_GPIO_Init_2 */
/* USER CODE END MX_GPIO_Init_2 */
}
/* USER CODE BEGIN 4 */
/* USER CODE END 4 */
/**
* @brief This function is executed in case of error occurrence.
* @retval None
*/
void Error_Handler(void)
{
/* USER CODE BEGIN Error_Handler_Debug */
/* User can add his own implementation to report the HAL error return state */
__disable_irq();
while (1)
{
}
/* USER CODE END Error_Handler_Debug */
}
#ifdef USE_FULL_ASSERT
/**
* @brief Reports the name of the source file and the source line number
* where the assert_param error has occurred.
* @param file: pointer to the source file name
* @param line: assert_param error line source number
* @retval None
*/
void assert_failed(uint8_t *file, uint32_t line)
{
/* USER CODE BEGIN 6 */
/* User can add his own implementation to report the file name and line number,
ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
/* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */