khelogram khelogram - 1 day ago 4
C Question

MCU Flash Memory programming in C

Newbie here. I am currently working on a project that involves saving password on MCU(NUC200LE3AN) Flash memory.

These codes works just fine. After writing it I am able to read the exact value of user_password1 even after the MCU restarts.

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);


But I will be using uint8_t array of 5(including the terminating '\0') as a source in changing my password. Example:

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] = '\0';

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);


With this, I can write the password and read it as long as those fix values are there and those fix values are just for default password. After I changed my password as long as i don't turn off the MCU it could still be read which is not acceptable due to the MCU needs to be turned on/off. If I apply this and then restart the MCU, reading PASSWORD1_LOCATION returns garbage/null.

Is there a way to turn this:

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


Into This:

uint32_t user_password1 = "1234";


I hope you know what I mean. Thank you.

LPs LPs
Answer

If you really want to store ascii values, you can simply translate it to its value in hex:

"1234" will be 0x31 0x32 0x33 0x34 0x00

To store it into a uint32_t, get rid of the null terminator and

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);
Comments