user3857924
user3857924

Reputation: 86

C casting to a structure

What is the purpose of the following code:

#define LPC_ADC  ((LPC_ADC_T   *) LPC_ADC_BASE)

LPC_ADC_T is a structure holding some constants.

typedef struct {                                
    __IO uint32_t CTRL;                     
    __I  uint32_t RESERVED0;
    __IO uint32_t SEQ_CTRL[ADC_SEQB_IDX + 1];   
    __IO uint32_t SEQ_GDAT[ADC_SEQB_IDX + 1];   
    __I  uint32_t RESERVED1[2];
    __I  uint32_t DR[9];                        
    __I  uint32_t RESERVED2[3];
    __IO uint32_t THR_LOW[2];                   
    __IO uint32_t THR_HIGH[2];              
    __IO uint32_t CHAN_THRSEL;              
    __IO uint32_t INTEN;                        
    __IO uint32_t FLAGS;                    
    __IO uint32_t TRM;                          
} LPC_ADC_T;

LPC_ADC_BASE is a constant.

Is it simply casting the constant number LPC_ADC_BASE to a structure?

Upvotes: 0

Views: 155

Answers (3)

unwind
unwind

Reputation: 399803

It's casting the integer value to a pointer to the structure.

The point is to allow access by name for each register in that particular device. It depends on the layout of the struct's members being very compact and predictable, often you use compiler-specific options to ensure that.

Upvotes: 1

alagner
alagner

Reputation: 4062

After that cast you can access the registers like

uint32_t something = 0xf5; //whatever
LPC_ADC->CTRL = something;

The following code

#define LPC_ADC  ((LPC_ADC_T   *) LPC_ADC_BASE)

means: Treat LPC_ADC_BASE as an address of LPC_ADC_T type structure and allow to access it using name LPC_ADC

Upvotes: 1

Waty
Waty

Reputation: 121

It's casting the constant number to a pointer to an address.

It assumes that at the memory of your program contains a LPC_ADC_T at the address LPC_ADC_BASE

This is a method used when you know the address of a struct/method at compiletime.

Upvotes: 0

Related Questions