一、概述

最近项目上使用STM32的device id来标识每个设备,这里简单记录下STM32的UID。

二、寄存器

芯片的手册,找到UID的地址。以STM32L051为例,如下图:
在这里插入图片描述
可以看到UID96位,也就是12字节。
在这里插入图片描述
有了具体地址,即可通过直接寻址读取ID。需要注意的是:Bits 95:64的Address offset为0x14。一定不要直接基地址、基地址+4、基地址+8的方式读取。

 #define UID_BASE 0x1FF80050
  uint32_t UID[3];
  UID[0] = (uint32_t)(*((uint32_t *)UID_BASE));
  UID[1] = (uint32_t)(*((uint32_t *)(UID_BASE + 0x04)));
  UID[2] = (uint32_t)(*((uint32_t *)(UID_BASE + 0x14)));

三、HAL库函数

此外,HAL库也提供了接口函数读取ID。

  uint32_t UID[3];
  UID[0] = HAL_GetUIDw0();
  UID[1] = HAL_GetUIDw1();
  UID[2] = HAL_GetUIDw2();

查看HAL函数,定义如下:

/**
  * @brief  Returns the first word of the unique device identifier (UID based on 96 bits)
  * @retval Device identifier
  */
uint32_t HAL_GetUIDw0(void)
{
  return(READ_REG(*((uint32_t *)UID_BASE)));
}

/**
  * @brief  Returns the second word of the unique device identifier (UID based on 96 bits)
  * @retval Device identifier
  */
uint32_t HAL_GetUIDw1(void)
{
  return(READ_REG(*((uint32_t *)(UID_BASE + 0x04U))));
}

/**
  * @brief  Returns the third word of the unique device identifier (UID based on 96 bits)
  * @retval Device identifier
  */
uint32_t HAL_GetUIDw2(void)
{
  return(READ_REG(*((uint32_t *)(UID_BASE + 0x14U))));
}

也是用直接寻址读取,只不过是封装了一下。


STM32 量产时自动写入序列号
概念扩展:UUID GUID

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