If I have multiple NODES one on each Serial port (and / or SoftwareSerial port) all of which have the same code for execution can the names of each Serial port be put into an array such that I can say:
for (int port = 0; port < 5; port++) {
SensorSerial[port].listen();
// Do a bunch of stuff
}
Is it as simple as predefining the SensorPort[]
array as
Stream& SensorSerial[] = {Node0, Node1, Node2, Node3, Node4}
1 Answer 1
The C++ language does not allow the creation of an array of references. The simple workaround is to instead use an array of pointers:
// Define SensorSerial as an array of pointers.
Stream* SensorSerial[] = {&Node0, &Node1, &Node2, &Node3, &Node4};
// In some function:
for (int port = 0; port < 5; port++) {
SensorSerial[port]->listen();
// Do a bunch of stuff
}
Edit: This is only a direct translation of your code to the array-of-pointers principle, but see timemage's comment for another issue.
-
->listen()
is aSoftwareSerial
thing. So it would need to beSoftwareSerial *SensorSerial[] =
. Or otherwise you need to downcast toSoftwareSerial *
before usinglisten()
.timemage– timemage2025年08月26日 19:02:24 +00:00Commented Aug 26 at 19:02 -
1@timemage: Indeed. I only addressed the actual question, without fixing this other issue.Edgar Bonet– Edgar Bonet2025年08月26日 20:26:12 +00:00Commented Aug 26 at 20:26
array of objects
that I put together ... the button example is probably the one for you, because each object in the array can have a different name (line 62) ... wokwi.com/projects/370998742721727489 and wokwi.com/projects/361204185271583745