jeudi 19 août 2021

Range based for loops without using std libraries

I am working on an arduino project where I need to do the same task for a number of digital outputs. Since the arduino compiler supports C++11, I would like to use range-based for loops to have more readable code. However, as far as I know, on arduino there is no access to the std libraries that one would usually use in this case (correct me, if I'm wrong here). So my question is, whether there are good approaches to use range-based for loops without the std libraries. My (simplified) working code looks as follows:

static const byte OUTPUT_GROUP1[] = {4};
static const byte OUTPUT_GROUP2[] = {5, 6, 7};
static const byte *OUTPUTS[] = {OUTPUT_GROUP1, OUTPUT_GROUP2};

static const uint32_t MILLIS_GROUP1[] = {1000};
static const uint32_t MILLIS_GROUP2[] = {5000, 2000, 3000};
static const uint32_t *MILLIS[] = {MILLIS_GROUP1, MILLIS_GROUP2};

static const size_t GROUP_SIZES[] = {1, 3};

void loop() {
    for (size_t group = 0; group < 2; ++group) {
        for (size_t i = 0; i < GROUP_SIZES[group]; ++i) {
            digitalWrite(OUTPUTS[group][i], HIGH);
            delay(MILLIS[group][i]);
            digitalWrite(OUTPUTS[group][i], LOW);
        }
    }
}

So there are two groups of outputs that I would like to keep apart. My main goal is to get rid of the variable GROUP_SIZES, since the number of outputs per group may change and forgetting about updating GROUP_SIZES is a source of error. For that I need to achieve two things. Firstly, I need to loop over nested lists, which usually I might solve using a std::vector. Secondly, I need to loop over two ranges simultaneously, to also access the millis to delay. This could be done using std or boost. However, on arduino it seems that there is no easy approach without coding a lot of magic myself. Is there an easy way to get this working?

Aucun commentaire:

Enregistrer un commentaire