You are viewing an older revision! See the latest version

SerialPC

Getting started

  1. Setup Guide
  2. Downloading a Program
  3. Creating a Program
  4. Communicating with your mbed

Serial Communication with a PC

The mbed Microcontroller can communicate with a host PC through a "USB Virtual Serial Port" over the same USB cable that is used for programming.

This enables you to:

  • Print out messages to a host PC terminal (useful for debugging!)
  • Read input from the host PC keyboard
  • Communicate with applications and programming languages running on the host PC that can communicate with a serial port, e.g. perl, python, java and so on.

Hello World!

Hello World!

#include "mbed.h"              

Serial pc(USBTX, USBRX); // tx, rx

int main() {
    pc.printf("Hello World!\n");
}

Host interface and terminal applications

Your mbed Microcontroller can appear on your computer as a serial port. On Mac and Linux, this will happen by default. For Windows, you need to install a driver:

Windows

See Windows-serial-configuration for full details about setting up Windows for serial communication with your mbed Microcontroller

It is common to use a terminal application on the host PC to communicate with the mbed Microcontroller. This allows the mbed Microcontroller to print to your PC screen, and for you to send characters back.

  • Terminals - Using Terminal applications to communicate between the Host PC and the mbed Micrcontroller

Some terminal programs (e.g. TeraTerm) list the available serial ports by name. However, if you do need to know the identity of the serial port so that you can attach a terminal or an application to it:

  • Windows - Look under the "Ports" section in "Device Manager" (''Start -> Control Panel -> System -> Hardware -> Device Manager''). The name will be ''mbed Serial Port (COMx)'', where ''x'' is the number of the COM port allocated.
  • Mac OS X - Use the command ls /dev/tty.usbmodem*
  • Linux - Use the command ls /dev/ttyACM*

Terminal Applications

Details

Communication over the USB Serial port simply uses the standard Serial Interface, specifying the internal (USBTX, USBRX) pins to connect to the Serial Port routed over USB.

The Serial Interface defaults to a 9600 baud standard serial connection (8 bits, 1 stop bit, no parity), so your host program should be set to the same settings. If you want to communicate at a different standard baud rate, ensure you modify the settings of both the Serial Interface and the Host PC application!

Examples

Echo back characters you type

#include "mbed.h"              

Serial pc(USBTX, USBRX);

int main() {
    pc.printf("Echoes back to the screen anything you type\n");
    while(1) {
        pc.putc(pc.getc());
    }
}

Connect to your mbed Microcontroller with a Terminal program and uses the 'u' and 'd' keys to make LED1 brighter or dimmer

#include "mbed.h"

Serial pc(USBTX, USBRX); // tx, rx
PwmOut led(LED1);

float brightness = 0.0;

int main() {
    pc.printf("Press 'u' to turn LED1 brightness up, 'd' to turn it down\n");

    while(1) {
        char c = pc.getc();
        if((c == 'u') && (brightness < 0.5)) {
            brightness += 0.01;
            led = brightness;
        }
        if((c == 'd') && (brightness > 0.0)) {
            brightness -= 0.01;
            led = brightness;
        } 

    }
}

Pass through characters in both directions between the PC and Serial Port

#include "mbed.h"

Serial pc(USBTX, USBRX);
Serial uart(p28, p27);

DigitalOut pc_activity(LED1);
DigitalOut uart_activity(LED2);

int main() {
    while(1) {
        if(pc.readable()) {
            uart.putc(pc.getc());
            pc_activity = !pc_activity;
        }
        if(uart.readable()) {
            pc.putc(uart.getc());
            uart_activity = !uart_activity;
        }
    }
}

The C stdin, stdout and stderr file handles are also defaulted to the PC serial connection

#include "mbed.h"

int main() {
    printf("Hello World!\n");
}

<<code title="Read in to a buffer">>

  1. include "mbed.h"

DigitalOut myled(LED1); Serial pc(USBTX, USBRX);

int main() { char c; char buffer[128];

pc.gets(buffer, 4);

pc.printf("I got '%s'\n", buffer); }<</code>>

Troubleshooting

If you have having difficulties with USB serial communication:

If you have any problems, or think this tutorial could be improved, please tell us in the Forum!




5 related questions:

48 comments:

06 Sep 2010

Thank you. All done no problems and now I can debug as much as I need.

07 Feb 2011

