How to simplyfy switch cases with the same repeating codes but uses different variables

Serial generally inherits from Stream, so you could do something like this (has not been tested)


void myFunc(int deviceNumber, int x, int y) {
  Stream* serials[] = {
    &Serial1,
    &Serial2,
    &Serial3,
    &Serial4,
    &Serial5,
    &Serial6
  };

  if ((deviceNumber >= 1) && (deviceNumber <= 6)) {
    serials[deviceNumber]->println(x);
    serials[deviceNumber]->println(y);
    serials[deviceNumber]->println(x + y);
  }
}
1 Like