BufferedSerial
BufferedSerial
class hierarchy
The BufferedSerial
class provides UART functionality. We recommend you use this class for serial data transfers. You can use it to send and receive bytes of data in a sequence using separate transmit (TX) and receive pins (RX). A device can interface with another device (such as sensors, printers or another board) to exchange data or to send text to be displayed on a text-based computer interface.
Serial channels have the following characteristics:
- TX and RX pins - you can specify either pin as Not Connected (NC) for simplex (unidirectional) communication or both as valid pins for full duplex (bidirectional) communication.
- Baud rate - predefined speed at which data is sent and received on the UART interface. Standard baud rates include 9600, 19200 and 115200.
Data is transmitted using packets of configurable sizes divided in different sections, which include:
- Start bit: indicates the start of UART data transmission.
- Data frame: can be 5 to 8 (or 9 if a parity bit is not used) bits for the actual data being transferred.
- Parity bit: optional bit, used for data error detection.
- Stop bits: 1-2 bits to signal the end of a data packet.
The BufferedSerial
calls the underlying HAL API functions. Please see the porting guide for target serial support.
When the receive interrupt is triggered when receiving data from a device, the BufferedSerial
class stores the byte(s) available to read from the hardware buffer to an internal intermediary buffer. When a read request is made, the BufferedSerial
class uses a mutex lock and enters a critical section to read out the number of bytes requested if as many are available in the intermediary buffer.
To transmit multiple bytes, the class uses an intermediary buffer to store the bytes to send and monitors the serial interface to transfer them to the hardware buffer as soon as it is available. However, all bytes are written unbuffered if in a critical section. Using intermediary buffers allows the UART interface to be used reliably for input from noninterrupt context while avoiding excess spinning waiting for transmission buffer space.
The RX and TX buffers are circular buffers with preallocated sizes configurable using the configuration parameters uart-serial-rxbuf-size
and uart-serial-txbuf-size
. You can find both configuration parameters in drivers/mbed_lib.json
.
Configuration
The following parameters can be configured at object instantiation:
- TX.
- RX.
- Baud rate.
The default baud rate value is configured in mbed-os/platform/mbed_lib.json
.
The following parameters can be configured after an BufferedSerial
object instantiation.
- Baud rate.
- Data frame length.
- Parity bit.
- Stop bits.
The default settings for a microcontroller are set as 9600-8-N-1, a common notation for serial port settings. This denotes a baud rate of 9,600 (9600), eight data frame length (8), no parity bit (N) and one stop bit (1).
You can also configure hardware flow control if necessary.
You can view more information about the configurable settings and functions in the class reference.
BufferedSerial class reference
Public Member Functions | |
BufferedSerial (PinName tx, PinName rx, int baud=MBED_CONF_PLATFORM_DEFAULT_SERIAL_BAUD_RATE) | |
Create a BufferedSerial port, connected to the specified transmit and receive pins, with a particular baud rate. More... | |
BufferedSerial (const serial_pinmap_t &static_pinmap, int baud=MBED_CONF_PLATFORM_DEFAULT_SERIAL_BAUD_RATE) | |
Create a BufferedSerial port, connected to the specified transmit and receive pins, with a particular baud rate. More... | |
short | poll (short events) const final |
Equivalent to POSIX poll(). More... | |
ssize_t | write (const void *buffer, size_t length) override |
Write the contents of a buffer to a file. More... | |
ssize_t | read (void *buffer, size_t length) override |
Read the contents of a file into a buffer. More... | |
int | close () override |
Close a file. More... | |
int | isatty () override |
Check if the file in an interactive terminal device. More... | |
off_t | seek (off_t offset, int whence) override |
Move the file position to a given offset from from a given location. More... | |
int | sync () override |
Flush any buffers associated with the file. More... | |
int | set_blocking (bool blocking) override |
Set blocking or non-blocking mode The default is blocking. More... | |
bool | is_blocking () const override |
Check current blocking or non-blocking mode for file operations. More... | |
int | enable_input (bool enabled) override |
Enable or disable input. More... | |
int | enable_output (bool enabled) override |
Enable or disable output. More... | |
void | sigio (Callback< void()> func) override |
Register a callback on state change of the file. More... | |
void | set_data_carrier_detect (PinName dcd_pin, bool active_high=false) |
Setup interrupt handler for DCD line. More... | |
void | set_baud (int baud) |
Set the baud rate. More... | |
void | set_format (int bits=8, Parity parity=BufferedSerial::None, int stop_bits=1) |
Set the transmission format used by the serial port. More... | |
void | set_flow_control (Flow type, PinName flow1=NC, PinName flow2=NC) |
Set the flow control type on the serial port. More... | |
virtual off_t | tell () |
Get the file position of the file. More... | |
virtual void | rewind () |
Rewind the file position to the beginning of the file. More... | |
virtual off_t | size () |
Get the size of the file. More... | |
virtual int | truncate (off_t length) |
Truncate or extend a file. More... | |
bool | writable () const |
Definition depends on the subclass implementing FileHandle. More... | |
bool | readable () const |
Definition depends on the subclass implementing FileHandle. More... |
Private Member Functions | |
void | baud (int baudrate) |
Set the baud rate of the serial port. More... | |
void | format (int bits=8, Parity parity=SerialBase::None, int stop_bits=1) |
Set the transmission format used by the serial port. More... | |
int | readable () |
Determine if there is a character available to read. More... | |
int | writeable () |
Determine if there is space available to write a character. More... | |
void | attach (Callback< void()> func, IrqType type=RxIrq) |
Attach a function to call whenever a serial interrupt is generated. More... | |
void | set_break () |
Generate a break condition on the serial line NOTE: Clear break needs to run at least one frame after set_break is called. More... | |
void | clear_break () |
Clear a break condition on the serial line NOTE: Should be run at least one frame after set_break is called. More... | |
void | send_break () |
Generate a break condition on the serial line. More... | |
void | set_flow_control (Flow type, const serial_fc_pinmap_t &static_pinmap) |
Set the flow control type on the serial port. More... | |
int | write (const uint8_t *buffer, int length, const event_callback_t &callback, int event=SERIAL_EVENT_TX_COMPLETE) |
Begin asynchronous write using 8bit buffer. More... | |
int | write (const uint16_t *buffer, int length, const event_callback_t &callback, int event=SERIAL_EVENT_TX_COMPLETE) |
Begin asynchronous write using 16bit buffer. More... | |
void | abort_write () |
Abort the on-going write transfer. More... | |
int | read (uint8_t *buffer, int length, const event_callback_t &callback, int event=SERIAL_EVENT_RX_COMPLETE, unsigned char char_match=SERIAL_RESERVED_CHAR_MATCH) |
Begin asynchronous reading using 8bit buffer. More... | |
int | read (uint16_t *buffer, int length, const event_callback_t &callback, int event=SERIAL_EVENT_RX_COMPLETE, unsigned char char_match=SERIAL_RESERVED_CHAR_MATCH) |
Begin asynchronous reading using 16bit buffer. More... | |
void | abort_read () |
Abort the on-going read transfer. More... | |
int | set_dma_usage_tx (DMAUsage usage) |
Configure DMA usage suggestion for non-blocking TX transfers. More... | |
int | set_dma_usage_rx (DMAUsage usage) |
Configure DMA usage suggestion for non-blocking RX transfers. More... |
BufferedSerial examples
This example toggles an LED and echoes input to a terminal:
/*
* Copyright (c) 2020 Arm Limited and affiliates.
* SPDX-License-Identifier: Apache-2.0
*/
#include "mbed.h"
// Maximum number of element the application buffer can contain
#define MAXIMUM_BUFFER_SIZE 32
// Create a DigitalOutput object to toggle an LED whenever data is received.
static DigitalOut led(LED1);
// Create a BufferedSerial object with a default baud rate.
static BufferedSerial serial_port(USBTX, USBRX);
int main(void)
{
// Set desired properties (9600-8-N-1).
serial_port.set_baud(9600);
serial_port.set_format(
/* bits */ 8,
/* parity */ BufferedSerial::None,
/* stop bit */ 1
);
// Application buffer to receive the data
char buf[MAXIMUM_BUFFER_SIZE] = {0};
while (1) {
if (uint32_t num = serial_port.read(buf, sizeof(buf))) {
// Toggle the LED.
led = !led;
// Echo the input back to the terminal.
serial_port.write(buf, num);
}
}
}
Printing to the console
Mbed OS redefines target-dependent I/O functions in the C library to allow you to use the C standard I/O library functions (s\v\f\n\printf
, scanf
and so on) in your application for printing to the console.
You can configure the system I/O retarget code to be buffered or unbuffered, depending on the configuration of the parameter stdio-buffered-serial
in platform/mbed_lib.json
. When it is buffered, the retarget code uses an instance of a BufferedSerial
class to perform the actual printing. This is where BufferedSerial
's Filehandle
inheritance is used.
Alternatively, if you need more configuration of the serial interface, you can pass an instance of the BufferedSerial
class to the system I/O retarget code at run time for printing to the console:
/*
* Copyright (c) 2020 Arm Limited and affiliates.
* SPDX-License-Identifier: Apache-2.0
*/
#include "mbed.h"
// Specify different pins to test printing on UART other than the console UART.
#define TARGET_TX_PIN USBTX
#define TARGET_RX_PIN USBRX
// Create a BufferedSerial object to be used by the system I/O retarget code.
static BufferedSerial serial_port(TARGET_TX_PIN, TARGET_RX_PIN, 9600);
FileHandle *mbed::mbed_override_console(int fd)
{
return &serial_port;
}
int main(void)
{
// print to the console using the `serial_port` object.
printf(
"Mbed OS version %d.%d.%d\n",
MBED_MAJOR_VERSION,
MBED_MINOR_VERSION,
MBED_PATCH_VERSION
);
}
We recommend you use the standard C I/O library directly to print to the console in Mbed OS.