zud
zud

Reputation: 169

Understanding use of pointer in embedded system

Here is a part of the code:

#define GPIO_PORTF_DATA_BITS_R  ((volatile unsigned long *)0x40025000)
#define LED_BLUE 0x04
#define LED_GREEN 0x08
#define LED_RED 0x02

GPIO_PORTF_DATA_BITS_R[LED_BLUE | LED_GREEN | LED_RED] = (LED_GREEN | LED_RED)

With my the little understanding I have about pointers, it is equivalent to

volatile unsigned long *p = 0x40025400;
p[0x0E] = 0x0A;

If I am correct, what does p[0x0E] mean or do here?

Upvotes: 2

Views: 542

Answers (2)

unwind
unwind

Reputation: 400109

In C, the indexing operator [] has the following semantics: a[b] means *(a + b), so either a or b must evaluate to an address.

Thus, your example means *(0x40025400 + 0xe) = 0xa, i.e. it accesses a register which is at offset 0xe * sizeof (unsigned long) from the base address at 0x40025400. The scaling is since the pointer is to unsigned long, and pointer arithmetic is always scaled by the size of the type being pointed at.

Upvotes: 3

chux
chux

Reputation: 154272

Agree with @Lundin. The defines LED_BLUE, LED_GREEN, LED_RED all being powers of 2 and LED control typically needing only a bit on or off imply that these defines are bit masks.

Suggest you need the following.

void LED_Red_On(void) {
  *GPIO_PORTF_DATA_BITS_R |= LED_RED;
}

void LED_Green_Off(void) {
  *GPIO_PORTF_DATA_BITS_R &= ~((unnsigned long)LED_GREEN);
}

...

Upvotes: 0

Related Questions