Understanding pointer usage

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)

3 answers

  • answered 2019-04-21 10:07 Weather Vane

    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...
    }
    

  • answered 2019-04-21 10:33 bruno

    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
    

  • answered 2019-04-22 07:14 Mina Karam

    Welcome to your site.

    feel free to ask any question.

    This Site will help you to learn more about Embedded Systems