0

How should I index HardwareSerial ports into a single array?.

This compiles, but do not work.

HardwareSerial Serials[]={Serial,Serial1,Serial2,Serial3};

void setup(){
    for (int i=0;i<=3;i++){
        Serials[i].begin(38400);
        while (!Serials[i]);
    }
}

char s;
void loop(){
    for (int i=0;i<=3;i++){
        if (Serials[i].available()){
            s=Serials[i].read(); 
            Serials[i].write(s); 
        }
    }
}
1
  • please, next time provide code that compiles
    – Juraj
    Commented Jul 17, 2019 at 6:59

1 Answer 1

5

your code makes copies of Serials into items in the array of HardwareSerials. To use the original Serial objects, store and use pointers.

HardwareSerial* Serials[]={&Serial,&Serial1,&Serial2,&Serial3};

void setup(){
    for (int i=0;i<=3;i++){
        Serials[i]->begin(38400);
        while (!*Serials[i]);
    }
}

void loop(){
    for (int i=0;i<=3;i++){
        if (Serials[i]->available()){
            char s=Serials[i]->read();
            Serials[i]->write(s);
        }
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.