I am trying to create a library to use in Arduino IDE and I would like to include the hardware serial setup in it.
I have not yet written anything yet but as a draft my h file would be:
//what library to include?
Class MyClass{
//constructor
MyClass(uint8_t hw_s, unsigned long baud);
}
and in my cpp file:
MyClass::MyClass(uint8_t hw_s, unsigned long baud){
if(hw_s==0) Serial.begin(baud);
else if(hw_s==1) Serial1.begin(baud);
else if(hw_s==2) Serial2.begin(baud);
else if(hw_s==3) Serial3.begin(baud);
}
is this all I would like to do or do I need some extra lines of code or libraries to be able to include Hardware serial into my library?
thanks! just to confirm that's would be the only library I would need to be able to use hardware serial from my library, right?
sherzaad:
thanks! just to confirm that's would be the only library I would need to be able to use hardware serial from my library, right?
Or, since HardwareSerial (and softwareSerial) are derived from Stream, you can just pass a pointer to a HardwareSerial or Stream object to your class.
like:
class MyClass{
public:
MyClass(Stream& str) : stream (str){};
void doSomething(void){stream.print("Hello World");};
protected:
Stream& stream;
};
MyClass myClass(Serial); // or Serial2, Serial3....
void setup()
{
Serial.begin(9600);
delay(1000);
myClass.doSomething();
}
void loop(void)
{
}