Obscure Arduino tips #4

I've started using the ESP32-C3 a lot recently because it's a good replacement for the ESP8266 with slightly more usable GPIO pins, no onerous pin strapping issues and native USB for flashing and debug output. It ticks all my boxes for a general purpose microcontroller and one day I might even use the Bluetooth capability.

One thing that is a minor irritation is the number and naming of the hardware Serial ports changes depending on whether you enable 'USB CDC on boot' and this isn't immediately obvious how to deal with.

With USB CDC on boot enabled you have...

  • Serial - USB CDC
  • Serial0 - hardware serial UART0
  • Serial1 - hardware serial UART1
Without it enabled you have...
  • Serial - hardware serial UART0
  • Serial1 - hardware serial UART1
  • USBSerial - USB CDC
The 'other' Serial ports don't exist other than when you choose the relevant compile option so you'll get compilation fails when swapping from enabled to disabled for the USB CDC.

Which means writing code that works in both situations needs some mediation. I had a poke around and found the relevant pre-processor directive that helps smooth this over.

Add some code like below and it handles the problem.

    #define SERIAL_DEBUG_PORT Serial
    #define SERIAL_DEBUG_PORT USBSerial

You can then just use

SERIAL_DEBUG_PORT.println("Hello World");


No comments: