Recent changes
mbed Library Releases
Order
tag order
SerialPC
Creating a program
Downloading a program
Setup guide
Exporting to Code Red
Exporting to uVision
From the mbed microcontroller Handbook.  

Serial

/media/uploads/mbedofficial/serial_interfaces.png

Serial is a generic protocol used by computers and electronic modules to send and receive control information and data. The Serial link has two unidirection channels, one for sending and one for receiving. The link is asynchronous, and so both ends of the serial link must be configured to use the same settings.

One of the Serial connections goes via the mbed USB port, allowing you to easily communicate with your host PC.

Hello World!

Print to the PC, then pass back characters (slightly modified!)

#include "mbed.h"

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

int main() {
    pc.printf("Hello World!");
    while(1) {
        pc.putc(pc.getc() + 1);
    }
}

API

API summary

SerialA serial port (UART) for communication with other serial devices
Functions
SerialCreate a Serial port, connected to the specified transmit and receive pins
baudSet the baud rate of the serial port
formatSet the transmission format used by the Serial port
putcWrite a character
getcRead a character
printfWrite a formated string
scanfRead a formated string
readableDetermine if there is a character available to read
writeableDetermine if there is space available to write a character
attachAttach a function to call whenever a serial interrupt is generated
attachAttach a member function to call whenever a serial interrupt is generated
class Serial : public Stream
A serial port (UART) for communication with other serial devices
Serial(PinName tx,  
PinName rx,  
const char *name =  NULL)
Create a Serial port, connected to the specified transmit and receive pins
void baud(int baudrate)
Set the baud rate of the serial port
void format(int bits =  8,
Parity parity =  Serial::None,
int stop_bits =  1)
Set the transmission format used by the Serial port
int putc(int c)
Write a character
int getc()
Read a character
int printf(const char *format,
 ...)
Write a formated string
int scanf(const char *format,
 ...)
Read a formated string
int readable()
Determine if there is a character available to read
int writeable()
Determine if there is space available to write a character
void attach(void (*fptr)(void),  
IrqType type =  RxIrq)
Attach a function to call whenever a serial interrupt is generated

Details

The Serial Interface can be used on mbed pins p9/p10, p13/p14, p28/p27 and USBTX/USBRX

Note that USBTX/USBRX are not DIP pins; they represent the pins that route to the interface USB Serial port so you can communicate with a host PC.

Note

If you want to send data to a host PC, take a look at:

  • SerialPC - Communicating between mbed and a host PC

Note that on a windows machine, you will need to install a USB Serial driver, see:

Serial channels have a number of configurable parameters:

The default settings for the mbed microcontroller are described as 9600 8N1, and this is common notation for Serial port settings.

See Also

Reference

Examples

Write a message to a device at a 19200 baud

#include "mbed.h"

Serial device(p9, p10);  // tx, rx

int main() {
    device.baud(19200);
    device.printf("Hello World\n");
}

Provide a serial pass-through between the PC and an external UART

#include "mbed.h"

Serial pc(USBTX, USBRX); // tx, rx
Serial device(p9, p10);  // tx, rx

int main() {
    while(1) {
        if(pc.readable()) {
            device.putc(pc.getc());
        }
        if(device.readable()) {
            pc.putc(device.getc());
        }
    }
}

Attach to RX Interrupt

#include "mbed.h"

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

Serial pc(USBTX, USBRX);

void callback() {
    led2 = !led2;
}

int main() {
    pc.attach(&callback);
    
    while (1) {
        led1 = !led1;
        wait(0.5);
    }
}



calendar Page history
Last modified 01 Jan 2012, by   user Simon Ford   tag No tags | 42 comments      

42 comments on Serial:

28 Jul 2010

Missing a closing > on <</code>

28 Jul 2010

Thanks! Now fixed...

28 Jul 2010

could someone give an example on using scanf() to receive a string, its not working quite well for me!!

29 Jul 2010

