STM32芯片具备eth网口功能,但其出厂时没有配置唯一的MAC地址,而网络初始化时需要用到MAC地址。我们可以通过STM32的12字节的唯一芯片ID进行计算,得到一个大概率唯一的MAC地址来使用。
大家可以修改自己的计算规则,生成自己专属的mac地址,如下代码仅供参考:
/**
* [url=home.php?mod=space&uid=247401]@brief[/url] 获取mac地址
*
* @param pMacBuf 存储MAC地址buffer的首地址
*/
void getmac(uint8_t* pMacBuf)
{
if(pMacBuf == NULL)
return;
uint32_t uiMcuId = 0;
uint8_t pMcuID[15] = {0};
int i = 0;
uint32_t CpuID[3] = {0};
//获取CPU唯一ID
#if 0//STM32F1系列
CpuID[0] =*(vu32*)(0x1ffff7e8); //按全字(32位)读取
CpuID[1] =*(vu32*)(0x1ffff7ec);
CpuID[2] =*(vu32*)(0x1ffff7f0);
#endif
#if 1//STM32F4系列
CpuID[0]=*(uint32_t*)(0x1fff7a10);
CpuID[1]=*(uint32_t*)(0x1fff7a14);
CpuID[2]=*(uint32_t*)(0x1fff7a18);
#endif
printf("MCU UID: %08X-%08X-%08X\r\n",CpuID[0],CpuID[1],CpuID[2]);
printf("Flash Size: %dK\r\n", *(uint16_t *)(0X1FFF7a22));
//按字节(8位)读取
pMcuID[0] = (uint8_t)(CpuID[0] & 0x000000FF);
pMcuID[1] = (uint8_t)((CpuID[0] & 0xFF00) >>8);
pMcuID[2] = (uint8_t)((CpuID[0] & 0xFF0000) >>16);
pMcuID[3] = (uint8_t)((CpuID[0] & 0xFF000000) >>24);
pMcuID[4] = (uint8_t)(CpuID[1] & 0xFF);
pMcuID[5] = (uint8_t)((CpuID[1] & 0xFF00) >>8);
pMcuID[6] = (uint8_t)((CpuID[1] & 0xFF0000) >>16);
pMcuID[7] = (uint8_t)((CpuID[1] & 0xFF000000) >>24);
pMcuID[8] = (uint8_t)(CpuID[2] & 0xFF);
pMcuID[9] = (uint8_t)((CpuID[2] & 0xFF00) >>8);
pMcuID[10] = (uint8_t)((CpuID[2] & 0xFF0000) >>16);
pMcuID[11] = (uint8_t)((CpuID[2] & 0xFF000000) >>24);
uiMcuId = (CpuID[0]>>1)+(CpuID[1]>>2)+(CpuID[2]>>3);
for(i=0; i<12; i++) //获取McuID[12]
{
pMcuID[12] += pMcuID[i];
}
for(i=0; i<12; i++) //获取McuID[13]
{
pMcuID[13] ^= pMcuID[i];
}
pMacBuf[0] = (uint8_t)(uiMcuId & 0xF0);
pMacBuf[1] = (uint8_t)((uiMcuId & 0xFF00) >>8);
pMacBuf[2] = (uint8_t)((uiMcuId & 0xFF0000) >>16);
pMacBuf[3] = (uint8_t)((uiMcuId & 0xFF000000) >>24);
pMacBuf[4] = pMcuID[12];
pMacBuf[5] = pMcuID[13];
return;
}
|