目录

概述

一、使用方法

二、STM32CubeMx配置

三、Examples

四、运行结果

五、总结


概述

        本篇文章介绍如何使用STM32HAL库,来读取 UID唯一码示例

硬件:STM32F103CBT6最小系统板
软件:Keil 5.29  + STM32CubeMX6.01
 

一、使用方法

         STM32通过读取芯片唯一ID号来实现程序的保护,防止被抄袭。按照用户不同的用法,可以以字节(8位)为单位读取,也可以以半字(16位)或者全字(32位)读取。在这里要提醒读者,要注意大端小端模式。
通过 datasheet(STM32用户指南)来了解,打开书签,找到跟 ID有关的,终于找到了“Unique device ID register (96 bits)”,那就是它了,错不了。


通过阅读datasheet,初步了解到,想获取 Device ID,只需要从这个地址“0x1FFF F7E8”开始12字节96bit,读取即可。


二、STM32CubeMx配置

三、Examples

1、使用STM32CubeMX生成keil IDE工程。

2、在工程目录下新建BSP文件夹,同时新建的bsp_cpu_id.c 与 bsp_cpu_id.h 这两文件

3、在keil IDE中新建 UID文件夹,把刚刚新建的bsp_cpu_id.c 与 bsp_cpu_id.h 这两文件添加进来即可,如下所示

4、添加头文件路径

5、bsp_cpu_id.c文件

#include "bsp_cpu_id.h"
#include "stdio.h"


uint32_t CPU_ID[3];

uint8_t UID[12];
uint8_t MAC[12];


/*定义STM32 MCU的类型*/
typedef enum {
    STM32F0_ = 0,
    STM32F1_ = 1,
	  STM32F2_,
    STM32F3_,
    STM32F4_,
    STM32F7_,
    STM32L0_,
    STM32L1_,
    STM32L4_,
    STM32H7_,
}MCUTypedef;


uint32_t ID_Addr_Table[]={
      [STM32F0_] = 0x1FFFF7AC,  /*STM32F0唯一ID起始地址*/
			[STM32F1_] = 0x1FFFF7E8,  /*STM32F1唯一ID起始地址*/
			[STM32F2_] = 0x1FFF7A10,  /*STM32F2唯一ID起始地址*/
			[STM32F3_] = 0x1FFFF7AC,  /*STM32F3唯一ID起始地址*/
			[STM32F4_] = 0x1FFF7A10,  /*STM32F4唯一ID起始地址*/
			[STM32F7_] = 0x1FF0F420,  /*STM32F7唯一ID起始地址*/
			[STM32L0_] = 0x1FF80050,  /*STM32L0唯一ID起始地址*/
			[STM32L1_] = 0x1FF80050,  /*STM32L1唯一ID起始地址*/
			[STM32L4_] = 0x1FFF7590,  /*STM32L4唯一ID起始地址*/
			[STM32H7_] = 0x1FF0F420}; /*STM32H7唯一ID起始地址*/
 

/**
  * 函数功能: 获取芯片ID
  * 输入参数: MCUTypedef type
  * 返 回 值: 无
  * 说    明:每个芯片都有唯一的 96_bit unique ID  
  */
void Get_ChipID2(void)
{
	 uint32_t id[3] = {0};
	 
//	 const static int Device_ID_Order[] =
//	 {
//			STM32F0_, STM32F1_, STM32F2_, STM32F3_, STM32F4_,  
//			STM32F7_, STM32L0_, STM32L1_, STM32L4_, STM32H7_
//	 };
	 
	 uint8_t size = sizeof(ID_Addr_Table)/sizeof(ID_Addr_Table[0]);
	 //printf("\r\n size: %d\r\n", size);
	 for(uint8_t i = 0; i < size; i++)
	 {
			if(ID_Addr_Table[i] == UID_BASE)
			{
				 id[0]=*(uint32_t*)(ID_Addr_Table[i]);
				 id[1]=*(uint32_t*)(ID_Addr_Table[i]+4);
				 id[2]=*(uint32_t*)(ID_Addr_Table[i]+8);
				 printf("\r\n芯片的唯一ID为: %08X-%08X-%08X\r\n",id[0],id[1],id[2]);
			}
	 }	
}


