In my use case I have multiple devices connected to the serial ports of an arduino. Currently I write to them using Serial1.write()
, Serial2.write()
, etc.
How can I choose the port programmatically, for example:
for(int i = 0; i < numDevices; i++){
Serial[i].write();
}
asked Sep 3, 2019 at 18:19
-
what have you tried? ... what errors did you get?jsotola– jsotola09/03/2019 18:25:29Commented Sep 3, 2019 at 18:25
-
I'm not getting any errors because, as stated, I know how to write it 'hard-coded' but not the way I want. I didn't try Serial[i] because that's obviously wrong, but I can't find any docs on how to write to a variable pin.progressiveCavemen– progressiveCavemen09/03/2019 18:55:25Commented Sep 3, 2019 at 18:55
1 Answer 1
You may use an array of pointers to the actual serial ports. For example, on an Arduino Mega:
const size_t PORTS_COUNT = 4;
const HardwareSerial *ports[PORTS_COUNT] = {
&Serial, &Serial1, &Serial2, &Serial3
};
void setup() {
for (size_t i = 0; i < PORTS_COUNT; i++)
ports[i]->begin(9600);
}
answered Sep 3, 2019 at 19:16