Skip to content

uBit.serial

Overview

uBit.serial provides access to the serial communication facilities of the micro:bit.

Serial communication provides a simple way to exchange a series of bytes between one device and another. The runtime's implementation of serial is general purpose and supports a number of different modes. It has a circular buffer for both the reception and transmission of data, and provides notifications to the user through the MessageBus.

By default, the baud rate for MicroBitSerial is 115200. Using serial has very little overhead until it is used to send() or read(), at which point buffers are allocated in order to accommodate incoming or outgoing data.

uBit.serial supports multithreaded operation, ensuring that only one fiber can access the serial port at a time.

The USB interface on the micro:bit is the KL27Z, which also provides DAPLink (resposible for the drag-and-drop functionality of a connected device.)

Important

If you are using Windows 7 or lower, you need to download a USB serial driver.

Note

The base class for uBit.serial (MicroBitSerial) maintains a consistent baud rate between all instances, and is enforced in hardware.

Using serial

Serial modes

There are three modes of operation for all send() or read() calls:

  • ASYNC - Returns immediately after fetching any available data for a given call
  • SYNC_SPINWAIT - Block the processor by synchronously accessing the serial port until the selected operation is complete. This isn't recommended if multiple fibers are in use.
  • SYNC_SLEEP - Blocks the current fiber only until the selected operation is complete. This mode cooperates with the fiber scheduler, and should be used in a multi-fiber program.

You simply need to pass any of these three as an parameter, e.g. uBit.serial.read(ASYNC).

Serial debug

The micro:bit provides simple debugging support over serial when enabled. Many of the components in CODAL will supply debug information that you can use without having to setup a full debugger.

You can also send debug messages yourself over serial when enabled, using the DMESG macro.

Set the following in your codal.json to enable debug information:

Config Name Value Purpose
CODAL_DEBUG 1 Enable component debug information.

Set the following in your codal.json to enable DMESG:

Config Name Value Purpose
DMESG_SERIAL_DEBUG 1 Enable DMESG macro use.
DEVICE_DMESG_BUFFER_SIZE (4096) Defines the serial buffer size for DMESG, in bytes.

For most intents and purposes, 4096 is a suitable value and should not be changed.

Reducing overhead with uBit.serial.printf

uBit.serial uses the NRF52 serial library and therefore inherits the printf function, a very lightweight solution to sending information over serial. You should prefer using this if you are only sending over serial as it uBit.serial will not allocate its buffers.

Example

Here's how you could make use of uBit.serial to display a received serial message on the display when received.

First, we need to spin on the device having data available in the buffer. Note that this will block the running fiber.

Example

1
2
3
4
while(true) {
    while(!uBit.serial.isReadable());
    print_recv_serial();
}

Then, we need to be able to read our data. This function invokes read which takes whatever is available in the buffer and turns it into a string, which can then be displayed on the device using uBit.display.

Note

We sleep at the start of this function as leeway as it is not necessarily true that the whole string is in the buffer by the time we try to read it.

Example

1
2
3
4
5
6
void print_recv_serial() {
    uBit.sleep(100);
    ManagedString msg = uBit.serial.read(1024, ASYNC); // Read up until this amount if available, otherwise return what's there.
    msg = msg.substring(0, msg.length() - 1); // Remove delimeters.
    uBit.display.scroll(msg);
}

Message Bus Info

Message Bus ID

Constant Value
DEVICE_ID_SERIAL 12

Message Bus Events

Constant Value
CODAL_SERIAL_EVT_DELIM_MATCH 1
CODAL_SERIAL_EVT_HEAD_MATCH 2
CODAL_SERIAL_EVT_RX_FULL 3

Notify Events

These events use the notification channel DEVICE_ID_NOTIFY, which provides general purpose synchronisation.

Constant Value
CODAL_SERIAL_EVT_TX_EMPTY 2

API

putc

int
putc
(
char
c)

Description

SUB CLASSES / IMPLEMENTATIONS DEFINE THE FOLLOWING METHODS:

Parameters

char
c


getc

int
getc
()


setBaudrate

int
setBaudrate
(
uint32_t
baudrate)

Parameters

uint32_t
baudrate


putc

int
putc
(
char
c)

Description

SUB CLASSES / IMPLEMENTATIONS DEFINE THE FOLLOWING METHODS:

Parameters

char
c


sendChar

int
sendChar
(
char
c)

Description

Sends a single character over the serial line.

c

the character to send

mode

the selected mode, one of: ASYNC, SYNC_SPINWAIT, SYNC_SLEEP. Each mode gives a different behaviour: ASYNC - the character is copied into the txBuff and returns immediately.

SYNC_SPINWAIT - the character is copied into the txBuff and this method will spin (lock up the processor) until the character has been sent.

SYNC_SLEEP - the character is copied into the txBuff and the fiber sleeps until the character has been sent. This allows other fibers to continue execution.

Defaults to SYNC_SLEEP.

Parameters

char
c - the character to send

Returns

the number of bytes written, or CODAL_SERIAL_IN_USE if another fiber is using the serial instance for transmission.

int
sendChar
(
char
c,
SerialMode
mode)

Description

Sends a single character over the serial line.

c

the character to send

mode

the selected mode, one of: ASYNC, SYNC_SPINWAIT, SYNC_SLEEP. Each mode gives a different behaviour: ASYNC - the character is copied into the txBuff and returns immediately.

SYNC_SPINWAIT - the character is copied into the txBuff and this method will spin (lock up the processor) until the character has been sent.

SYNC_SLEEP - the character is copied into the txBuff and the fiber sleeps until the character has been sent. This allows other fibers to continue execution.

Defaults to SYNC_SLEEP.

Parameters

char
c - the character to send

SerialMode
mode - the selected mode, one of: ASYNC, SYNC_SPINWAIT, SYNC_SLEEP. Each mode gives a different behaviour: ASYNC - the character is copied into the txBuff and returns immediately.

SYNC_SPINWAIT - the character is copied into the txBuff and this method will spin (lock up the processor) until the character has been sent.

SYNC_SLEEP - the character is copied into the txBuff and the fiber sleeps until the character has been sent. This allows other fibers to continue execution.

Returns

the number of bytes written, or CODAL_SERIAL_IN_USE if another fiber is using the serial instance for transmission.


send

int
send
(
ManagedString
s)

Description

Sends a ManagedString over the serial line.

s

the string to send

mode

the selected mode, one of: ASYNC, SYNC_SPINWAIT, SYNC_SLEEP. Each mode gives a different behaviour: ASYNC - bytes are copied into the txBuff and returns immediately.

SYNC_SPINWAIT - bytes are copied into the txBuff and this method will spin (lock up the processor) until all bytes have been sent.

SYNC_SLEEP - bytes are copied into the txBuff and the fiber sleeps until all bytes have been sent. This allows other fibers to continue execution.

Defaults to SYNC_SLEEP.

Parameters

ManagedString
s - the string to send

Returns

the number of bytes written, CODAL_SERIAL_IN_USE if another fiber is using the serial instance for transmission, DEVICE_INVALID_PARAMETER if buffer is invalid, or the given bufferLen is <= 0.

int
send
(
ManagedString
s,
SerialMode
mode)

Description

Sends a ManagedString over the serial line.

s

the string to send

mode

the selected mode, one of: ASYNC, SYNC_SPINWAIT, SYNC_SLEEP. Each mode gives a different behaviour: ASYNC - bytes are copied into the txBuff and returns immediately.

SYNC_SPINWAIT - bytes are copied into the txBuff and this method will spin (lock up the processor) until all bytes have been sent.

SYNC_SLEEP - bytes are copied into the txBuff and the fiber sleeps until all bytes have been sent. This allows other fibers to continue execution.

Defaults to SYNC_SLEEP.

Parameters

ManagedString
s - the string to send

SerialMode
mode - the selected mode, one of: ASYNC, SYNC_SPINWAIT, SYNC_SLEEP. Each mode gives a different behaviour: ASYNC - bytes are copied into the txBuff and returns immediately.

SYNC_SPINWAIT - bytes are copied into the txBuff and this method will spin (lock up the processor) until all bytes have been sent.

SYNC_SLEEP - bytes are copied into the txBuff and the fiber sleeps until all bytes have been sent. This allows other fibers to continue execution.

Returns

the number of bytes written, CODAL_SERIAL_IN_USE if another fiber is using the serial instance for transmission, DEVICE_INVALID_PARAMETER if buffer is invalid, or the given bufferLen is <= 0.


read

int
read
()

Description

Reads a single character from the rxBuff

