Question

Here is a part of microcontroller code, which I am not able to understand.

#define GPIO_PORTF_DIR_R        (*((volatile unsigned long *)0x40025400))

int main (void){
     GPIO_PORTF_DIR_R = 0x0E;
...}

As I understood, GPIO_PORTF_DIR_R is not a vairable, and (*((volatile unsigned long *)0x40025400)) is the content of the address pointed by the pointed. Then how is it possible to use GPIO_PORTF_DIR_R as variable. What is happening here.

Was it helpful?

Solution

#define declares a preprocessor macro. This means that before compilation GPIO_PORTF_DIR_R will be replaced everywhere in the code with the contents of the macro. So your actually compiled code will be

(*((volatile unsigned long *)0x40025400)) = 0x0E;

Which pretty much means write 0x0E to that address.

Preprocessor macros are often used if you wish to to reference some (complicated) numeric value by a name. This allows you to centrally change that value if you have to, but have a meaningful name in your code without having to have a variable for it.

OTHER TIPS

The constant value 0x40025400 is being used as a memory address. It seems that on your platform (a microcontroller), that address is a memory-mapped general-purpose I/O port.

The code is equivalent to this, if it makes it more readable:

// pointer to memory address 0x40025400
volatile unsigned long *p = 0x40025400;

// set that value in memory
*p = 0x0E;

tl;dr. The assignment isn't to a variable, it is to a specific location in memory.

The macro here can be thought of as just being substitued in for its use.

#define GPIO_PORTF_DIR_R (*((volatile unsigned long *)0x40025400))
int main (void) {
  GPIO_PORTF_DIR_R = 0x0E;
...

Could be rewritten as

int main (void) {
  (*((volatile unsigned long *)0x40025400)) = 0x0E;
...

Which is just dereferencing the memory address 0x40025400 and assigning it the value 0x0E.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top