1

I have been developing a set of software drivers for the peripherals of a MCU. I need to implement those drivers in the C++ programming language. My idea was to model each driver by its own class.

Interface of a driver for the Peripheral01:

#include "HalCfg.h"

class Periph01 {
public:
    Periph01(HalCfg*);
    Periph01(const Periph01& orig);
    virtual ~Periph01();
    void init();
    int getCfg();
private:
    HalCfg *m_halCfg;
    int m_cfg;

};

Implementation of a driver for the Peripheral01:

#include "Periph01.h"

Periph01::Periph01(HalCfg *halCfg) {
    m_halCfg = halCfg;
}

Periph01::Periph01(const Periph01& orig) {
}

Periph01::~Periph01() {
}

void Periph01::init() {
    m_cfg = m_halCfg->periph01Cfg.cfg;
}

int Periph01::getCfg() {
    return m_cfg;
}

Each driver will have its configuration

struct Periph01Cfg
{
    int cfg;
};

Configuration of all the drivers will be aggregated at one place

#include "Periph01Cfg.h"

struct HalCfg
{
    Periph01Cfg periph01Cfg;
};

The usage will be following

int main(int argc, char** argv) {
    
    HalCfg halCfg;
    halCfg.periph01Cfg.cfg = 255;
    
    Periph01 periph01 = Periph01(&halCfg);
    periph01.init();
    
    cout << "Peripheral_01 configuration: " << periph01.getCfg() << endl;

    return 0;
}

The weakness of this solution is that I need to define a HalCfg type variable and then fill the configuration of all the peripherals at run time. From my point of view it would be better if I can fill the configuration of all the peripherals at compile time at one place in the software. Does anybody have any idea how to do that? Thanks in advance.

UPDATE:

I have probably find a solution based on the so called in-class initialization:

Configuration of all the drivers will be aggregated at one place

#include "Periph01Cfg.h"

struct HalCfg
{
    Periph01Cfg periph01Cfg = {255};
};

The usage will be following

int main(int argc, char** argv) {
    
    HalCfg halCfg;
            
    Periph01 periph01 = Periph01(&halCfg);
    periph01.init();
    
    cout << "Peripheral_01 configuration: " << periph01.getCfg() << endl;

    return 0;
}
L3sek
  • 159
  • 5
  • please don't **[cross-post](https://meta.stackexchange.com/tags/cross-posting/info "'Cross-posting is frowned upon...'")**: https://stackoverflow.com/questions/64842880/how-to-develop-mcu-peripheral-drivers-in-c "Cross-posting is frowned upon as it leads to fragmented answers splattered all over the network..." – gnat Nov 15 '20 at 10:11
  • @gnat I advised the OP to ask here. The original question should be deleted though. – πάντα ῥεῖ Nov 15 '20 at 10:20
  • @πάνταῥεῖ I have probably find a solution of my problem (please see the update in my original post). Please can you tell me what do think about that idea? – L3sek Nov 15 '20 at 19:49

0 Answers0