I am building a Library for a serial device, but I want to rely on the “serialEvent” callback.
So basically I want to move all the serial code to its own object. I have seen libraries that pass by value the serial port upon instancing it in the main cpp file. But I haven’t seen how I can pass to my objet the “Serial” object and the “serialEvent” from the main cpp file to my file (Object).
Can someone point me in the right direction and if you think this is appropriate.
If you only need to print to the port, make the parameter to your library a Stream&. You can pass Serial, Serial1, etc. and it will be cast to a Stream and you can call println, printlnf, etc. on it.
If you need change settings like baud rate, use USARTSerial&. Note, however, that you can’t pass Serial (the USB serial port) because that’s a USBSerial&. Both have Stream as a base class.
I wouldn’t try to use serialEvent from a library. I’d just make a loop method in your library and call it from your actual loop and check the serial port from your library using available().
You need to return from your library loop as quickly as possible, presumably after you’ve read all of the serial data. It would work just like the real loop function.