In what circumstances it is useful to have multiple instances of classes from standard libraries (eg. Serial, Wire, etc.)

In what circumstances it is useful to have multiple instances of classes from standard libraries (eg. Serial, Wire, etc.)

Please reword.

Many circumstances.

For example, the Mega2560 has four serial ports: Serial, Serial1, Serial2, Serial3.

Where there are multiple instances of a hardware resource which can each be encapsulated be an instance of a class (object).
This could apply to timers, UARTs. I/O devices etc. etc.
If, however, a MCU has, for example, only one I2C port then there will be little point in creating multiple Wire objects.

And, contention between the two instances for the common hardware resource could cause problems. That makes the exercise worse than pointless.

Another example is when you want two or more RFID readers. Each one would need its own instance of the RFID class. As you pass the pin numbers to the class that you are going to use there is no hardware conflict.

Another is using the AdaFruit neopixel library, you can define two totally different strings of LEDs.

Basically if you have to ask the question you are fundamentally not understanding what classes do and why they are different from functions.

Also, with some libraries you can't create multiple instances because these employ a mechanism to prevent it. For example, a DS3231 library instantiates itself with a specific name and this can happen only once. This makes sense because, except with a hardware trick, you can have only one DS3231 device on an I2C bus because it has a single, fixed I2C address.
There are other such mechanisms to prevent multiple instances. See for example: Explain C++ Singleton design pattern.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.