使用的是STM32F042的板子,先配置好虚拟串口(VCP),可按次教程配置:https://www.smilefrog.net/eefrog/?p=259
修改主函数如下:
/* USER CODE BEGIN WHILE */ char *buff = "\n"; //换行符 char *buff1 = "UID = "; //特定字符 char UID0[8] = ""; //UID缓存 char UID1[8] = ""; char UID2[8] = ""; while (1) { if (HAL_GPIO_ReadPin(KEY_GPIO_Port, KEY_Pin) == GPIO_PIN_SET) //检测按键是否按下 { HAL_GPIO_WritePin(LED_GPIO_Port, LED_Pin, GPIO_PIN_SET); //亮灯提示 sprintf(UID0, "%08X", HAL_GetUIDw0()); //获取ID转成16进制存到UID缓存 sprintf(UID1, "%08X", HAL_GetUIDw1()); sprintf(UID2, "%08X", HAL_GetUIDw2()); while (CDC_Transmit_FS((uint8_t*)buff1, 6)); //输出特定字符 while (CDC_Transmit_FS((uint8_t*)UID0, sizeof(UID0))); //输出UID while (CDC_Transmit_FS((uint8_t*)UID1, sizeof(UID1))); while (CDC_Transmit_FS((uint8_t*)UID2, sizeof(UID2))); while (CDC_Transmit_FS((uint8_t*)buff, 1)); //换行 while (HAL_GPIO_ReadPin(KEY_GPIO_Port, KEY_Pin) == GPIO_PIN_SET); //等待松开按键 } HAL_GPIO_WritePin(LED_GPIO_Port, LED_Pin, GPIO_PIN_RESET); //灭灯 /* USER CODE END WHILE */ }
下载运行程序后,打开电脑串口,按下板子上的PB8按键,在串口监视器中便能看到uid了。