Using Arduino Leonardo as an USB/UART adapter

Mi 22 April 2015
By Uli Köhler

In C/C++

In contrasts to older designs like the Arduino Uno, the Arduino Leonardo features a separate connection Serial1 for TTL-UART whereas Serial is used for the USB CDC UART interface.

This allows one to use the Leonardo as an USB/UART bridge without having to resort to more expensive boards like the Arduino Mega 2560. In order to do this, use this sketch which can also be modified to provide an intelligent UART bridge.

Remember to adjust the baudrate for your application. This version of the sketch does not support automatic baudrate selection via the CDC peripheral.

LeonardoUSBUARTBridge.ino download
/*
  USB/UART bride for Arduino Leonardo
  Originally written by Uli Koehler in 2015
  Published on techoverflow.net

  Revision 1.0

  Published under the public domain (CC 1.0 Universal)
 */

void setup() {
  // Adjust baudrate here
  const int baudrate = 115200;
  Serial.begin(baudrate);
  Serial1.begin(baudrate);
  //Wait until USB CDC port connects
  while (!Serial) {
  }
}

void loop() {
  //Copy byte incoming via TTL serial
  if (Serial1.available() > 0) {
    Serial.write(Serial1.read());
  }
  //Copy byte incoming via CDC serial
  if (Serial.available() > 0) {
    Serial1.write(Serial.read());
  }
}