18

How do you assign a specific memory address to a pointer?

The Special Function Registers in a microcontroller such AVR m128 has fixed addresses, the AVR GCC defines the SFR in the io.h header file, but I want to handle it myself.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Peter Luke
  • 181
  • 1
  • 1
  • 3

1 Answers1

38

Sure, no problem. You can just assign it directly to a variable:

volatile unsigned int *myPointer = (volatile unsigned int *)0x12345678;

What I usually do is declare a memory-mapped I/O macro:

#define mmio32(x)   (*(volatile unsigned long *)(x))

And then define my registers in a header file:

#define SFR_BASE    (0xCF800000)
#define SFR_1       (SFR_BASE + 0x0004)
#define SFR_2       (SFR_BASE + 0x0010)

And then use them:

unsigned long registerValue = mmio32(SFR_1); // read
mmio32(SFR2) = 0x85748312;                   // write
Carl Norum
  • 219,201
  • 40
  • 422
  • 469