mode

the selected mode, one of: ASYNC, SYNC_SPINWAIT, SYNC_SLEEP. Each mode gives a different behaviour: ASYNC - A character is read from the rxBuff if available, if there are no characters to be read, a value of DEVICE_NO_DATA is returned immediately.

SYNC_SPINWAIT - A character is read from the rxBuff if available, if there are no characters to be read, this method will spin (lock up the processor) until a character is available.

SYNC_SLEEP - A character is read from the rxBuff if available, if there are no characters to be read, the calling fiber sleeps until there is a character available.

Defaults to SYNC_SLEEP.

Returns

a character, CODAL_SERIAL_IN_USE if another fiber is using the serial instance for reception, DEVICE_NO_RESOURCES if buffer allocation did not complete successfully, or DEVICE_NO_DATA if the rx buffer is empty and the mode given is ASYNC.

int
read
(
SerialMode
mode)

Description

Reads a single character from the rxBuff

mode

the selected mode, one of: ASYNC, SYNC_SPINWAIT, SYNC_SLEEP. Each mode gives a different behaviour: ASYNC - A character is read from the rxBuff if available, if there are no characters to be read, a value of DEVICE_NO_DATA is returned immediately.

SYNC_SPINWAIT - A character is read from the rxBuff if available, if there are no characters to be read, this method will spin (lock up the processor) until a character is available.

SYNC_SLEEP - A character is read from the rxBuff if available, if there are no characters to be read, the calling fiber sleeps until there is a character available.

Defaults to SYNC_SLEEP.

Parameters

SerialMode
mode - the selected mode, one of: ASYNC, SYNC_SPINWAIT, SYNC_SLEEP. Each mode gives a different behaviour: ASYNC - A character is read from the rxBuff if available, if there are no characters to be read, a value of DEVICE_NO_DATA is returned immediately.

SYNC_SPINWAIT - A character is read from the rxBuff if available, if there are no characters to be read, this method will spin (lock up the processor) until a character is available.

SYNC_SLEEP - A character is read from the rxBuff if available, if there are no characters to be read, the calling fiber sleeps until there is a character available.

Returns

a character, CODAL_SERIAL_IN_USE if another fiber is using the serial instance for reception, DEVICE_NO_RESOURCES if buffer allocation did not complete successfully, or DEVICE_NO_DATA if the rx buffer is empty and the mode given is ASYNC.


readUntil

ManagedString
readUntil
(
ManagedString
delimeters)

Description

Reads until one of the delimeters matches a character in the rxBuff

delimeters

a ManagedString containing a sequence of delimeter characters e.g. ManagedString ("\r\n")

mode

the selected mode, one of: ASYNC, SYNC_SPINWAIT, SYNC_SLEEP. Each mode gives a different behaviour: ASYNC - If one of the delimeters matches a character already in the rxBuff this method will return a ManagedString up to the delimeter. Otherwise, it will return an Empty ManagedString.

SYNC_SPINWAIT - If one of the delimeters matches a character already in the rxBuff this method will return a ManagedString up to the delimeter. Otherwise, this method will spin (lock up the processor) until a received character matches one of the delimeters.

SYNC_SLEEP - If one of the delimeters matches a character already in the rxBuff this method will return a ManagedString up to the delimeter. Otherwise, the calling fiber sleeps until a character matching one of the delimeters is seen.

Defaults to SYNC_SLEEP.

Parameters

ManagedString
delimeters - a ManagedString containing a sequence of delimeter characters e.g. ManagedString ("\r\n")

Returns

A ManagedString containing the characters up to a delimeter, or an Empty ManagedString , if another fiber is currently using this instance for reception.

Note

delimeters are matched on a per byte basis.

ManagedString
readUntil
(
ManagedString
delimeters,
SerialMode
mode)

Description

Reads until one of the delimeters matches a character in the rxBuff

delimeters

a ManagedString containing a sequence of delimeter characters e.g. ManagedString ("\r\n")

mode

the selected mode, one of: ASYNC, SYNC_SPINWAIT, SYNC_SLEEP. Each mode gives a different behaviour: ASYNC - If one of the delimeters matches a character already in the rxBuff this method will return a ManagedString up to the delimeter. Otherwise, it will return an Empty ManagedString.

SYNC_SPINWAIT - If one of the delimeters matches a character already in the rxBuff this method will return a ManagedString up to the delimeter. Otherwise, this method will spin (lock up the processor) until a received character matches one of the delimeters.

SYNC_SLEEP - If one of the delimeters matches a character already in the rxBuff this method will return a ManagedString up to the delimeter. Otherwise, the calling fiber sleeps until a character matching one of the delimeters is seen.

Defaults to SYNC_SLEEP.

Parameters

ManagedString
delimeters - a ManagedString containing a sequence of delimeter characters e.g. ManagedString ("\r\n")

SerialMode
mode - the selected mode, one of: ASYNC, SYNC_SPINWAIT, SYNC_SLEEP. Each mode gives a different behaviour: ASYNC - If one of the delimeters matches a character already in the rxBuff this method will return a ManagedString up to the delimeter. Otherwise, it will return an Empty ManagedString.

SYNC_SPINWAIT - If one of the delimeters matches a character already in the rxBuff this method will return a ManagedString up to the delimeter. Otherwise, this method will spin (lock up the processor) until a received character matches one of the delimeters.

SYNC_SLEEP - If one of the delimeters matches a character already in the rxBuff this method will return a ManagedString up to the delimeter. Otherwise, the calling fiber sleeps until a character matching one of the delimeters is seen.

Returns

A ManagedString containing the characters up to a delimeter, or an Empty ManagedString , if another fiber is currently using this instance for reception.

Note

delimeters are matched on a per byte basis.


setBaud

int
setBaud
(
int
baudrate)

Description

A wrapper around the inherited method "baud" so we can trap the baud rate as it changes and restore it if redirect() is called.

Parameters

int
baudrate - the new baudrate. See: https://github.com/mbedmicro/mbed/blob/master/libraries/mbed/targets/hal/TARGET_NORDIC/TARGET_MCU_NRF51822/serial_api.c for permitted baud rates.

Returns

DEVICE_INVALID_PARAMETER if baud rate is less than 0, otherwise DEVICE_OK.

Note

the underlying implementation chooses the first allowable rate at or above that requested.


redirect

int
redirect
(
Pin &
tx,
Pin &
rx)

Description

A way of dynamically configuring the serial instance to use pins other than USBTX and USBRX.

Parameters

Pin &
tx - the new transmission pin.

Pin &
rx - the new reception pin.

Returns

CODAL_SERIAL_IN_USE if another fiber is currently transmitting or receiving, otherwise DEVICE_OK.


eventAfter

int
eventAfter
(
int
len)

Description

Configures an event to be fired after "len" characters.

Will generate an event with the ID: DEVICE_ID_SERIAL and the value CODAL_SERIAL_EVT_HEAD_MATCH.

Parameters

int
len - the number of characters to wait before triggering the event.

Returns

DEVICE_INVALID_PARAMETER if the mode given is SYNC_SPINWAIT, otherwise DEVICE_OK.

int
eventAfter
(
int
len,
SerialMode
mode)

Description

Configures an event to be fired after "len" characters.

Will generate an event with the ID: DEVICE_ID_SERIAL and the value CODAL_SERIAL_EVT_HEAD_MATCH.

Parameters

int
len - the number of characters to wait before triggering the event.

SerialMode
mode - the selected mode, one of: ASYNC, SYNC_SPINWAIT, SYNC_SLEEP. Each mode gives a different behaviour: ASYNC - Will configure the event and return immediately.

SYNC_SPINWAIT - will return DEVICE_INVALID_PARAMETER

SYNC_SLEEP - Will configure the event and block the current fiber until the event is received.

Returns

DEVICE_INVALID_PARAMETER if the mode given is SYNC_SPINWAIT, otherwise DEVICE_OK.


eventOn

int
eventOn
(
ManagedString
delimeters)

Description

Configures an event to be fired on a match with one of the delimeters.

Will generate an event with the ID: DEVICE_ID_SERIAL and the value CODAL_SERIAL_EVT_DELIM_MATCH.

Parameters

ManagedString
delimeters - the characters to match received characters against e.g. ManagedString ("\n")

Returns

DEVICE_INVALID_PARAMETER if the mode given is SYNC_SPINWAIT, otherwise DEVICE_OK.

Note

delimeters are matched on a per byte basis.

int
eventOn
(
ManagedString
delimeters,
SerialMode
mode)

Description

