How should I inherit from Stream
, for creating a new class MySerial
able to be initialized from a Stream0
instance?.
The error so far is: "cannot declare variable 'mySerial' to be of abstract type 'MySerial'"
.
If I make a class MySerial
not inheriting, but adding a property Stream
, everything works fine, except the new call mechanism for the resend()
function, created to accept Stream
instances.
EDIT: This is the edited code. Current error is: "expected unqualified-id before '=' token"
.
MySerial.h
class MySerial:public Stream{
private:
int param;
public:
MySerial(){}; // OK
MySerial(Stream &Serial0){MySerial=&Serial0} // Here is the question
// Stream Implementation
int available(){return available();}
int read(){return read();}
int peek(){return peek();}
size_t write(uint8_t c){return write(c);}
using Print::write;
};
MySerial.ino
#include <MySerial.h>
#include <SoftwareSerial.h>
SoftwareSerial swSerial(6,7);
MySerial mySerial(swSerial);
void setup(){}
void loop(){
if (mySerial.available()){
c=mySerial.read();
resend(mySerial,c);
}
}
// This function should accept any Stream: SoftwareSerial, MySerial, Serial...
void resend(Stream &Stream0, char c){
Stream0.write(c);
}
1 Answer 1
The Stream
class has pure virtual methods which must be implemented in derived not abstract class.
The pure virtual method from base class Print
is:
virtual size_t write(uint8_t) = 0;
The pure virtual methods from Stream
are:
virtual int available() = 0;
virtual int read() = 0;
virtual int peek() = 0;
additionally add in your class the line
using Print::write;
to pull in overloaded methods write(str) and write(buf, size) fromPrint
Here I have an example of a simple class derived from Stream
.
EDIT: Most of your question seemed to focus on wrapping some Stream implementation. Now I see that you maybe want to enhance the SoftwareSerial class and add a new method in the inherited class. It is simple:
MySerial.h
#ifndef _MYSERIAL_H_
#define _MYSERIAL_H_
#include <SoftwareSerial.h>
class MySerial: public SoftwareSerial {
private:
int param;
public:
MySerial(uint8_t receivePin, uint8_t transmitPin) :
SoftwareSerial(receivePin, transmitPin, false) {
param = 0;
}
void resend(char c) {
write(c);
}
};
#endif
MySerial.ino
#include "MySerial.h"
MySerial mySerial(6, 7);
void setup() {
mySerial.begin(9600);
}
void loop() {
if (mySerial.available()) {
int c = mySerial.read();
mySerial.resend(c);
}
}
-
Thanks. I made the indicated changes. I am still troubled with the constructor declaration, for taking a Stream object as initial object.Brethlosze– Brethlosze2019年03月22日 15:13:04 +00:00Commented Mar 22, 2019 at 15:13
-
Your answers are great just as the last time. I will study this code further.Brethlosze– Brethlosze2019年03月22日 16:37:31 +00:00Commented Mar 22, 2019 at 16:37