i have 6 serial objects here. Im coding for the raspberry pi pico using Earl E . Philhower's core.
Serial1 (hardware)
Serial2 (hardware)
Serial3 (SerialPIO)
Serial4 (SerialPIO)
Serial5 (SerialPIO)
Serial6 (SerialPIO)
and have a function
void myFunc(int deviceNumber, int x, int y) {
switch (deviceNumber) {
case 1:
Serial1.println(x);
Serial1.println(y);
//some more codes that uses Serial 1
Serial1.println(x + y);
break;
case 2:
Serial2.println(x);
Serial2.println(y);
//some more codes that uses Serial 2
Serial2.println(x + y);
break;
case 3:
Serial3.println(x);
Serial3.println(y);
//some more codes that uses Serial 3
Serial3.println(x + y);
break;
case 4:
Serial4.println(x);
Serial4.println(y);
//some more codes that uses Serial 4
Serial4.println(x + y);
break;
case 5:
Serial5.println(x);
Serial5.println(y);
//some more codes that uses Serial 5
Serial5.println(x + y);
break;
case 6:
Serial6.println(x);
Serial6.println(y);
//some more codes that uses Serial 6
Serial6.println(x + y);
break;
default:
break;
}
}
Each case statement is identical the only difference is which serial object i am using. I find this to be cluttered as if i need to edit 1 case statement i have to edit them all, which will leads me to sometimes miss a case. There has to be a better way of writing this that is more clean.
I would like to get something like this, its much more cleaner and not confusing to the eyes as there is no repeating lines of codes
void myFunc(int deviceNumber, int x, int y) {
switch (deviceNumber) {
case 1:
HardwareSerial* ptr = Serial1;
break;
case 2:
HardwareSerial* ptr = Serial2;
break;
case 3:
SerialPIO* ptr = Serial3;
break;
case 4:
SerialPIO* ptr = Serial4;
break;
case 5:
SerialPIO* ptr = Serial5;
break;
case 6:
SerialPIO* ptr = Serial6;
break;
}
ptr -> println(x);
ptr -> Serial1.println(y);
//some more codes that uses SerialX
ptr -> Serial1.println(x + y);
}
How can i do this?