Configures an event to be fired on a match with one of the delimeters.

Will generate an event with the ID: DEVICE_ID_SERIAL and the value CODAL_SERIAL_EVT_DELIM_MATCH.

Parameters

ManagedString
delimeters - the characters to match received characters against e.g. ManagedString ("\n")

SerialMode
mode - the selected mode, one of: ASYNC, SYNC_SPINWAIT, SYNC_SLEEP. Each mode gives a different behaviour: ASYNC - Will configure the event and return immediately.

SYNC_SPINWAIT - will return DEVICE_INVALID_PARAMETER

SYNC_SLEEP - Will configure the event and block the current fiber until the event is received.

Returns

DEVICE_INVALID_PARAMETER if the mode given is SYNC_SPINWAIT, otherwise DEVICE_OK.

Note

delimeters are matched on a per byte basis.


isReadable

int
isReadable
()

Description

Determines whether there is any data waiting in our Rx buffer.

Returns

1 if we have space, 0 if we do not.

Note

We do not wrap the super's readable() method as we don't want to interfere with communities that use manual calls to serial.readable().


isWriteable

int
isWriteable
()

Description

Determines if we have space in our txBuff.

Returns

1 if we have space, 0 if we do not.

Note

We do not wrap the super's writeable() method as we don't want to interfere with communities that use manual calls to serial.writeable().


setRxBufferSize

int
setRxBufferSize
(
uint8_t
size)

Description

Reconfigures the size of our rxBuff

Parameters

uint8_t
size - the new size for our rxBuff

Returns

CODAL_SERIAL_IN_USE if another fiber is currently using this instance for reception, otherwise DEVICE_OK.


setTxBufferSize

int
setTxBufferSize
(
uint8_t
size)

Description

Reconfigures the size of our txBuff

Parameters

uint8_t
size - the new size for our txBuff

Returns

CODAL_SERIAL_IN_USE if another fiber is currently using this instance for transmission, otherwise DEVICE_OK.


getRxBufferSize

int
getRxBufferSize
()

Description

The size of our rx buffer in bytes.

Returns

the current size of rxBuff in bytes


getTxBufferSize

int
getTxBufferSize
()

Description

The size of our tx buffer in bytes.

Returns

the current size of txBuff in bytes


clearRxBuffer

int
clearRxBuffer
()

Description

Sets the tail to match the head of our circular buffer for reception, effectively clearing the reception buffer.

Returns

CODAL_SERIAL_IN_USE if another fiber is currently using this instance for reception, otherwise DEVICE_OK.


clearTxBuffer

int
clearTxBuffer
()

Description

Sets the tail to match the head of our circular buffer for transmission, effectively clearing the transmission buffer.

Returns

CODAL_SERIAL_IN_USE if another fiber is currently using this instance for transmission, otherwise DEVICE_OK.


rxBufferedSize

int
rxBufferedSize
()

Description

The number of bytes currently stored in our rx buffer waiting to be digested, by the user.

Returns

The currently buffered number of bytes in our rxBuff.


txBufferedSize

int
txBufferedSize
()

Description

The number of bytes currently stored in our tx buffer waiting to be transmitted by the hardware.

Returns

The currently buffered number of bytes in our txBuff.


rxInUse

int
rxInUse
()

Description

Determines if the serial bus is currently in use by another fiber for reception.

Returns

The state of our mutex lock for reception.

Note

Only one fiber can call read at a time


txInUse

int
txInUse
()

Description

Determines if the serial bus is currently in use by another fiber for transmission.

Returns

The state of our mutex lock for transmition.

Note

Only one fiber can call send at a time


Component Constructor

Advanced users only

Do not use this unless you really know what you're doing. It's usually best to use uBit.

NRF52Serial(
Pin &
tx,
Pin &
rx)

Description

Constructor

tx

the pin instance to use for transmission

rx

the pin instance to use for reception

Parameters

Pin &
tx - the pin instance to use for transmission

Pin &
rx - the pin instance to use for reception

NRF52Serial(
Pin &
tx,
Pin &
rx,
NRF_UARTE_Type *
device)

Description

Constructor

tx

the pin instance to use for transmission

rx

the pin instance to use for reception

Parameters

Pin &
tx - the pin instance to use for transmission

Pin &
rx - the pin instance to use for reception

NRF_UARTE_Type *
device