Can you pass a serial port as a parameter?

Im working with a sensor that uses serial communication, and to use it and so the code is more legible, I just made a class for the sensor.

The thing is that right now its connected to Serial, and so it's hardcoded inside it's methods to call for Serial, but if I decide to move it to another port, or use software serial, it would be ideal to just change the declaration so it's something like "Sensor sensor(serial_port);"

How can you pass the serial port as a parameter, or get a pointer/reference to it and use that in my methods?

You can pass it by reference or pointer. Here's a forum thread about it.

HardwareSerial and SoftwareSerial both inherit behavior from Stream (which inherits behavior from Print). If you pass the serial port as a "Stream" (pointer or reference) then it will work with both hardware and software serial ports.

void function1(Stream &serialport)
{
   serialport.println("In function1()");
}

void function2(Stream *serialport)
{
   serialport->println("In function2()");
}

void setup()
{
   function1(Serial);
   function2(Serial);
}
1 Like

Passing it by reference as a Stream object is the normal way of doing it (as johnwasser noted), but you can also overload your functions with all different types of possible serial objects available or even use a template.

1 Like