This code allows you to use any library that inherits the Print object. [ethernet serial softwareserial etc etx]
class MyLibrary {
public:
//pass a reference to a Print object
MyLibrary( Print &print ) {
printer = &print; //operate on the adress of print
}
void test() {
printer->println("Hello library with serial connectivity!");
}
private:
Print* printer;
};
MyLibrary myLibrary(Serial);
void setup() {
Serial.begin(9600); //initialize Serial here
myLibrary.test();
}
void loop() {
}
This code explicitly expects a Serial object
class MyLibrary {
public:
//pass a reference to a Print object
MyLibrary( HardwareSerial &print ) {
printer = &print; //operate on the adress of print
printer->begin(9600);
}
void test() {
printer->println("Hello library with serial connectivity!");
}
private:
HardwareSerial* printer;
};
MyLibrary myLibrary(Serial);
void setup() {
myLibrary.test();
}
void loop() {}
I always go with the first unless there is a reason for not allowing anything other than serial based objects.
I'm currently writing a library to use the pins of a second arduino board connected via serial. It's a project for school. And my teacher told me that he isn't able to help me with things like that ;).
Another question: I used the first method. Is it possible to write the Serial.begin(9600); into the MyLibrary function? You need know, I am a bloody newby in arduino programming.
Is there any way to make library accepting Serial or NewSoftSerial object ?
Of course there is. One of C++'s biggest features is function overloading. Simply provide two methods with the same name, but different argument types. One method will accept a Serial instance. The other will accept a NewSoftSerial instance.
The rest of the functions will need to know which method (hardware or software) was used, so the correct instances (hardware or software) to invoke methods (available(), read(), etc.) for.