I recently purchased an M-BED and got through all your information about the Serial PC setup steps. I missed the driver portion that needed to be loaded on my PC. It was a frustrating experience trying to get the device manager to find it. Just needed to keep reading your instructions again and what a wonderful experience when it started working as described. Keep up the good work supporting this excellent tool.

10 Feb 2011

It is incredible!!! I am excited about the versatility of every component of mbed. I am playing every day, and learning more every second.

15 Apr 2011

Using either PuTTY or Hyperterm (pinched from previous windows release) under Windows 7, I'm getting they same problem. Both seem to treat "\n" as only that - a new line. This may be a difference between the *NIX world and the Windows world. I think Windows prefers CR and LF. The effect I'm seeing is the when I write to STDOUT the following "Line1\nLine2\nLine3\n" Hyperterm and putty display

Line1
     Line2
          line3

I'm new to MBED so forgive my ignorance but is there an easy way to get around this without having to change all the print statements?

15 Apr 2011

You can use \r to return to the start of the line, e.g.

PC.printf("Line1\n\rLine2\n\rLine3\n\r");

Will print

Line1
Line2
Line3

Is that what you wanted?

15 Apr 2011

In Putty: Settings-Terminal-Implicit CR in every LF.

15 Apr 2011

Thanks Igor, that did the trick.

08 May 2011

In Example 2 "Connect to your mbed Microcontroller with a Terminal program and uses the 'u' and 'd' keys to make LED1 brighter or dimmer" - how would I output the current value of the brightness variable to the terminal? Is there a 'sprintf()' analogy with mbed?

13 May 2011

Can you clear the screen on the pc with a code?

14 May 2011

Yes you can. Ensure your Terminal program is set up for "VT100 emulation" or "ANSI emulation" (this is usually the default setting) and include the following lines into your program:

    printf("\x1B[2J");    //VT100 erase screen
    printf("\x1B[H");     //VT100 home

Alternatively, use the Cookbook VT100 Terminal driver:

#include "mbed.h"
#include "Terminal.h"
 
Terminal term(USBTX, USBRX); // tx, rx
 
int main() {
    term.cls();
    term.locate(0, 0);
    term.printf("Hello World, mbed calling!");
}
05 Jun 2011

Can I use serial comms on pins tx p9 and rxp10 WITHOUT the USB cable plugged in? As soon as I unplug the USB cable I can no longer do serial communication. i was wanting to use the mbed on a mobile robot. I just want to continually print "hello world" from my mbed to a pc without a usb cable plugged in. i have a working comm port on my windows machine and i've used it many times before. the code below works only when a usb cable is plugged into my mbed.

#include "mbed.h"

Serial device(p9,p10);

int main() {
    device.baud(9600);
    while (1) {
        device.printf("Hello World\n");
        wait(0.2);      
    }
}
17 Jun 2011

user Jay Davey wrote:

Can I use serial comms on pins tx p9 and rxp10 WITHOUT the USB cable plugged in? As soon as I unplug the USB cable I can no longer do serial communication. i was wanting to use the mbed on a mobile robot. I just want to continually print "hello world" from my mbed to a pc without a usb cable plugged in. i have a working comm port on my windows machine and i've used it many times before. the code below works only when a usb cable is plugged into my mbed.

Yes you can use the serial comms of course, but if you remove the USB cable you cut the power supply from the mbed. So make sure you supply +5V and gnd to the apropriate pins of the mbed. Also make sure that your bot can handle the 3.3V logic levels, otherwise you will need an aditional level changer like the MAX232 Serial level converter.

Hi all, Im new to mbed programming. Is there anyway to communicate PC and mbed through only usb cable without using serial port pins Tx and Rx? I just want communication for debugging purpose only. Plz giv me a breif explanation also.

Thanks

18 Jul 2011

user Department of Electrical Eng University of Moratuwa wrote:

Hi all, Im new to mbed programming. Is there anyway to communicate PC and mbed through only usb cable without using serial port pins Tx and Rx? I just want communication for debugging purpose only. Plz giv me a breif explanation also.

Thanks

The 'Hello World' program does this. The pins are USBTX and USBRX

31 Aug 2011

If you forget to include the pc. in front of the printf command you might see the information properly printed on your PC's display. But the formatting might look odd in some cases, and something "printed" after the printf command can appear before the information printed with the printf command. Always ensure you use pc.printf. It's easy to slip into using only printf if you program other computers with C/C++.