int main() { char string[50]; String 'variable' (strings in C are arrays of chars) Serial pc(USBTX, USBRX); pc.printf("Hello\n"); while (1) { pc.scanf("%s", &string); scanf" the placeholder is '%s' for strings. scanf must be given a pointer where to store the data. The &string represents the address of string. pc.printf("%s", string); } }

Seems to work. Remember that the scanf takes enter or space as the delimiter. Also, make sure you don't try to scan strings longer than the char array or nasty things can happen. And remember the string terminator '\0' that gets placed in the array at the end of the sting. Make sure there is room for it..

06 Aug 2010

The list of supported baud rates is:

110, 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 38400, 57600, 115200, 230400, 460800, 921600

(from [[http://mbed.org/forum/mbed/topic/893/?page=1#comment-4520|this forum post)

07 Aug 2010

That list of supported baud rates is only for the USB serial port. The other serial ports can use non-standard baud rates, using the fractional baud rate generation capabilities of the LPC1768/LPC2368.

12 Sep 2010

I think I am experiencing some "buffer full" effects. Could it be possible? E.g. I write N characters and the pc.getc() function just return me the first sixteen chars. The other one get lost. -> I write: 01234567890123456789012345678901234567890123456789012345678901234567890123456789 -> I get: 01234567890123456 Any idea?

12 Sep 2010

Where and how are you reading the characters?

21 Sep 2010

Hi, (sorry for late, I didn't get an automatic email)

I use a "Serial pc(USBTX, USBRX);" I get the characters using: "char c = pc.getc();"

To check that I really get an overflow I just send back the char using: "pc.putc(c);"

22 Sep 2010

I think perhaps it should be made clearer that voltage level conversion circuit is required to tie to a "real" RS-232 serial port or perhaps another short section on that topic in the handbook.

03 Nov 2010

I already have a max232 converter circuit :-). I have also tried to use slower baud rate and I get the same problem. Thanks

04 Nov 2010

Hello, I have a problem in understanding or with the Eval board. When I put the Evel board into the pc with the USB Cable, then the program runs. But there is no new serial Connection (COM xx) on the PC. So I can not receive data. Can someone say, what mistake I have? Thanks

04 Nov 2010

Have you followed the instructions in http://mbed.org/handbook/Windows-serial-configuration?

user Frank Klöpfel wrote:

Hello, I have a problem in understanding or with the Eval board. When I put the Evel board into the pc with the USB Cable, then the program runs. But there is no new serial Connection (COM xx) on the PC. So I can not receive data. Can someone say, what mistake I have? Thanks

04 Nov 2010

Thanks ;-) sometimes it is better to read all the handbook, but I thought that this theme is uninteresting for me. Sorry and Thaks for Help.

04 Nov 2010

Added a note to this page to try and help discovery of these requirements!

05 Nov 2010

If you are using .attach for serial interrupts at high baud rates, putc() is a lot safer than printf(). My code crashed with printf() and worked fine with putc(). Someone else suggested this in an old Forum post.

25 Nov 2010

Errors

If an invalid pin value is given, the constructor throws a runtime error.
This causes Siren lights (see: /handbook/Debugging).
And, "pinmap not found" is sent to stderr

I believe this is correct.
(should all possible error calls out of a library be listed? Just like a "man" page)

10 Jan 2011

could someone give an example using the attach function in UART?

29 Jan 2011

Will the serial interface tolerate hooking to a 5 volt TTL serial interface? How about a standard RS232 interface which is 12 volts? There isn't much info I can find about hardware interfacing to the serial pins.

02 Feb 2011

If one of the serial ports, such as P9 and P10 are used, is a driver such as a MAX232 required?

02 Feb 2011

The serial interface will tolerate hooking to a 5 volt TTL serial interface but not a standard RS232 interface which could give 15 volts and needs interted signals also. For using standard RS232 interface is always needed a interface ( discrete or MAX232 family).

26 Feb 2011

What if the peripheral with which I want to communicate uses a 9-bit datalength? Is there a workaround using the parity bit or something like that?

Thanks

26 Feb 2011

Hi Jérémie,

If it is a 9-bit data length, is it really a UART protocol? It may be that something like /handbook/SPI is what you are after.

Simon

26 Feb 2011

user Simon Ford wrote:

Hi Jérémie,

If it is a 9-bit data length, is it really a UART protocol? It may be that something like /handbook/SPI is what you are after.

Simon

Some (i admit, pretty rare) measuring instruments uses a 9-bit datalength in their serial protocol.

I was hoping there was a way to use the same kind of trick as the one explained here: http://digital.ni.com/public.nsf/allkb/3BDC7FF03541F772862564990057F919

10 Mar 2011

Hello,

Is there a way to reverse the polarity of Mark and Space? I am using an old parallax LCD that needs that uses inverse logic. Thanks.

23 Mar 2011

Hello,

I'm trying to read out weather sensors from ELV. They have a serial protocol <STX>,6 byte data,<ETX>.

Code

Serial wetter(p9, p10);                    // tx, rx
void InitWetter()
    {
    wetter.format(8,Serial::Odd,2);        // 8o2, 19200
    wetter.baud(19200);
    }

but, cannot see the <STX> and the <ETX> (0x02 and 0x03). Is there any problem with not printable bytes ?

27 Mar 2011

user Thomas Rode wrote:

Hello,

I'm trying to read out weather sensors from ELV. They have a serial protocol <STX>,6 byte data,<ETX>.

Code

Serial wetter(p9, p10);                    // tx, rx
void InitWetter()
    {
    wetter.format(8,Serial::Odd,2);        // 8o2, 19200
    wetter.baud(19200);
    }

but, cannot see the <STX> and the <ETX> (0x02 and 0x03). Is there any problem with not printable bytes ?

When you say you "cannot see STX and ETX", do you mean through terminal or when monitoring through the code? If I was looking in my program I would use if(wetter.getc() == 0x02) { do stuff } for example which should work. However in terminal you would need to make sure you're viewing in hex mode rather than ascii.

20 Apr 2011

At the top of this page it shows a small diagram depicting which pins you can use the Serial object with and lists them thus:-

Quote:

The Serial Interface can be used on mbed pins p9/p10, p13/p14, p28/p27 and USBTX/USBRX

However, it's possible to "move" a set of pins from the p13/p14 slot to p26/25 pins (if you are not using p26/p25 for some other function). This is useful if you need to use all three UARTs and both SPI ports in a project. Below is the standard "Mbed pinning diagram" and an alternative pinning diagram I hashed up from the original depicting this alternate method.

/media/uploads/AjK/pinout-standard.png/media/uploads/AjK/pinout-alternate.png
02 Jun 2011

Hi , I am new here , do you guys know where I can find extra examples on codes on Serial communication ? I will appreciate your help

Tareq

04 Jul 2011

user Terry Neckar wrote:

If one of the serial ports, such as P9 and P10 are used, is a driver such as a MAX232 required?

It depends entirely on what p9/p10 are connected to. If the other side is using RS-232 signaling, yes. The pins can be used as-is for direct connection to any similar UART.

04 Jul 2011

user Igor Martinovski wrote:

Code

        pc.scanf("%s", &string);           // scanf" the placeholder is '%s' for strings. scanf must be given a pointer where to store the data. The &string represents the address of string.
        pc.printf("%s", string);

}

Technically, you should be using pc.scanf("%s", string) here and not pc.scanf("%s", &string), as "string" is already the address of the buffer. Alternatively, you could specify "&string[0]" here and that would be correct also.

04 Jul 2011

putc(), printf() and scanf() are documented to return an "int", but nowhere is it documented what these return values are. I'm particularly interested in knowing how to detect errors.

04 Jul 2011

What do you mean with 'nowhere'? Did you try google?

16 Aug 2011

user luca.scalabrino@... wrote:

I think I am experiencing some "buffer full" effects. Could it be possible? E.g. I write N characters and the pc.getc() function just return me the first sixteen chars. The other one get lost. -> I write: 01234567890123456789012345678901234567890123456789012345678901234567890123456789 -> I get: 01234567890123456 Any idea?

I have the same problem but I´m trying to send more than 16 bytes between two mbeds using ports p9 and p10... Did you find a solution? thanks!

01 Dec 2011

user María Amo wrote:

user luca.scalabrino@... wrote:

I think I am experiencing some "buffer full" effects. Could it be possible? E.g. I write N characters and the pc.getc() function just return me the first sixteen chars. The other one get lost. -> I write: 01234567890123456789012345678901234567890123456789012345678901234567890123456789 -> I get: 01234567890123456 Any idea?

I have the same problem but I´m trying to send more than 16 bytes between two mbeds using ports p9 and p10... Did you find a solution? thanks!

Any fix on this yet?

04 Jan 2012

Is it posible to connect a device which uses USART to the mbed?

04 Jan 2012

Try MODSERIAL (Serial with interrupts) if you seem to drop characters. http://mbed.org/cookbook/MODSERIAL

Also see http://mbed.org/cookbook/Serial-Interrupts

3 weeks ago

Hi! I have a very serious problem and it took me at least 3 weeks thinking about a possible solution, but I didn´t find it yet. I am developing a HMI (Human Machine Interface) in LabView. The problem is that I need to send data from my MBED to LabView (with a Serial Interface, connecting USBTX and USBRX pins, so routing Serial Port over USB Port) with high speeds, without no successful. I try to run this simple program in my MBED, and read the data in LabView:

main.cpp

#include "mbed.h"

Serial pc(USBTX, USBRX);

int main() {
    
    char letter;
    
    pc.baud(921600);
    
    letter = 0;
        
    while(1) 
    {   
        letter = letter +1;
        pc.printf("%c\n", letter);
    }
}

Talking about the LabView code, I only put the "mbed read VI" (reading the Line String), whose information appears in the next link: http://mbed.org/cookbook/Interfacing-with-LabVIEW (below "Serial Communication").

I test the C++ code, reading what MBED was sending me, with TERA TERM at 921600 bauds, and it worked. So, I think that the problem is in LabView, but I don´t know where.

Could anybody help me ? Best Regards.

3 weeks ago

It´s me again. In my last post I said that my application didn´t run in LabView. It´s false. It starts running, and after 5 seconds LabView stop receiving data and hang up. What´s the problem ?

3 days, 23 hours ago

help me to get a library cmps10????

3 days, 19 hours ago

What is cmps10, Google only comes up with digital compass.

The more infornation you give, the more solutions you will get! !

Cheers.

Ceri

3 days, 11 hours ago

There are already able to program cmps10 with serial connection to the mbed nxp lpc1768?

Please login to post comments.