/**
  * 函数功能: 获取MCU系列ID HAL库封装好的API
  * 输入参数: 无
  * 返 回 值: 无
  * 说    明:每个芯片都有唯一的 96_bit unique ID  
  */
void getSTM32SeriesID(void)
{
	uint32_t UIDw[3];
  uint32_t HalVersion  = HAL_GetHalVersion();
  uint32_t REVID       = HAL_GetREVID();
  uint32_t DEVID       = HAL_GetDEVID();
  UIDw[0]              = HAL_GetUIDw0();
  UIDw[1]              = HAL_GetUIDw1();
  UIDw[2]              = HAL_GetUIDw2();
	printf("\r\n芯片的HAL库版本号为: %d\r\n",HalVersion);
	printf("\r\n芯片修订标识符为: %d\r\n",REVID);
	printf("\r\n芯片标识符为: %d\r\n",DEVID);
	printf("\r\n芯片的唯一ID为: %08X-%08X-%08X\r\n",UIDw[0],UIDw[1],UIDw[2]);
}


/**
  * 函数功能: 获取芯片ID
  * 输入参数: 无
  * 返 回 值: 无
  * 说    明:每个芯片都有唯一的 96_bit unique ID  
  */
void Get_ChipID(void)
{
	CPU_ID[0] = *(__IO uint32_t *)(0X1FFFF7F0); // 高字节
	CPU_ID[1] = *(__IO uint32_t *)(0X1FFFF7EC); // 
	CPU_ID[2] = *(__IO uint32_t *)(0X1FFFF7E8); // 低字节
	
	/* 芯片的唯一ID */
	printf("\r\n芯片的唯一ID为: %08X-%08X-%08X\r\n",CPU_ID[0],CPU_ID[1],CPU_ID[2]);
}

/**
  * 函数功能: 获取芯片ID
  * 输入参数: 无
  * 返 回 值: 无
  * 说    明:每个芯片都有唯一的 96_bit unique ID  
  */
void Get_UID(void)
{
	uint8_t i = 0;
	//用芯片唯一ID来做模块的MAC F0系列 0x1FFFF7AC  F1系列 0x1FFFF7E8
	for(i=0; i<8; i++)
	{
		MAC[i] = *(uint8_t *)(0x1FFFF7E8 + i);
		UID[i] = MAC[i];
	}
	UID[8]  = *(uint8_t *)(0x1FFFF7E8 + 8);
	UID[9]  = *(uint8_t *)(0x1FFFF7E8 + 9);
	UID[10] = *(uint8_t *)(0x1FFFF7E8 + 10);
	UID[11] = *(uint8_t *)(0x1FFFF7E8 + 11);
	
	MAC[4] += UID[8];
	MAC[5] += UID[9];
	MAC[6] += UID[10];
	MAC[7] += UID[11];
	
	/* 芯片的唯一ID */
	printf("\r\n UID: %0.2X-%0.2X-%0.2X-%0.2X\r\n",UID[8],UID[9],UID[10],UID[11]);
	printf("\r\n MAC: %X-%X-%X-%X\r\n",MAC[4],MAC[5],MAC[6],MAC[7]);
}

/**
  * 函数功能: 获取芯片ID
  * 输入参数: 无
  * 返 回 值: 无
  * 说    明:每个芯片都有唯一的 96_bit unique ID  
  */
