1

I wanted to know how to access a particular register in a microcontroller having mapped at a particular fixed address. I googled about this issue and I found the following:

#define WDTCTL     (*((volatile unsigned short *)0x0120))
#define P1DIR (*((volatile unsigned char *)0x0022))

This method of works absolutely fine but I do not understand how it works.

I will be glad if someone could explain it to me.

flau
  • 1,328
  • 1
  • 20
  • 36

1 Answers1

1

define WDTCTL (*((volatile unsigned short *)0x0120))

This means that WDTCTL register is at the address 0x0120. (volatile unsigned short *) will typecast that into a short pointer. Then (*((volatile unsigned short *)0x0120)) will give the value at that pointer location.

The reason to use volatile here is that for microcontroller addresses, the value can change at any time independently of the C code. The volatile keyword disallows compiler optimizations around this register.

For more information see Why is volatile needed in C?

Community
  • 1
  • 1
Rishikesh Raje
  • 8,556
  • 2
  • 16
  • 31
  • Hey thanks for the reply. I have a question can I do the above in this way, "volatile unsigned short *WDTCTL " , "WDTCTL=0×0120" and then dereference it "*WDTCTL = 0×01" and write whatever I want. Pls reply – Anas Shaikh Aug 17 '16 at 13:33
  • Yes, you can do it like that. However, in your case you are assigning a pointer variable `WDCTL` which will take some memory. Also you will have to do it for all the registers of the microcontroller, which might take too much memory. – Rishikesh Raje Aug 18 '16 at 04:43