1

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
2
  • what have you tried? ... what errors did you get? Commented 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. Commented Sep 3, 2019 at 18:55

1 Answer 1

4

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

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.