Recent changes
Order
tag order
RTOS
Help
mbed NXP LPC1768
Firmware
Homepage
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 | 57 comments  

57 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

18 Jan 2012

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.

18 Jan 2012

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 ?

05 Feb 2012

help me to get a library cmps10????

05 Feb 2012

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

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

Cheers.

Ceri

05 Feb 2012

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

30 Mar 2012

Hi, best regards, I'm new and I have a problem simiar, uh read the posts, and i applied his advice but my project does not work. two mbeds , communicate with each pin9y10 serial; the USB cable is connected to respective mbed .( different pc) and the comunicaion is perfect...But dont work when is conected to power sources ; when using power supplys, pin 39 is not used.

The only way to communicate with sources of power is to share the GND.

This seems illogical because when the USB plug of the MBEDS is connected to different computers. (in theory is different GND.)

i don´t know for what is the pin 3 &4, i never see connected pins 3&4 in a circuit...

¿¿ONE SOLUTION??

09 Apr 2012

Dear All!

I am trying to understand serial communications with the mbed. I think I do understand, that setting the baudrate for the Serial class will set the baudrate for the built in UART. But what will the baudrate setting for USBRX, USBTX do?

I observe, that on linux I have to match the baudrate for Serial class and ttyACM* . Why is this the case? Will this set the serial clock for USB ??!

The reason I am asking: I need to know if setting the baudrate will throttle data flow to the mbed. I am observing overruns instead.

