2

I need to read the content of a specific address from the FLASH memory of a STM32F1 microcontroller. Each address contains 32 bits, so I would like to know if I can do the following:

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

or should I do something like this:

uint32_t addr = 0X0801F000;
read_value = *(unsigned char *)addr;  // this in a loop since char is 8 bits?
9
  • 1
    Why not uint32_t *addr = 0X0801F000; read_value = *addr; Notice that you missed the star in the declaration of addr. Commented Mar 10, 2021 at 21:23
  • 1
    Sure. If the pointer is a uint32_t *addr then accessing *addr will give you a 32 bit number. Commented Mar 10, 2021 at 21:29
  • 2
    If you want the compiler to not optimize away the actual reading and writing you should declare addr as volatile uint32_t *addr (volatile tells the compiler that it MUST read and write to the memory and it can't optimize it away even if it knows what is in the memory location.) Commented Mar 10, 2021 at 21:36
  • 1
    Very true, I forgot about volatile. So to summarize, in order to read different values each time I can simply do: read_value = (*((volatile uint32_t*)(0x0801F000)));? Commented Mar 10, 2021 at 21:41
  • 1
    That looks right to me. Commented Mar 10, 2021 at 21:44

1 Answer 1

2

It can be written it like this (but see below for a beeter idea):

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

If you cast addr as an unsigned char * like you do in your second example, then, when you dereference the unsigned char pointer, you get an unsigned char:

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

So that's not what you want because then you only read one character. Then, there is one other thing you should remember, you need volatile if you want the compiler to read the memory address every single time you dereference the pointer. Otherwise, the compile could skip that if it already knows that the value is. Then you would have to write it like this:

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

Or if you put it all on one line (like you did in your comment):

uint32_t read_value = (*((volatile uint32_t*)(0x0801F000)));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.