Search code examples
c++pointersstructavr

Passing a Port-Address to function


How do I retrieve the pointer from this definition?

The Definition: #define SPIE (*(SPI_t *) 0x0AC0) /* Serial Peripheral Interface */ and the adress of the register is 0x0AC0. SPI_t is a struct defined further down in the header file:

/* Serial Peripheral Interface */
typedef struct SPI_struct
{
    register8_t CTRL;  /* Control Register */
    register8_t INTCTRL;  /* Interrupt Control Register */
    register8_t STATUS;  /* Status Register */
    register8_t DATA;  /* Data Register */
} SPI_t;

I really have no idea what is going on in the define. It looks like the pointer is being casted to the struct, but I'm not sure. What I need is a uint16_t* pointer, so I can pass it on to a function. Using spi mySpi( &PORTB); with the constructor being

spi::spi(volatile uint16_t* reg)
{
    spiReg = reg;
} //spi

results in Error 1 no matching function for call to 'spi::spi(PORT_t*)'


Solution

  • The define #define SPIE (*(SPI_t *) 0x0AC0 is creating a symbolic name (SPIE) for 4 bytes of memory located at 0x0AC0. That is 0x0AC0 is the control register, 0x0AC1 is the interrupt control register, and so on.

    Your C code should be able to reference these like so

    SPIE.CTRL = 7; // set low 3 bits for some reason
    SPIE.INTCTRL = 4; // set 3rd bit, disable all others
    

    To get the address, you could "take the address" as usual: &SPIE. This will be 0x0AC0 when evaluated, but will have the type SPI_t *.

    Your constructor takes a 16-bit register, but SPIE defines only 8-bit registers, so I don't think its going to work out so well.