You are viewing an older revision! See the latest version
USBSerial
The USBSerial interface is used to emulate a serial port over USB. You can use this serial port as an extra serial port or as a debug solution. It's also a great solution to easily communicate between your mbed and a computer.
The USB connector should be attached to p31 (D+), p32 (D-) and GND. You can also connect the USB power to VIN to power the mbed when connected.
Driver required on Windows!
On Windows, you need a configuration file. You can download this archive containing a .inf file. Extract it.
When you plug your USBSerial serial device, Windows will try to find an existing driver for it without success. After this step, go into the device manager to find the unknown device:
- Right click on the device
- Update driver software
- Click on "Browse my computer for driver software"
- Indicate the path of serial.inf extracted previously and click next.
- Accept the warning and you should have a virtual port (called Mbed Virtual Serial Port in device manager) over USB!
As product_id and vendor_id are hardcoded in the .inf file, if you don't want to use default values, you will have to change them in your program AND in the .inf file.
Hello World¶
USBSerial Hello World!
#include "mbed.h" #include "USBSerial.h" //Virtual serial port over USB USBSerial serial; int main(void) { while(1) { serial.printf("I am a virtual serial port\r\n"); wait(1); } }
Import programUSBSerial_HelloWorld
USBSerial Hello World
API¶
Import library
Public Member Functions |
|
USBSerial (uint16_t vendor_id=0x1f00, uint16_t product_id=0x2012, uint16_t product_release=0x0001) | |
Constructor.
|
|
virtual int | _putc (int c) |
Send a character.
|
|
virtual int | _getc () |
Read a character: blocking.
|
|
uint8_t | available () |
Check the number of bytes available.
|
|
bool | writeBlock (uint8_t *buf, uint16_t size) |
Write a block of data.
|
|
template<typename T > | |
void | attach (T *tptr, void(T::*mptr)(void)) |
Attach a member function to call when a packet is received.
|
|
void | attach (void(*fn)(void)) |
Attach a callback called when a packet is received.
|
More example¶
In this example, the program waits a line on the virtual serial port. When it receives a line, it sends it to the usual mbed serial port (the one used to flash a new program) and to the virtual one.
USBSerial echo
#include "mbed.h" #include "USBSerial.h" //Virtual serial port over USB USBSerial serial; Serial pc(USBTX, USBRX); int main(void) { uint8_t buf[128]; while(1) { serial.scanf("%s", buf); serial.printf("recv: %s", buf); pc.printf("recv: %s\r\n", buf); } }
Import programUSBSerial_Echo
USBSerial echo example