I have a question for all you seasoned programmers.
I made a library that writes data to serial ports depending on which chip I'm using sometimes I use a ATM328p sometimes ATM2560 sometimes others. Since the 328P has only one serial this isn't a problem but when I use the 2560 I have 4 serial ports and sometimes my projects use all 4 of them.
The solution I found was to define something like this:
My question, is there another method to accomplish the same task like passing a variable with the function or something that doesn't require code duplication? Something like this (I know this doesn't work) SerialX.print(data);
Your class constructor or begin() method should take a Stream parameter. Stream is the class that sits behind Serial. It also sits behind most LCD libraries, software serial and I2C so your class could possibly talk to those devices as well.
#include <MyClass.h>
MyClass MyObject;
setup() {
//SERIAL_PORT_MONITOR is a constant defined by Arduino to refer to whatever serial port is connected to the serial monitor
SERIAL_PORT_MONITOR.begin(9600);
MyObject.begin(SERIAL_PORT_MONITOR);
}
loop() {
MyObject.doSomething();
}