0

I wish to know if there is a way to use a single property Serial0 to hold a HardwareSerial or a SoftwareSerial or other class instances supporting basic methods such as available(), read() and write(), in order to make a CustomSerial Class (polymorphism?).

class CustomSerial{
 <GenericSerial??> Serial0;
 char c;
 void read(void){
 c=Serial0.read();
 }
};

The calls should be:

CustomSerial SerialCus;
int n=SerialCus.available();
char c=SerialCus.read();
SerialCus.write(c);

What should I use as GenericSerial class, or what should be the proper use? I tried the Stream class (as the answer pointed), but for some reason the functionality is not preserved (it writes unknown characters). Should indeed Stream be the generic class I need for this?

Greenonline
3,1527 gold badges36 silver badges48 bronze badges
asked Aug 30, 2018 at 16:02
1
  • 1
    If you can not make a common class, then you can use a template. If the class (any class) has a .available() and .read() and .write(), then the compiler fills in the used class. Commented Aug 30, 2018 at 16:40

1 Answer 1

3

A base type for Arduino hardware serial classes, SoftwareSerial and other software serial classes and some other Arduino classes is Stream (reference). Stream.h on GitHub

enter image description here

class CustomSerial {
private:
 Stream &stream;
public:
 CustomSerial(Stream &_stream) : stream(_stream) {}
 int read() {
 return stream.read();
 }
 int available() {
 return stream.available();
 }
 int peek() {
 return stream.peek();
 }
 void write(byte b) {
 stream.write(b);
 }
};
SoftwareSerial Serial0(10, 11);
CustomSerial SerialCus(Serial0);
void setup() {
}
void loop(){
 if (SerialCus.available()) {
 char c = SerialCus.read();
 SerialCus.write(c);
 }
}
answered Aug 30, 2018 at 16:05
4
  • I indeed used Stream for defining the property, but for some reason, this do not work the same way as using HardwareSerial, hence i have been unable to extend it for SoftwareSerial instances. Commented Aug 30, 2018 at 16:31
  • 1
    @hyprfrcb, I added code to the answer Commented Aug 30, 2018 at 16:51
  • This setting works perfect!... And also address how to use the Stream references... :) Commented Aug 30, 2018 at 19:22
  • 1
    The AltSoftSerial uses the Stream as well. Commented Aug 31, 2018 at 5:27

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.