Serial port access from library

Status
Not open for further replies.

Kirah

Member
I need to write an arduino library that can be instanciated multiple times, with different hardware serial ports as targets.

I've seen that libraries that are receive-only like TinyGPS go around the complexity by letting you handle the serial port in your main sketch and just expect you to push received chars to it. Mine however need to both read and write to the port, so that approach doesn't work, or it would be somewhat dirty to implement a function to get any pending bytes form the library and send them in the main sketch.

What would be the correct way to tell the port I want to use to the constructor of the class in my library?
 
Recommend you follow Firmata's example.

https://github.com/firmata/arduino/blob/master/Firmata.cpp#L128

Create a begin() function that takes a Stream or HardwareSerial reference, then store it as a Stream pointer for use by the rest of the library.

Avoid code in your constructor which deals with other classes. While that usually works with Teensy, because we use constexpr constructors, it tends to go quite badly on many other boards if you hit the "c++ static initialization order fiasco".

Also generally recommend using constexpr on your constructor, if your design can work within the limits constexpr imposes. Those limits *really* help the compiler to optimize programs which use your library.
 
Status
Not open for further replies.
Back
Top