I'm trying to creaper class wraper to use an Stream
object but I've an error when I try to compile.
My .h
file :
#include <Arduino.h>
class TestSerialListener {
public:
TestSerialListener(Stream &serial);
void testPrint(void);
private:
bool _listener_start;
Stream &_serial;
void startListener(void);
};
my cpp
file
#include "TestSerialListener.h"
#include <Arduino.h>
TestSerialListener::TestSerialListener(Stream &serial) : _serial(serial)
{
}
void TestSerialListener::testPrint(){
_serial.begin(115200); <---------- error compilation
_serial.println("test");
}
void TestSerialListener::startListener(void)
{
if(!_listener_start){
_listener_start = true;
}
}
And when i try to compile it I got this error : error: 'class Stream' has no member named 'begin'
Why I can't use begin()
in my classe ?
1 Answer 1
the begin()
method is defined in the HardwareSerial
class, not in Stream
. You can look that up yourself in your Arduino installation. For me these files are placed under ~/.arduino15/packages/arduino/hardware/avr/1.8.6/cores/arduino/
and are named Stream.h
and HardwareSerial.h
.
And if you think about it, this is quite logical. The Stream
class can represent any object, that can stream data. It doesn't know anything about how exactly the data is streamed on a hardware level. It just provides the convenient functions for handling the data. The HardwareSerial
class then derives from Stream
to get those data handling methods and adds its own methods to handle the hardware side of the problem, including setting a baudrate.
When providing a Stream
reference to a class constructor you want to begin()
the corresponding object outside of the class, before you start to stream any data through it. Doing it this way makes your class widely usable, since you could use any Stream
object, even a file on an SD card.
So move the begin()
line from your class to the setup()
function in your main code.
For reference: Juraj showed the inheritance between the classes in his answer to this question. Have a look at it, since it is quite enlightening.
Stream
class has no method namedbegin
". Does this answer your question?SerialUSB.begin(115200)
in my sketch ? @EdgarBonetSerialUSB
does have a method namedbegin
. SomeStream
-derived classes can have such a method, It's just not something you can expect from anyStream
object.