从STM32F1的闪存中读取特定地址的内容

Read content of a specific address from flash memory STM32F1

我需要从STM32F1单片机的FLASH存储器中读取特定地址的内容。每个地址包含 32 位,所以我想知道是否可以执行以下操作:

uint32_t addr = 0X0801F000;
read_value = (*((uint32*)(addr)));

或者我应该这样做:

uint32_t addr = 0X0801F000;
read_value = *(unsigned char *)addr;  // this in a loop since char is 8 bits?

可以这样写(但是更好的想法见下文):

uint32_t *addr = 0X0801F000;
uint32_t read_value = *addr;

如果像在第二个示例中那样将 addr 转换为 unsigned char *,那么,当您取消引用 unsigned char 指针时,您会得到一个 unsigned char:

uint32_t* addr = 0X0801F000;
unsigned char read_value = *(unsigned char *)addr;

这不是你想要的,因为那样你只读了一个字符。然后,还有一件事你应该记住,你需要 volatile 如果你希望编译器在你每次取消引用指针时读取内存地址。否则,编译可能会跳过它,如果它已经知道该值是的话。那么你必须这样写:

volatile uint32_t *addr = 0X0801F000;
uint32_t read_value = *addr;

或者,如果您将所有内容都放在一行中(就像您在评论中所做的那样):

uint32_t read_value = (*((volatile uint32_t*)(0x0801F000)));