09 Sep 2011

I have two mbed1768 modules and if I download the same test program to each, using the USBTX & USBRX setup for serial comms via the USB, one identifies as a new serial port on Windows XP while the other doesn't. Apart from that, both will run the remaining parts of the test program (which exercises SPI and the LED outputs) correctly. Any thoughts on why one does not support USB serial, please??

09 Sep 2011

user Lorcan Smith wrote:

I have two mbed1768 modules and if I download the same test program to each, using the USBTX & USBRX setup for serial comms via the USB, one identifies as a new serial port on Windows XP while the other doesn't. Apart from that, both will run the remaining parts of the test program (which exercises SPI and the LED outputs) correctly. Any thoughts on why one does not support USB serial, please??

You will need to install the Windows serial driver twice, once for each mbed , as they appear as unique devices to Windows.

06 Nov 2011

How we can print integer to terminal(like putty and etc ) . i mean all serial function support character ...

06 Nov 2011

user jamshed iqbal wrote:

serial is easy in mbed

11 Nov 2011

You should try www.hyperserialport.com . It is a serial terminal application with built in features for debugging embedded elecronics. And it was written to work with USB to Serial devices running under Windows 7.

15 Nov 2011

How Can I use HyperTermial to send Massege by USB to my LPC1768 ? can you add pictures ?

15 Nov 2011

user Diana ROSs wrote:

How Can I use HyperTermial to send Massege by USB to my LPC1768 ? can you add pictures ?

Hello, as I assume You have done connection with mbed and hyperterminal. I do not know what do You mean by message so i expect You mean type anything to hyperterminal and send it to mbed by pressing enter.

You need to compile some code like this



#include "mbed.h"

Serial pc(USBTX, USBRX); // connection to terminal 

int main() {
pc.baud(9600); // sets speed of communication (9600 default for hyperterminal)
char buffer_for_incoming_message[30]; // creates buffer for message with max length 30 characters or numbers

pc.printf("We are alive\r\n"); //prints We are alive to terminal from mbed so You know connection works

while(1){ //from here, code is repeated each turn
if (pc.readable()){ // If pc is readable
pc.scanf("%s", &buffer_for_incoming_message); //each turn reads message from pc and stores it to "buffer_for_incoming_message". %s means that reading is ended while /n or /r appears in message (it is sent if enter pressed)

pc.printf("Recieved message is :\r\n"); // prints "Recieved message is :" and goes to new line

 for (int i = 0; i< 30; i++){ 
pc.printf("%c", buffer_for_incoming_message[i]); //prints each character from buffer one by one back to screen to show You if message recieved
}
pc.printf("\r\n"); //Goes to new line
for (int a = 0; a< 30; a++){ 
 buffer_for_incoming_message[a] = 0; // each turn sets each character of "buffer_for_incoming_message" to zero for next turn (deletes old message for new one)
 }
}
}
}

You can copy this over all text to main.cpp in new project in compiler.

But be sure You set size of "buffer_for_incoming_message[]" to size higher than is max length of message You will send or program will try to write to memory higher than reserved and collapses program.

If You want to send messages of constant length You can specify it in "pc.scanf("%s", &buffer_for_incoming_message);" and use number of characters instead of %s (for example %6c for 6 character message) and then You do not need to press enter.

I tried this code with teraterm and works. You should also turn on "local echo" in settings of hyperterminal to see what are You typiing.

I am neewbie too so I hope it helps. I am sorry of my english.

-lu

09 Dec 2011

Hi !

That possible to edit this help ?

Linux - Use the command ls /dev/ttyACM*

It is important to speecify :

Linux - Use the command screen /dev/ttyACM* (you need to install screen by command : apt-get install screen)

23 Jan 2012

.

02 Feb 2012

nice

20 Mar 2012

Hello is it possible to transmit at 1Mb/s? I've tried with this obvious command

pc.baud(1000000);

