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); 
        }
    }
}
  • please, next time provide code that compiles – Juraj Jul 17 at 6:59
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, privacy policy and cookie policy

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