Search code examples
c++staticavrstatic-membersavr-gcc

saving a PORT as static const member


How do i store a PORT or DDR or such as static const member? What i am trying todo is, instead of using #define TEMPERATURE_PORT PORTC inside of my class header i would like to store a static const member with that value and iniziallise this inside of a settings.h to have all my defines at one place.

class Temperatur
{
private:
    static const volatile uint8_t m_port;
};

settings.h which gets included last

const uint8_t Temperatur::m_port = PORTC;

This acutally causes the

Error   24  'Temperatur::m_port' cannot be initialized by a non-constant expression when being declared 

I use the assignement is inside of the settings.h which get included right after that file:

#include "Sensors/Temperatur.h"
#include "Sensors/Microphone.h"
//... some more includes here
//load the static and const settings
#include "settings.h"

This does already work for some other values but not for PORT and DDR.

Some more information: The Port is defined as:

#define PORTC _SFR_IO8(0x08)

which is defined as:

#define _SFR_IO8(io_addr) ((io_addr) + __SFR_OFFSET)

And this is a fixed value since the __SFR_OFFSET is defined as 0x00 or 0x20 depending on some marko value.

Is it maybe the definition of the makro for the _SFR_IO8 because it has a simple calculation? If so how do i solve this?


Solution

  • This compiles fine for me:

    #define __SFR_OFFSET 0x00
    #define _SFR_IO8(io_addr) ((io_addr) + __SFR_OFFSET)
    #define PORTC _SFR_IO8(0x08)
    
    class Temperatur
    {
    private:
        static const volatile uint8_t m_port;
    };
    
    const volatile uint8_t Temperatur::m_port = PORTC;
    

    The only thing that I found you might be missing is the volatile keyword in the assignment.