Question
BKPSRAM access in STM32MP1x MPU
We need to store some of our application data in BKPSRAM block so we can persist it during power down. Here is the code that we created to write to the BKPSRAM block, could you please help me to define what is wrong. Thanks.
#include <sys/mman.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdint.h>
#include <sys/stat.h>
#include <string.h>
#define PAGE_SIZE 4096
typedef struct __attribute__((packed)) {
uint32_t value1;
uint32_t value2;
char str[24];
} MyStruct;
int main() {
int fd;
uint32_t *mapped_memory;
// Open /dev/mem
fd = open("/dev/mem", O_RDWR | O_SYNC);
if (fd == -1) {
perror("open");
return 1;
}
// Calculate the page-aligned address
off_t base_addr = 0x54000000U;
off_t aligned_addr = base_addr & ~(PAGE_SIZE - 1);
// Calculate the offset from the page boundary
off_t offset = base_addr - aligned_addr;
// Map the aligned address with the required size
mapped_memory = mmap(NULL, offset + sizeof(MyStruct), PROT_READ | PROT_WRITE, MAP_SHARED, fd, aligned_addr);
if (mapped_memory == MAP_FAILED) {
perror("mmap");
close(fd);
return 1;
}
// Calculate the pointer to the desired address
MyStruct *myStruct = (MyStruct *)((uintptr_t)mapped_memory + offset);
// Write data to BKPSRAM
myStruct->value1 = 0xDEADBEEF;
printf("Data read from BKPSRAM: 0x%08x\n", myStruct->value1);
myStruct->value2 = 0xFFFFEEEE;
printf("Data read from BKPSRAM: 0x%08x\n", myStruct->value2);
char str[] = "Hello World!\0";
for(int i = 0; i < sizeof(str)/sizeof(char); i++){
myStruct->str[i] = str[i];
printf("%c", myStruct->str[i]);
}
printf("\n");
// Unmap the memory
if (munmap(mapped_memory, offset + sizeof(MyStruct)) == -1) {
perror("munmap");
close(fd);
return 1;
}
// Close /dev/mem
close(fd);
return 0;
}
