Generic UART Device

Note

This class is only supported on the EV3 at this time. It could be added to Powered Up hubs in a future release. If you’d like to see this happen, be sure to ask us on our support page.

../_images/sensor_rj12_gray.png
class UARTDevice(port, baudrate, timeout=None)

Generic UART device.

Parameters
  • port (Port) – Port to which the device is connected.

  • baudrate (int) – Baudrate of the UART device.

  • timeout (time: ms) – How long to wait during read before giving up. If you choose None, it will wait forever.

read(length=1)

Reads a given number of bytes from the buffer.

Your program will wait until the requested number of bytes are received. If this takes longer than timeout, the ETIMEDOUT exception is raised.

Parameters

length (int) – How many bytes to read.

Returns

Bytes returned from the device.

Return type

bytes

read_all()

Reads all bytes from the buffer.

Returns

Bytes returned from the device.

Return type

bytes

write(data)

Writes bytes.

Parameters

data (bytes) – Bytes to be written.

waiting()

Gets how many bytes are still waiting to be read.

Returns

Number of bytes in the buffer.

Return type

int

clear()

Empties the buffer.

Example: Read and write to a UART device

#!/usr/bin/env pybricks-micropython
from pybricks.hubs import EV3Brick
from pybricks.iodevices import UARTDevice
from pybricks.parameters import Port
from pybricks.media.ev3dev import SoundFile

# Initialize the EV3
ev3 = EV3Brick()

# Initialize sensor port 2 as a uart device
ser = UARTDevice(Port.S2, baudrate=115200)

# Write some data
ser.write(b'\r\nHello, world!\r\n')

# Play a sound while we wait for some data
for i in range(3):
    ev3.speaker.play_file(SoundFile.HELLO)
    ev3.speaker.play_file(SoundFile.GOOD)
    ev3.speaker.play_file(SoundFile.MORNING)
    print("Bytes waiting to be read:", ser.waiting())

# Read all data received while the sound was playing
data = ser.read_all()
print(data)