0

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}
Edgar Bonet
45.1k4 gold badges42 silver badges81 bronze badges
asked Aug 26 at 14:59
2
  • do you get some error? Commented Aug 26 at 17:27
  • this might help ... here are couple of examples of 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 Commented Aug 26 at 19:23

1 Answer 1

0

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.

answered Aug 26 at 18:18
2
  • ->listen() is a SoftwareSerial thing. So it would need to be SoftwareSerial *SensorSerial[] =. Or otherwise you need to downcast to SoftwareSerial * before using listen(). Commented Aug 26 at 19:02
  • 1
    @timemage: Indeed. I only addressed the actual question, without fixing this other issue. Commented Aug 26 at 20:26

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.