0

I have a function that accept an HardwareSerial class as argument:

void ProcessLine(HardwareSerial *serial, char *line)
{
    // do something
    serial->write("blablabla");
}

In my code I also have a BluetoothSerial that shares the required functions (i.e. write()) with HardwareSerial.

To avoid to duplicate the code of my ProcessLine() that is quite long, is there a way to "cast" a BlutoothSerial to a HardwareSerial?

1

1 Answer 1

2

No, you don't "cast" between them. Instead you make use of polymorphism.

In the Arduino framework most classes fit into a "tree" with similar classes "hanging off" a common parent "branch". In this case both BluetoothSerial and HardwareSerial, being both serial classes, are both children of the Stream class. Indeed it is this Stream class (which itself is a child of the Print class) which gives these objects most of their functions.

So unless you need access to some function that is specific to the HardwareSerial class (such as the .begin(...) function) you should always work up the tree to the class that provides the most restrictive set of functions that suit your needs. In this case, since you are only printing data, it would be the Print class. If you were reading data you would choose the Stream class.

So if you change your function to accept Print *serial instead of HardwareSerial *serial then it will accept any object that ultimately inherits from the Print object - so any serial objects, any network stream objects, etc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.