Skip to content
luni64 edited this page Mar 10, 2020 · 13 revisions

USB Serial

To communicate to a PC or any other USB host via USB Serial you can use the Serial object. The following example shows how to print the current value of millis() every 100ms. Please note that there is no need to set a baud rate. Serial communicates with the USB host via a Serial emulation. Data will always be transmitted with full USB speed.

void setup()
{
   // no baudrate setting requried for USB serial
}

void loop()
{
   Serial.println(millis());
   delay(100);
}

Since Teensies boot up very fast they will be running your user code before the PC can detect the connection of the Teensy and load the corresponding drivers. Thus, it can happen that your code sends out data via Serial before the PC can receive them. To avoid this you can easily check if the USB host already established the connection.

void setup()
{
   while(!Serial){}  //wait until the connection to the PC is established
   Serial.println("Start");
}

void loop()
{
}

This code works nicely but if you do not connect the Teensy to an USB Host the while(!Serial){} will wait forever and the rest of your code will never start, which can be very confusing. To allow for start even if no PC is connected you can add a timeout the connection checking:

void setup()
{
   while(!Serial && millis() < 500){}  //wait (at most 500 ms) until the connection to the PC is established 
   Serial.println("Start");
}

void loop()
{
}

Hardware Serial

TBD

Clone this wiki locally