void Get_UID2(void)
{
	uint8_t i = 0;
	//用芯片唯一ID来做模块的MAC F0系列 0x1FFFF7AC  F1系列 0x1FFFF7E8
	for(i=0; i<12; i++)
	{
		MAC[i] = *(uint8_t *)(0x1FFFF7E8 + i);
		printf(" %0.2X", MAC[i]);
	}
	
	//芯片的唯一ID为: 30 FF 69 06 4D 50 35 35 39 25 08 43
	if(MAC[0] == 0x30 && MAC[1] == 0xFF && MAC[2] == 0x69 &&
		 MAC[3] == 0x06 && MAC[4] == 0x4D && MAC[5] == 0x50 &&
	   MAC[6] == 0x35 && MAC[7] == 0x35 && MAC[8] == 0x39 &&
	   MAC[9] == 0x25 && MAC[10] == 0x08 && MAC[11] == 0x43
		)
	{
		printf("\r\n pass ok \r\n");
	}
	else
	{
		printf("\r\n error \r\n");
	}
}

void test(void)
{

	Get_ChipID();
	
	Get_ChipID2();
	
	getSTM32SeriesID();
	
	Get_UID();
	Get_UID2();
	
	/* 芯片的容量 */
	printf("\r\n芯片flash的容量为: %dK \r\n", *(__IO uint16_t *)(0X1FFFF7E0));
}





6、bsp_cpu_id.h文件

#ifndef __CHIPID_H
#define	__CHIPID_H


#include "stm32f1xx_hal.h"


void test(void);

#endif /* __CHIPID_H */




7、main.c文件

/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; Copyright (c) 2021 STMicroelectronics.
  * All rights reserved.</center></h2>
  *
  * This software component is licensed by ST under BSD 3-Clause license,
  * the "License"; You may not use this file except in compliance with the
  * License. You may obtain a copy of the License at:
  *                        opensource.org/licenses/BSD-3-Clause
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "stdio.h"
#include "bsp_cpu_id.h"
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* 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 ---------------------------------------------------------*/

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

#ifdef __GNUC__
  /* With GCC/RAISONANCE, small printf (option LD Linker->Libraries->Small printf
     set to 'Yes') calls __io_putchar() */
  #define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
#else
  #define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
#endif /* __GNUC__ */
/**
  * @brief  Retargets the C library printf function to the USART.
  * @param  None
  * @retval None
  */
PUTCHAR_PROTOTYPE
{
  /* Place your implementation of fputc here */
  /* e.g. write a character to the EVAL_COM1 and Loop until the end of transmission */
  HAL_UART_Transmit(&huart1, (uint8_t *)&ch, 1, 0xFFFF);
 
  return ch;
}
 
int fgetc(FILE * f)
{
  uint8_t ch = 0;
  HAL_UART_Receive(&huart1, (uint8_t *)&ch, 1, 0xffff);
  return ch;
}




/* 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_USART1_UART_Init();
  /* USER CODE BEGIN 2 */
	test();	
	
	
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
		HAL_Delay(1000);
		HAL_GPIO_TogglePin(LED_GPIO_Port, LED_Pin);
    /* 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();
  }
}

/* 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 */

  /* 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,
     tex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/

注意:STM32单片机的存储方式为小端模式。
一般的大小端:
地址从小到大,先放低字节,再放高字节:小端模式
地址从小到大,先放高字节,再放低字节:大端模式

四、运行结果

测试通过

换个芯片重新烧录测试


(注://芯片的唯一ID为: 30 FF 69 06 4D 50 35 35 39 25 08 43)
在测试时,需要在代码中手动添加,才能验证是否通过。
新增如下:两个方法
   Get_ChipID2(); 
    getSTM32SeriesID();
以下提高的代码需添加以上两个方法,由于分享的代码无法实施更新,删除步骤麻烦,这也是CSDN的BUG。请谅解,以文章提交的代码为准,谢谢各位攻城狮观阅 ^_^。

传送门->代码

参考文章:

1、STM32 进阶教程 9 - 芯片维一码(UID)读取_张十三的博客-CSDN博客_uid芯片

2、《嵌入式-STM32开发指南》第二部分 基础篇 - 第15章 程序加密(HAL库)_不问归期的博客-CSDN博客_stm32加密库的使用


五、总结

      好了,就介绍到此,有了它使用产品上就如虎添翼。

Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