Writing a class that can accept hardware serial and usb serial.

nickexists

Active member
I'm trying to write a class to help manage serial communications in my project. I'm trying to make it so that the constructor saves a reference to the serial object it is given and then methods of the class will write to and read from the serial object. The problem is that Serial1 Serial2 and Serial3 are different HardwareSerial objects while Serial is a usb_serial_class object. How can I make my class compatible with both types.

Example:
Code:
class Comms
{
	public:
		Comms(HardwareSerial& serial);
		void floatToBytes(float in);
	private:
		HardwareSerial& _serial;

};

Comms::Comms(HardwareSerial& serial):_serial(serial)
{
}


void Comms::doStuff(int in)
{	
		_serial.write(b);
	}
}
 
try to add this to your Comms class public section

Code:
virtual void begin(uint32_t baud) {_serial.begin(baud);};
 
That didn't seem to change anything. Still getting this error: error: 'class Stream' has no member named 'begin'
 
Last edited:
Yeah, that's one little issue with Stream. It doesn't have begin(). So to use Stream, you need to have the sketch or higher-level code begin(), then pass the object to your library.

Or you can use C++ function overloading, where you create multiple functions that take each type of object, call it's begin() function, and then store it as a Stream pointer. The rest of your code can access it as Stream, but begin() won't be available through the pointer.

But really, is requiring the sketch to call begin(baud) first, and then pass the object after it's begin() such a big problem?
 
That didn't seem to change anything. Still getting this error: error: 'class Stream' has no member named 'begin'

ok, try removing the virtual from the declaration.

it must work, as that will be no different than declaring foo() function for your class.

I have the exact same requirement (to pass a serial object to constructor) and Stream is the only parent class I use and I don't get a compile error.

since the begin function was declared with a parameter, I assume you were calling that function with a parameter and not just begin(). Likewise, if you want to call end(), you must declare it, just like any C class function.

one other thing to try is to remove the reference & in the declaration for _serial.
 
Last edited:
Back
Top