Unfortunately the code which implements this is not free :-( so I cannot dive deeper to find out myself.

regards, roland

09 Apr 2012

@German, rs232 communications always need a common ground between the transmitter and receiver. The only way to avoid this is by using some optical or transformer based isolator. However, you still need a ground to get a current flowing through the LED or primary side of the transformer. In the case of your two PCs the USB shields are probably connected to safety earth and to gnd. This would result in the common ground.

Pin 3 is the backup battery supply for the internal mbed real time clock. You need to supply power on pin 3 to keep the clock running when mbed is powered down.

Pin 4 is an external reset input for mbed. Same behaviour as when you push the reset button. Pull the input to gnd to reset.

@Roland, previous comments from mbed staff suggested that baudrate setting has no meaning for USBTX and USBRX. They always run at max USB bitrate. Overruns may be the result of slow handling and small buffers that are too small. You may want to look at the Modserial lib on the cookbook page.

22 Apr 2012

Hi Wim, you wrote:

Quote:

previous comments from mbed staff suggested that baudrate setting has no meaning for USBTX and USBRX. They always run at max USB bitrate. Overruns may be the result of slow handling and small buffers that are too small. You may want to look at the Modserial lib on the cookbook page.

Thank you for the pointer. I tried it, but the result is the same :-( As I understand MODSERIAL just extends the Serial. What puzzles me is that I get overruns even with baudrates as low as 9600 Bd. Do you have any idea why I need to set the baudrate in the pc _and_ on the mbed anyways?

If they are ignored it should be meaningless as to which values I set them. What instead I do observe that they have to match, else not a single (slow sent) byte will get through.

I must be doing something basically wrong, altough I am following the examples ... :-(

Roland

22 Apr 2012

I think the baudrate settings still have to match because the values are checked by the terminal software etc. However, the actual USB communication speed does not depend on the baudrate setting. It always runs at maximum speed. The standard serial class does not have a large buffer for storing characters that you send or that have been received. I think you only have the hardware buffer of 16 bytes or so. This means that the buffer overruns and you loose data when you dont empty the buffer in time. MODSERIAL fixes that by using a larger buffer (default 1024 bytes I think). The serial hardware interrupt is used to transfer receive/transmit data to and from the buffers. Your own software will only read/write to the buffers and does not have direct access to the serial hardware.

So are you sending data to mbed and some of that data gets lost? How much data do you send in one burst and what is mbed doing with it. Is it binary data or ASCII.

22 Apr 2012

I think the baudrate is still important since the setting used on the PC is transferred over the USB connection to the mbed interface chip which uses it to configure its UART. The actual data does arrive to the LPC1768 on a real UART, UART0, and the mbed interface chip acts as a converter between USB and UART protocols.

1 month ago

Adam, that is very good explanation... This shoud be written in bold at the front of the page... It took me a few days of playing around with mbed to figure that out and to start using it...

So, the mbed interface chip is actually using internall rom boot loader to flash lpc over uart0, and in a user program run time it is free for some debugging..

1 month ago

Adam, I also figured this out just before I read your post. I still do not understand however why I can't get reliable data transfer even when using the buffered MODSERIAL. I set the buffer sizes to 1024 and I am still not able to transfer even only 30 bytes at 9600. Is the mbed really that slow on IRQ's ?

Is there something special about the UART0, or is the behaviour the same for the other UART's ?

1 month ago

It might just be dependent on what else your program is doing. I regularly run data in and out of UART0 on the mbed at 115200 and 230400 baud. I haven't used MODSERIAL though but I see that it was recently updated so you might want to pull down the latest version.

3 weeks, 6 days ago

Hi, i have a problem with "Attach to RX Interrupt" example. I need to communicate with PC via RS232. So I have used "MAX232" as a hardware interface. It is 5V TTL/CMOS compatible. I have loaded "Attach to RX Interrupt" example without any change. Just changed:

Serial pc(USBTX, USBRX); -> Serial pc(p9, p10);

When i send data from PC to mbed via RS232, the mbed is locked. So what should be the problem? I need interrupt driven receive.

Thanks.

3 weeks, 6 days ago

user Adam Green wrote:

It might just be dependent on what else your program is doing. I regularly run data in and out of UART0 on the mbed at 115200 and 230400 baud. I haven't used MODSERIAL though but I see that it was recently updated so you might want to pull down the latest version.

It is doing absolute nothing, but sitting in a loop, and when a expected number of characters has been received turing on a led.

3 weeks, 6 days ago

user Roland Schwarz wrote:

It is doing absolute nothing, but sitting in a loop, and when a expected number of characters has been received turing on a led.

Standard questions: can you get any communication going? Did you try a terminal program on your PC and type in chars, let mbed echo something on each received char. Is your cable ok (TXD,RXD,GND and perhaps RTS/CTS and DTR/DSR shorted).

3 weeks, 3 days ago

user Bora YILDIZ wrote:

Hi, i have a problem with "Attach to RX Interrupt" example. I need to communicate with PC via RS232. So I have used "MAX232" as a hardware interface. It is 5V TTL/CMOS compatible. I have loaded "Attach to RX Interrupt" example without any change. Just changed:

Serial pc(USBTX, USBRX); -> Serial pc(p9, p10);

When i send data from PC to mbed via RS232, the mbed is locked. So what should be the problem? I need interrupt driven receive.

Thanks.

Ok i have tried again. And i see that it interrupts just one time. It opens led2, but when i send second data from PC led2 doesn't turn off. Also led1 doesnt blink anymore after i send data from PC to mbed. I am waiting for your comments.

2 weeks, 6 days ago

user Wim Huiskamp wrote:

Standard questions: can you get any communication going? Did you try a terminal program on your PC and type in chars, let mbed echo something on each received char. Is your cable ok (TXD,RXD,GND and perhaps RTS/CTS and DTR/DSR shorted).

Thank you for having answered. But none of your suggestions do not apply: I am using the USB (debugging) port, i.e. there is no possibility to short circuit RTS/CTS or make an error with cabling (it's the USB cable) And yes, slow communications (typing at the keyboard) works. I am even able to set up two mbeds and communicate over a wireless link (CC1101 chip). It is just, that I cannot even get a moderately short block (32 bytes) into the mbed without having huge inter character spacing.

3 days, 14 hours ago

I'm trying to use the device.readable function in my program for a GPS module. But it seems to ignore it. Any reasons why this is happening ? Thanks

Please login to post comments.