Question

I'm iterating over hardware serial ports and I'd like to print some status information about which port is currently in use. How do I print the name of the HardwareSerial type? some sample code:

HardwareSerial *possible_ports[] = {&Serial2, &Serial3};
int port_count = 2;
for (int i=0; i<port_count; i++) {
    Serial.print("using: ");
    Serial.println(*possible_ports[i]);
}

the compilation error when trying this:

"no known conversion for argument 1 from 'HardwareSerial' to 'const Printable&'"
Was it helpful?

Solution

well, as the compiler is telling you, you can't print a HardwareSerial, because it makes no sense.

Though, you're not taking the right approach for your problem, because this is a folded problem:

  • depending on the hardware, you may have a different number of serial ports ;
  • in the settings you set up or not the serial ports.

For the first point, there's not much you can do, everything is setup at compile time, and that's what you'll have to implement: different usecases depending on different AVR.

HardwareSerial *possible_ports[] = {
#if defined(UBRRH) || defined(UBRR0H)
&Serial,
#endif
#if defined(UBBR1H)
&Serial1, 
#endif
#if defined(UBBR2H)
&Serial2,
#endif
#if defined(UBBR3H)
&Serial3
#endif
};

For the second point, I don't think there's anything to test that in the HardwareSerial class, though you can do it yourself:

bool serial_is_configured() {
    return (_BV(TXEN0) & UCSRB == _BV(TXEN0));
} 
bool serial1_is_configured() {
    return (_BV(TXEN1) & UCSRB == _BV(TXEN1));
} 
// ...

cf source code of HardwareSerial:

in there:

  • cbi() clears a bit
  • sbi() sets a bit

HTH

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top