0

My question is generic and not related to any specific microcontroller. Below is code for writing to a hardware register address. In this code, I'm trying to write several values, one after the other.

unsigned int *p;  //declare a pointer

p = (int *) 0x200;  //point to hardware register address

*p = 0x12;  // write to hardware register address

*p = 0xA5;  // write to hardware register address

*p = 0xff;  // write to hardware register address

Does the above need any correction?

Martin B
  • 23,670
  • 6
  • 53
  • 72
  • What do you mean by correction? This post might be some help: [How to initialize a pointer to a specific memory address in C++](http://stackoverflow.com/questions/3934775/how-to-initialize-a-pointer-to-a-specific-memory-address-in-c) – gongzhitaao Mar 23 '13 at 04:32
  • In your architecture, would you need to insert memory barriers between the three assignments to `*p`? – Celada Mar 23 '13 at 04:58

1 Answers1

9

If you're writing to a hardware register, you'll typically want to use the volatile keyword:

volatile unsigned int *p;

Without the volatile, an optimizing compiler might conclude that the first two writes are unnecessary (because the value is immediately overwritten) and optimize them away.

This Wikipedia article has more information on volatile.

Martin B
  • 23,670
  • 6
  • 53
  • 72
  • Also [this](http://www.embedded.com/electronics-blogs/beginner-s-corner/4023801/Introduction-to-the-Volatile-Keyword) on Embedded.com. – Clifford Mar 23 '13 at 21:39
  • 1
    An alternative is to use [Memory barriers](http://en.wikipedia.org/wiki/Memory_barrier). We don't have the semantics of the register (write only, etc). It is possible if this is an interrupt mask register that **memory barriers** would be better. If the register is updated asynchronously by *non-CPU* hardware or if the writes are stateful, `volatile` is the best. Maybe *stateful* is the wrong terminology, *write 1 to clear* is an example of what I am thinking of. – artless noise Mar 25 '13 at 14:38