Usb Serial (communication Class 7
Home | Products | Teensy | Blog | Forum |
Universal Serial Bus Communications Class Subclass Specification for Mobile Broadband Interface Model (developed pursuant to USB-IF IP Agreement for Network Control Model Rev 1.0 and subsequently renamed as above) Revision 1.0 November 14, 2011. To be able to use the HardwareSerial class (or at least a compatible interface) you must connect an USB to serial adapter to the port (p.e. FTDI, PL-2303, etc.). For the mentioned chips and for the ACM interface (which the UNO, Leonardo, Mega2560 and others use) the USB host shield library has support already, but that support doesn't emulate a.
You are here:TeensyTeensyduinoUSB Serial |
| Teensyduino provides a Serial object which is compatible with theSerial object on standard Arduino boards. Usually Serial is usedto print information to the Arduino IDE Serial Monitor.Unlike a standard Arduino, the Teensy Serial object always communicatesat 12 Mbit/sec USB speed. Many computes, especially older Macs, can notupdate the serial monitor window if there is no delay to limit the speed!In this example, 'Hello World...' is printed once per second. The Teensy does not actually become a serial device until your sketch is running,so you must select the serial port (Tools -> Serial Port menu) afteryour sketch begins. Standard Serial FunctionsAll of the standard Serial functions are supported.Serial.begin()Initialize the Serial object. The baud rate is ignored and communicationalways occurs at full USB speed.Serial.print() and Serial.println()Print a number or string. Serial.print() prints only the number or string, andSerial.println() prints it with a newline character.On a standard Arduino, this function waits while the data is transmitted. With Teensyduino,Serial.print() and Serial.println() typically return quickly when the message fits within theUSB buffers. See Transmit Buffering below.Serial.write()Transmit a byte. You can also use Serial.write(buffer, length) to send more thanone byte at a time, for very fast and efficient data transmission.Serial.available()Returns the number of received bytes available to read, or zero if nothing has been received.On a standard Arduino, Serial.available() tends to report individual bytes, whereaslarge blocks can become instantly available with Teensyduino.See Receive Buffering below for details. Usually the return value from Serial.available() should be tested as a boolean, eitherthere is or is not data available. Only the bytes available from the most recentlyreceived USB packet are visible. SeeInefficient Single Byte USB Packets below for details. Serial.read()Read 1 byte (0 to 255), if available, or -1 if nothing available. Normally Serial.read()is used after Serial.available(). For example:Serial.flush()Wait for any transmitted data still in buffers to actually transmit. If no data is waiting in a buffer to transmit, flush() returns immediately.Arduino 0022 & 0023: flush() discards any received data that has not been read. Teensy USB Serial ExtensionsTeensyduino provides extensions to the standard Arduino Serial object, soyou can access USB-specific features.Serial.send_now()Transmit any buffered data as soon as possible.See Transmit Buffering below.Serial.dtr()Read the DTR signal state. By default, DTR is low when no software hasthe serial device open, and it goes high when a program opens the port.Some programs override this behavior, but for normal software you can useDTR to know when a program is using the serial port.On a standard Arduino, the DTR and RTS signals are present on pins of theFTDI chip, but they are not connected to anything. You can solderwires between I/O pins and the FTDI chip if you need these signals.Serial.rts()Read the RTS signal state. USB includes flow control automatically,so you do not need to read this bit to know if the PC is ready to receiveyour data. No matter how fast you transmit, USB always manages buffersso all data is delivered reliably. However, you can cause excessive CPUusage by the receiving program is a GUI-based java applicationlike the Arduino serial monitior!For programs that use RTS to signal some useful information, you can readit with this function. Serial.baud()Read the baud rate setting from the PC or Mac. Communication is alwaysperformed at full USB speed. The baud rate is useful if you intend tomake a USB to serial bridge, where you need to know what speed the PCintends the serial communication to use.Serial.stopbits()Read the stop bits setting from the PC or Mac. USB never uses stopbits.Serial.paritytype()Read the parity type setting from the PC or Mac. USB uses CRC checkingon all bulk mode data packets and automatically retransmits corrupteddata, so parity bits are never used.Serial.numbits()Read the number of bits setting from the PC or Mac. USB always communicates8 bit bytes.USB Buffering and Timing DetailsUsually the Serial object is used to transmit and receive data withoutworrying about the finer timing details. It 'just works' in most cases.But sometimes communication timing details are important, particularlytransmitting to the PC.Transmit BufferingOn a standard Arduino, when you transmit with Serial.print(), the bytesare transmitted slowly by the on-chip UART to a FTDI USB-serial converterchip. The UART buffers 2 bytes, so Serial.print() will return when allbut the last 2 bytes have been sent to the FTDI converter chip, which inturn stores the bytes into its own USB buffer.On a Teensy, Serial.print() writes directly into the USB buffer. Ifyour entire message fits within the buffer, Serial.print() returns toyour sketch very quickly. Both Teensyduino and the FTDI chip hold a partially filled bufferin case you want to transmit more data. After a brief timeout, usually8 or 16 ms on FTDI and 3 ms in Teensyduino, the partially filled bufferis scheduled to transmit on the USB. The FTDI chip can be made to immediately schedule a partially filledbuffer by toggling any of the handshake lines (which are not connectedon a standard Arduino board). It can also be configured (by the PCdevice driver) to schedule when an 'event character' is received.Normally it is difficult to control when the FTDI chip schedules itspartially filled transmit buffer. Teensyduino immediately schedules any partially filled buffer to transmitwhen the Serial.send_now() function is called. All USB bandwidth is managed by the host controller chip in your PC orMac. When a full or partially filled buffer is ready to transmit, itactual transmission occurs when the hostcontroller allows. Usually this host controller chip requests anyscheduled transfers 1000 times per second, so typically actual transmissionoccurs within 0 to 1 ms after the buffer is scheduled to transmit. Ifother devices are using a lot of USB bandwidth, priority is given to'interrupt' (keyboard, mouse, etc) and 'isychronous' (video, audio, etc)type transfers. When the host controller receives the data, the operating system thenschedules the receiving program to run. On Linux, serial ports openedwith the 'low latency' option are awakened quickly, others usually waituntil a normal 'tick' to run. Windows and MacOS likely add processscheduling delays. Complex runtime environments (eg, Java) can alsoadd substantial delay. Receive BufferingWhen the PC transmits, usually the host controller will send at leastthe first USB packet within the next 1ms. Both Teensyduino and theFTDI chip on Arduino receive a full USB packet (and verify its CRC check). TheFTDI chip then sends the data to a standard Arduino via slow serial.A sketch repetitively calling Serial.available() and Serial.read() willtend to see each byte, then many calls to Serial.availble() will returnfalse until the next byte arrives via the serial communication.On aTeensy, the entire packet, up to 64 bytes, becomes available all at once.Sketches that do other work while receiving data might depend onslow reception behavior, where successive calls to Serial.available()are very unlikely to return true. On a Teensy receiving large amountsof data, it may be necessary to add a variable to count the number ofbytes processed and limit the delay before other important work mustbe done.Inefficient Single Byte USB PacketsWhen transmitting, Serial.write() and Serial.print() group bytes from successivewrites together into USB packets, to make best possible use of USB bandwidth. Youcan override this behavior using Serial.send_now(), but by default multiple writesare merged to form packets.Microsoft Windows and Linux unfortunately do NOT provide a similar function whentransmitting data. If an application writes inefficiently, such as a single byteat a time, each byte is sent in a single USB packet (which could have held 64 bytes).While this makes poor use of USB bandwidth, a larger concern is how this affectsbuffering as seen by Serial.available(). The USB hardware present in Teensy can buffer 2 USB packets. Serial.available()reports the number of bytes that are unread from the first packet only. If thepacket contains only 1 byte, Serial.available() will return 1, regardless ofhow many bytes may be present in the 2nd package, or how many bytes may be waiting in more packets still buffered by the PC's USB host controller. This code will not work on Teensy when the PC transmits the expected 11 byte messagein more than 1 USB packet. This code can be rewritten to always read a byte when Serial.available() returns non-zero. Of course, there are always many ways to write a program. The above versions lookfor a '@' character to begin the message, but do not handle the case where additionalbytes (incorrectly) appear before the 10 digit number. It is also not necessary tostore the entire message in a buffer, since the work can be done as the bytes areread. Here is a more robust and more efficient version. |
Home | Products | Teensy | Blog | Forum |
Usb Serial Communication
You are here:TeensyHow-To TipsTroubleshoot |
Usb Serial (communication Classic
| If your question isn't answered here, please post on the forum. PJRC does monitor the forumand every attempt is made to answer customer questions. You must post code or details needed to reproduce the problem.Please readthe posting guidelines.Just a few minutes to compose a detailed question usually results in much better help. The Teensy Quick Reference: Code Examples, Tips and Tricks list has a list useful resources and solutions for many common projects. The Most Common Problems#1: LED Blinks But No USB Communication: Many cell phones are sold withcharging-only cables. They have only 2 wires for power, but are missingthe 2 data wires. Try another USB cable, ideally one known to work for USB.#2: No COM Port or Serial Device Seen: Teensy uses HID protocol for uploading,not serial. Brand new Teensy boards are shipped with the LED blink example compiledto appear as RawHID. You must program Teensy at least once from Arduino. The COMport (Windows) or Serial Device (Mac, Linux) appears only after Teensy beginsrunning your program. Regular Arduino boards are always serial. Teensy uses HIDand supports many protocols. To use serial, make sure the Tools > USB Type menuis set to 'Serial', and understand Teensy only becomes a serial device when it runsyour program built with this setting. #3: Dead (usually overheating) Main Chip: More than 4 volts applied to the3.3V power pin instantly kills a Teensy LC or 3.2. Be extremely careful if connectingcircuits to Teensy using both VIN(5V) & 3.3V pins, or when using any external powersupply. Loose wires between Teensy and other electonics accidentally touching arethe most common way Teensy fails. Just a few extra minutes to cover exposed leadsand mechanically secure loose wires, especially if they can easily unplug from asolderless breadboard, can save you from an unpleasant and costly 'learning experience'. Unreliable CommunicationSome USB hubs have trouble handling the rapidsequence of connect/disconnect events when programming Teensy.Most hubs workfine, but the few that do not can cause very strange problems.If you experience trouble, always try connecting Teensy directly with a qualityUSB cable.Teensy 3.0 Not Recognized by Teensy LoaderTeensy Loader 1.07 is the first version to support Teensy 3.0.You can check the version using Help > About.Version 1.07 is part of theTeensyduino installer. Itautomatically runs when you click Upload or Verify in Arduino.Brand New Teensy Not RecognizedWhen a brand new Teensy has never been recognized by Teensy Loader,follow these steps.
Teensy Not Recognized by Teensy LoaderA previously working board may seem to be dead, but the problem may simply be codeon your Teensy which confuses your PC's USB port.
On Windows systems, 'strange' problems are occasionally reported, whereWindows will not detect new devices. It does not seem to be unique toTeensy. Creating a new user account sometimes solves the problem. Pluggingthe cable into different USB ports can also help. Rebooting is always a goodidea. The best approach is to try on a Mac or Linux machine, or a differentWindows machine. No Serial Port While ProgrammingThis is normal. Teensy is NOT natively a serial device.Arduino boards appear as a serial device for all programmingand communication. Arduino remains connected as a serial device whileit reboots. Teensy is a native USB device. Experience troubleshootingArduino does not apply to Teensy! During programming, Teensy appears as a HID device.When Teensy reboots, electrically your computer sees Teensy disconnect, asif the cable were physically unplugged. When Teensy begins running yourprogram, the USB is disconnected. The fast and slow LED blink examples do not enable the USB port. When programs do use USB, type of device Teensy becomes depends on the codeyou have loaded. Your computer will see a new USB device connect when yourprogram begin using the USB port.In Arduino, the device type is controlled by the Tools > USB Type menu.In C language, the USB code you use determine the type of device. The hid_listenprogram only responds to specific C programs. While troubleshooting, you mustlook for the type of device which your program implements. TODO: list of C code and Teensyduino device types, VID/PID numbers for each. Pushbutton Does Not Reset ApplicationThe pushbutton lets you to manually putTeensy into programming mode. With Arduino, this happens automaticallywhen you click Upload. But if your code disables the USB port, or disables interrupts,or enters a deep sleep mode which stop the CPU, Teensy can not respond to theUSB-based reboot request.Every Teensy is made with a physical pushbutton to allow recovery from anot-responding program. The pushbutton does NOT reset Teensy to restart your application. However, ifTeensy is connected to your computer, andTeensy Loader is running and configured for automatic mode (the default whenused with Arduino), pressing the button will enter programming mode.Teensy Loader will quickly reprogram and restart your Teensy. This restart ofyour application is due to Teensy Loader's 'auto' mode, not only the pushbutton. LED Blinks Green or BlueYou have a counterfeit board. PJRC has never made any Teensy with a greenor blue LED. If you purchased using Ebay and Paypal, we recommend you immediatelybegin a dispute on Paypal's website. Do not bother contacting the seller. Theyhave already scammed many other people with defective boards, but they simply donot care. A dispute on Paypal is the only way you will recover your money. Thesooner you file the dispute, the better your odds of receiving a refund. Werecommend waiting to leave negative feedback until after Paypal returns your money.Large Programs Mysteriously CrashOn Teensy 2.0, the compiler places string constants in RAM. If you have have many, RAMcan run out quickly. In Arduino, you can use F() to cause strings usedwith print() to avoid using RAM.In C language, usually PSTR() is used, and special functions which accessflash memory must be called. Often they have a '_P' suffix. Large data tables or arrays can also cause trouble. If data is constant,PROGMEM and pgm_read_byte() can be used. See theavr-libc manualfor details. Teensy LC, 3.0, 3.1 do not have this problem. Variables defined with 'const'are placed only in flash memory, but can be accessed normally. Only the older8 bit AVR-based boards require these special steps to prevent strings andread-only variables from consuming limited RAM. Windows: Serial Driver Installed But Not UsedOn Windows, even if the serial driver installer hasrun correctly, sometimes Windows will retain old information in its registry andfail to load the driver. The Device Manager will show 'USB Serial' with an error,instead of 'USB Serial (Communication Class, Abstract Control Model)' with a COMport number assigned.These actions usually can cause Windows to re-detect the device and begin usingthe correct driver.
If there is no 'USB Serial' at all, please rememober Teensy only becomes a Serial device when programmed to do so. See 'No Serial Port While Programming' above. Windows 7: Unknown Device (Code 43)Windows 'Code 43' is a mystery. Other devices, even Apple iPod, haveexperienced this problem. The solution seem to be becompletelypowering down, and if a latop, remove the battery for a few minutes. Thissame solution has beenreportedmultiple timeswith success.This code 43 error is a mystery. It might be related to laptops enteringsuspend mode? If you have any insight, please contact us! Pieter Rautenbach found a case where programming the wrong HEX file(compiled for a different chip) causes error 43. Windows: Teensy Loader Window Does Not AppearOn Windows, if multiple monitors are used and then only a single monitoris later used (eg, a laptop used at a docking station), the Teensy Loadermay attempt to appear on the missing monitor. The Teensy Loader appearsin the Windows Task Bar, but not on the screen.
Additional info from Gilbert Hersschens: 'Since you can't see the missing window, you won't know for sure if it's visible or hidden. But you can see this in the context menu. When the window is shown on the missing display, the menu item 'Move' will be active and the item 'Restore' will be greyed out. When it's hidden, it will be just the opposite. You can only move a window in its visible state.To hide or unhide a window, you can click on the icon in the taskbar to toggle its state or use the corresponding menu items in the context menu. Linux: Gentoo & Arch AVR ToolchainThe AVR toolchains provided by Gentoo and Arch are broken. Theycompile .hex files which simply do not work!Starting with version 1.0.1, Arduino downloading from www.arduino.cchas a known-good toolchain.If running avr-gcc with a makefile, download Arduino 1.0.1and set your $PATH to access the toolchain inarduino-1.0.1/hardware/tools/avr/bin directory. Linux: Long Delay Before USB Serial DetectedOn some Linux systems, USB Serial is detected very slowly. The kerneldetects the device quickly (usually seen with 'tail -f /var/log/messages'),but the device files do not appear for a very long time.Edit '/lib/udev/rules.d/77-nm-probe-modem-capabilities.rules',adding this line: Linux: Many Duplicate Device Names with Ubuntu 9.10On Ubuntu 9.10 (and maybe other systems), when using a serial device type,the kernel assigns a new number each time, /dev/ttyACM0, /dev/ttyACM1, /dev/ttyACM2, etc.This is caused by the Gnome Modem Manager, which holds the port in (as far as the kerel isconcerned) use even after you have reset the Teensy and the port no longer exists.The simplest solution is to uninstall Modem Manager, and restart the network manageror simply reboot. You could also try deleting /usr/lib/ModemManager/libmm-plugin-generic.so andof course reboot. This might leave Modem Manager able to work with most modems,but not interfere with Teensy. Modem Manager's troublesome probing and inability to configure exclusionsfor specific device is a known bug.Hopefully it will be fixed in future releases. Windows: Teensyuino Installer Unable To WritePlease temporarily disable any anti-virus software. Many 'heuristic' anti-virusprograms do not like one program writting to another. The Teensyduino installerneeds to modify many files inside the Arduino software. 'Windows Essential Security'has been reported to cause trouble. |