C 语言的 MCU 闪存编程

MCU Flash Memory programming in C

这里是新手。我目前正在做一个涉及在 MCU(NUC200LE3AN) 闪存上保存密码的项目。

这些代码工作得很好。写入后,即使在 MCU 重新启动后,我也能够读取 user_password1 的确切值。

FMC_Erase(PASSWORD1_LOCATION); //u32addr 
if (*(uint32_t *)(PASSWORD1_LOCATION) == 0xffffffff)
{
    uint32_t user_password1 = "1234";
    FMC_Write(PASSWORD1_LOCATION,user_password1);
}

uint32_t ReadPass1 = *(uint32_t *)(PASSWORD1_LOCATION);

UART_Write(UART0,ReadPass1,4); //4 -> string length 
_UART_SENDBYTE(UART0,0x0D);

但我将使用 uint8_t 数组 5(包括终止 '\0')作为更改密码的来源。示例:

FMC_Erase(PASSWORD1_LOCATION);    

uint8_t new_password[5];
new_password[0] = '1';
new_password[1] = '2';
new_password[2] = '3';
new_password[3] = '4';
new_password[4] = '[=11=]';

if (*(uint32_t *)(PASSWORD1_LOCATION) == 0xffffffff)
{
  user_password1 = (uint32_t *)(new_password);
  FMC_Write(PASSWORD1_LOCATION,user_password1);
}

uint32_t ReadPass1 = *(uint32_t *)(PASSWORD1_LOCATION);

UART_Write(UART0,ReadPass1,4); //4 -> string length 
_UART_SENDBYTE(UART0,0x0D);

有了这个,只要那些固定值在那里,我就可以编写和读取密码,而这些固定值仅用于默认密码。在我更改密码后,只要我不关闭 MCU,它仍然可以读取,这是不可接受的,因为 MCU 需要打开 on/off。如果我应用它然后重新启动 MCU,读取 PASSWORD1_LOCATION returns garbage/null.

有没有办法改变这个:

uint8_t new_password[5];     
new_password[0] = '1';
new_password[1] = '2';
new_password[2] = '3';
new_password[3] = '4';
new_password[4] = '[=12=]';

进入这个:

uint32_t user_password1 = "1234";

我希望你明白我的意思。谢谢。

如果你真的想存储 ascii 值,你可以简单地将其转换为十六进制值:

"1234" 将是 0x31 0x32 0x33 0x34 0x00

要将其存储到 uint32_t 中,去掉空终止符和

FMC_Erase(PASSWORD1_LOCATION); //u32addr 
if (*(uint32_t *)(PASSWORD1_LOCATION) == 0xffffffff)
{
    uint32_t user_password1 = 0x31323334;
    FMC_Write(PASSWORD1_LOCATION, &user_password1);
}

uint32_t ReadPass1 = *(uint32_t *)(PASSWORD1_LOCATION);

UART_Write(UART0,ReadPass1,4); //4 -> string length 
_UART_SENDBYTE(UART0,0x0D);