setting pointers to fixed values

I'm writing a program for an embedded application. There are several registers at fixed addresses, and I'd like to refer to those addresses symbolically.

I tried this:

1
2
3
4
5
6
7
8
9
10
11
#include <stdint.h>

const uint32_t *GPIOC = (uint32_t *) 0x40020800;

int main()
{
  uint32_t *p32;
  p32 = GPIOC;
 
  return 0;
}


But the compiler throws an error (why?).

This works:

1
2
3
4
5
6
7
8
9
10
11
12
#include <stdint.h>

const uint32_t GPIOC = 0x40020800;

int main()
{
  uint32_t *p32;
  
  p32 = (uint32_t *) (GPIOC);
  
  return 0;
}


But this strikes me as really inelegant and rather failure-prone (I left out much of the pointer arithmetic necessary to get to offsets from these base addresses).

Any comments/suggestions? Thanks.
The only error I had on the first one is a const conversion error, because you screwed up the position of your const:

const uint32_t* GPIOC //this is a pointer to a CONST integer

I think you meant:

uint32_t* const GPIOC //this is a CONST pointer to a mutable integer

Btw, you should post your errors next time in addition to your code so we don't have to compile it ourselves.
Last edited on
Thanks, firedraco. Those access modifiers trip me up every time.

I'll try to remember to post errors in the future.

Now, for my offsets: they're defined as integers (since I can't add pointers). But I'm getting a 4X increment over what I really want. Examples:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <stdint.h>

uint32_t* const GPIOC = (uint32_t *) 0x40020800;
const uint8_t GPIO_MODER_OFFSET = 0x0;
const uint8_t GPIO_SPEEDR_OFFSET = 0x8;
const uint8_t GPIO_BSRR_OFFSET = 0x18;

const uint32_t RCC = 0x40023800;
const uint8_t RCC_AHB1RSTR_OFFSET = 0x10;

int main()
{
  uint32_t *p32;
  uint16_t *p16;
  
  p32 = GPIOC + GPIO_MODER_OFFSET;
  *p32 = 0xc000;
  p32 = GPIOC + GPIO_SPEEDR_OFFSET;  // result is 0x40020820
  
  p32 = GPIOC + GPIO_BSRR_OFFSET;    // result is 0x40020860
  
  return 0;
}


One solution, I suppose, would be to use pointers to uint8_t instead of 32, but...I'll need to set 32-bit values in a single operation, so I'm not sure that will work. Any suggestions on this?
Topic archived. No new replies allowed.