then it compiles without problem. But then in pc serial terminal (I'm using termite)

I can't select this baud rate.

Maybe the usb to serial driver on the pc side doesn't support 1Mb/s feature?

Thank you all

PS: other standards baud rates work very well

Max

03 Jun 2012

The bit rate setting in the PC, for a USB Virtual Comm Port, should not really matter, since the bytes are arriving in USB packets.

However, for some reason the speed setting in the PC's terminal program does matter. Unless the speeds match, I do not get communication.

10 Jun 2012

I need help with this code

#include "mbed.h"
#include "USBMouseKeyboard.h"
#include "USBSerial.h"

USBMouseKeyboard key_mouse;
USBSerial serial;

int main(void) {
    while (1) {
        char c = serial.getc();
        if (c == 'move mouse') {
            key_mouse.move(8000, 12000); //32700 Max
        }
        if (c == 'type') {
            key_mouse.printf("hello world \t 123 \t");
        }
        if (c == '1') {
            key_mouse.press(MOUSE_LEFT);
        }
        if (c == '2') {
            key_mouse.release(MOUSE_LEFT);
        }
        if (c == '3') {
            key_mouse.press(MOUSE_RIGHT);
        }
        if (c == '4') {
            key_mouse.release(MOUSE_RIGHT);
        }
    }
}

It only receives one char? i'm seriously steaming here trying to figure out how to create a char buffer??? Can anyone advise, Thanks in advance.

10 Jun 2012

For now, just use one character:

 if (c == 'm') { ...

 if (c == 't') { ...

//a character array:
char MyChars[15] ;
10 Jun 2012

Hi Matthew,

The functions associated with streams are getc(), gets() and scanf(); here is an example:

ยป Import this program

00001 #include "mbed.h"
00002 
00003 DigitalOut myled(LED1);
00004 Serial pc(USBTX, USBRX);
00005 
00006 int main() {
00007     char c;
00008     char buffer[128];
00009     
00010     c = pc.getc();
00011     
00012     pc.gets(buffer, 4);
00013 
00014     pc.printf("I got '%c' and '%s'\n", c, buffer);    
00015 }

If you run this and type some characters at the terminal, you should see it captures the first character, then the next 3 characters (3 + automatically appended \0 string terminator = 4), and prints them back out to you.

Simon

10 Jun 2012

What i'm trying to do:

I have USBSerial.h Not Serial.h

Here are the variables the mbed should receive from terminal

X1234,Y3826 //Moves the mouse to a location on the  -> key_mouse.move(1234, 3826);
LMP12345678 //Triggers left mouse press -> key_mouse.press(MOUSE_LEFT);
LMR12345678 //Triggers left mouse release -> key_mouse.release(MOUSE_LEFT);
RMP12345678 //Triggers right mouse press -> key_mouse.press(MOUSE_RIGHT);
RMR12345678 //Triggers right mouse release -> key_mouse.release(MOUSE_RIGHT);
Hello World //Sends keys -> key_mouse.printf("Hello World");

These variables will be received by the mbed and then parsed which will trigger a response which will move the mouse to a certan X,Y location on my screen or mouse click type or printing characters

If anyone can please try to make a basic version of this and upload a sample?

I'm using the "USBSerial.h" Interface, Not the "Serial.h" interface module

19 Jul 2012

Is it possible to specify 2 serial interfaces through 1 standard USB cable?? I want to send data to the terminal and different data to another application (f.e Labview). Any information would be appreciated.

19 Jul 2012

user Kristof Lieben wrote:

Is it possible to specify 2 serial interfaces through 1 standard USB cable?? I want to send data to the terminal and different data to another application (f.e Labview). Any information would be appreciated.

This question was discussed on the handbook page on 09 May 2012

user Samuel Joseph wrote:

@Leon: You cannot instantiate two virtual serial port. You need to modify the configuration descriptor and mix two serial port on it. So that there is only one USB device with two serial port.

The option you have is to use another serial port on the mbed or use the USB device/host port on the mbed as a virtual serial port.

18 Aug 2012

Hi all, I'd like to generate serial from a Ticker routine using printf(), but my program crashes. Is there some kind of re-entrance problem with this approach? Thanks in Advance, Wayne

05 Sep 2012

printf() is not reentrant - can disable interrupts around it. Might also use an sprintf to a buffer and then putc. http://mbed.org/cookbook/Serial-Interrupts shows the commands for interrupt disable and enable.

28 Sep 2012

Several issues here:

- Does the CPU hang while sending serial output? It seems to retain a local cache of output until I attempt to read it. - In OS X I had to use "cat /dev/tty.usbmodem622" not "ls". - This only worked once. If I control-C'd the output, I could never receive output again until I physically reinserted the device.

15 Oct 2012

Hi all,try to run the terminal program but have a message on the screen"pinmap not found for peripheralpinmap" and Led 1 to Led4 are runing continous.normaly Led1 should get brigther or dimmer depending if you press 'u' or 'd'.

18 Oct 2012

i downloaded Teraterm successfully and compiled and ran the Hello World Pintf program. All worked fine.

However, I see that the "/n" escape sequence doesnt skip to the beginning of the next line. It goes to the next line but at the location of the prior line. Is there another escape sequence to make the teraterm work line a Console Application in VC++ ???

23 Oct 2012
27 Oct 2012

Serial communication was much easier in mbed!!!:-)

30 Oct 2012

Im trying to mix the USB Serial(TX, RX) with the Keyboard library. But im not able to received right the same character over the serial three times in a row, like i received the two first character right but the third one changes its value even though i sent the same value on hyper terminal. Example of receiving data on mbed, sending character 'a' on hyper terminal: a = 97, a= 97, 225, 97, 225, 97 and so on.

This is my code:

  1. include "mbed.h"
  1. include "USBKeyboard.h" USBKeyboard keyboard; Serial pc(USBTX, USBRX); Serial pc(p9, p10); tx, rx

DigitalOut led1(LED1); DigitalOut led2(LED2);

int main() { unsigned int arre1[]={0,125,250,375,500,625}; while (1) { if(pc.readable()) {

unsigned char posi=pc.getc(); leer datos del puerto serial keyboard.printf("valor= %d \r\n",posi);

led1=1; wait(0.1); led1=0; }

}

}

Please needing some help quickly.

30 Oct 2012

<<quote Proyect>>

Im trying to mix the USB Serial(TX, RX) with the Keyboard library. But im not able to received right the same character over the serial three times in a row, like i received the two first character right but the third one changes its value even though i sent the same value on hyper terminal. Example of receiving data on mbed, sending character 'a' on hyper terminal: a = 97, a= 97, 225, 97, 225, 97 and so on.

This is my code:

  1. include "mbed.h"
  1. include "USBKeyboard.h" USBKeyboard keyboard; Serial pc(USBTX, USBRX); Serial pc(p9, p10); tx, rx

DigitalOut led1(LED1); DigitalOut led2(LED2);

int main() {

while (1) {

if(pc.readable()) {

unsigned char posi=pc.getc(); data i received over the USB serial

keyboard.printf("valor= %d \r\n",posi); im not able to print exactly received over the serial three times in a row

led1=1; wait(0.1); led1=0; }

}

}

needing some help quickly. I have 3 embed board doing the same thing.

29 Nov 2012

Dear all. how to know the serial work in the example "Pass through characters in both directions between the PC and Serial Port" ? I used pin 28&27)

I have compile and its success, and I connected the MBED with max232 (the circuit http://sodoityourself.com/max232-serial-level-converter/) and connect with USB to serial converter to my laptop. and how to make it, if i would like to send a character from laptop and MBED respon it.

Thank you

30 Nov 2012

hi, i'm new to mbed. I have only the NXP LPC1768 mbed development board. Can anybody tell me how to interface hitachi HD44780 to this mbed board. Is is possible to do that or do i need to buy any interfacing board?

Thanks in advance.

30 Nov 2012
30 Nov 2012

Neglect my previous post. I got the idea from http://mbed.org/cookbook/Text-LCD.

07 Jan 2013

:)

03 Feb 2013

Hello,

I need help to get the serial port working. Here is my code:

#include "mbed.h"

Serial pc(USBTX, USBRX); // tx, rx

DigitalOut myled1(LED1);
DigitalOut myled2(LED2);
DigitalOut myled3(LED3);
DigitalOut myled4(LED4);

int main()
{
    pc.printf("Hello World!");

    while(1) {
        myled1 = 1;
        myled4 = 0;
        wait(0.2);
        myled1 = 0;
        myled2 = 1;
        wait(0.2);
        myled2 = 0;
        myled3 = 1;
        wait(0.2);
        myled3 = 0;
        myled4 = 1;
        wait(0.2);
        pc.putc(pc.getc() + 1);
    }
}

I can't see any character print to the terminal, but when I input some char from keyboard I can see the program is running since leds are flashing. I have installed the driver, made sure the terminal is setup correctly. Why is the terminal not showing anything?

Posting comments for this page has been disabled