TransWikia.com

Serial port usage in code

Arduino Asked by Joe Mann on December 11, 2021

I want to write a function that defines a serial port based on a flag but I’m not sure it’s possible.

For example:

void writeToSerial(bool useSerial1)
{
   SerialPortClass serialPortObject; // Is there some way of defining a generic Serial port object and reusing it below?

   if (useSerial1)
   {
      serialPortObject = Serial1;
   }
   else
   {
      serialPortObject = Serial2;
   }

   serialPortObject.write("test123");
}

2 Answers

This is not a proper answer, but rather a suggestion to reconsider your approach. The code posted in the question is obviously just a simplified example, and printing “test123” is likely not your final goal. I assume what you really want to do is print out some information about some variables. You can then collect these variables into a data structure (a C++ object) and make writeToSerial() a method of this object. The object can the be printed like so:

myDataStructure::writeToSerial(true);   // printed to Serial1
myDataStructure::writeToSerial(false);  // printed to Serial2

In this case, what I suggest is to instead explicitly print() (or println()) the object to the relevant serial port, like this:

Serial1.print(myDataStructure);
Serial2.print(myDataStructure);

This makes the code self-explanatory, and easier to maintain.

Obviously, you cannot just print arbitrary objects this way, as Serial1 and Serial2 would have no idea about how to serialize them. But the thing is, you can teach them! Make your class derive from Printable, implement the virtual printTo() method, and you will be able to print it to any serial port, LCD, or whatever understands print():

class MyDataStructure : public Printable {
public:
    size_t printTo(Print& p) const {
        return p.print("test123");
    }
};

MyDataStructure someData;

void setup() {
    Serial1.begin(9600);
    Serial2.begin(9600);
    Serial1.println(someData);
    Serial2.println(someData);
}

void loop(){}

See the answer to Is it possible to print a custom object by passing it to Serial.print()? for an example with actual data in the object.

Answered by Edgar Bonet on December 11, 2021

According to sources at c:Program Files (x86)ArduinohardwarearduinoavrcoresarduinoHardwareSerial* (on Windows platform), you can use pointer to Stream class (because Serials are inherited from Stream).

So, your function could look like this:

void writeToSerial(bool useSerial1)
{
   Stream* serialPortObject;

   if (useSerial1)
   {
      serialPortObject = &Serial1;
   }
   else
   {
      serialPortObject = &Serial2;
   }

   serialPortObject->write("test123");
}

Answered by Ihor Drachuk on December 11, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP