Using Arduino Leonardo as an USB/UART adapter

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.

/*
  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
  Serial.begin(115200);
  Serial1.begin(115200);
  //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());
  }
}

Update 2017-09-13: Fix const int baudrate being a 2-byte int on avr-gcc and therefore not being able to take 115200 as a number. Thanks Andrei Kovari!