2

I have some code

   // Locals to hold pointers to the hardware

static volatile uint32_t *gpio ;
static volatile uint32_t *pwm ;
static volatile uint32_t *clk ;
static volatile uint32_t *pads ;

     void setPadDrive (int group, int value)
{
  uint32_t wrVal ;

  if ((wiringPiMode == WPI_MODE_PINS) || (wiringPiMode == WPI_MODE_PHYS) || (wiringPiMode == WPI_MODE_GPIO))
  {
    if ((group < 0) || (group > 2))
      return ;

    wrVal = BCM_PASSWORD | 0x18 | (value & 7) ;
    *(pads + group + 11) = wrVal ;

    if (wiringPiDebug)
    {
      printf ("setPadDrive: Group: %d, value: %d (%08X)\n", group, value, wrVal) ;
      printf ("Read : %08X\n", *(pads + group + 11)) ;
    }
  }
}

So from above the CPU registers are memory mapped and pointed by pointer. So, if I accessed those memory location, the CPU see volatile and it will reroute the access to the register.

also, how does CPU knows a particular memory location will route to which register? Am I missing a table that indicate that?

lilzz
  • 5,243
  • 14
  • 59
  • 87
  • I think you meant [this](http://stackoverflow.com/questions/578202/register-keyword-in-c). – Mauren Oct 09 '13 at 18:26
  • @Mauren I don't think so. This is clearly embedded programming, and `volatile` is used a lot there for this exact purpose. – orlp Oct 09 '13 at 18:27

1 Answers1

1

No, volatile means that the C compiler will not optimize away code regarding the variable. This is absolutely crucial when it comes to interfacing with hardware through pointers.

As a pretty contrived example, let's say I have a pointer printer that is set up in such a way that the machine will print any byte stored in it. Then this code would print aa:

*printer = 'a';
*printer = 'a';

However, a compiler might think the second assignment is unnecessary and optimize it out - volatile prevents this.


In your particular example it seems the machine was set up such that particular memory addresses function as registers (or register proxies).

orlp
  • 112,504
  • 36
  • 218
  • 315