-1

I'm a newbie embedded system developer and actually, this is my first question here if you guys could answer my question also if you have any useful websites for the embedded system would be really appreciated if posted it.

What does the second pointer after u8 mean in this code?

#define DDRA (*(volatile u8*) 0x3A)
Weather Vane
  • 33,872
  • 7
  • 36
  • 56

2 Answers2

2

The macro

#define DDRA (*(volatile u8*) 0x3A)

is using (volatile u8*) to cast 0x3A as a pointer to an 8-bit value, and then the first * is deferencing that pointer. It is accessing a memory-mapped port control register.

The volatile keyword is needed to prevent the compiler optimising away references to the register, being a hardware location.

An example usage would be when setting up the port A data direction in a micro-controller:

#define DDRA (*(volatile char*) 0x3A)

int main()
{
    DDRA = 0x2A;
    // etc...
}
Weather Vane
  • 33,872
  • 7
  • 36
  • 56
  • u8* is the same as *u8? – Mahmoud Usama Apr 21 '19 at 10:19
  • @mahmoudosama no, `u8*` is the type "pointer to a _u8_" (supposing not u8 times something ;-) ) but `*u8` try to deference _u8_ (like `*((char*) "ab")` returns 'a' – bruno Apr 21 '19 at 10:29
  • @mahmoudosama no, the `u8` is a type and `*u8` is trying to dereference a type, which doesn't make sense. The `*` is placed *after* the type name, to indicate it is a pointer to that type. – Weather Vane Apr 21 '19 at 10:35
0

What does the second pointer after u8 mean in this code?

I suppose you speak about the second "*"

u8* is the type "pointer to an u8"

(*(volatile u8*) 0x3A)

adding () it is like

(*((volatile u8*) 0x3A))

so 0x3A is considered as an address of an u8 (u8*) and the first "*" dereference it so (*((volatile u8*) 0x3A)) try to return the u8 at the address 0x3A (it will produces a segmentation fault if 0x3A is not a valid address) or on a left side of an assignment try to write at the address 0x3A

For instance defining u8 as a char and replacing 0x3A by the address of a global var :

#include <stdio.h>

#define DDRA (*(volatile u8 *) &A)

typedef char u8;

int A = 'a';

int main()
{
  printf("%c\n", DDRA);
  DDRA = 'b';
  printf("%c\n", DDRA);

  return 0;
}

Compilation and execution :

pi@raspberrypi:/tmp $ gcc -pedantic -Wextra -Wall c.c
pi@raspberrypi:/tmp $ ./a.out
a
b
bruno
  • 32,421
  • 7
  • 25
  • 37