serial — Serial port class

The serial module is designed as a subset of the PySerial library with some differences due to serial being implemented as a built-in streaming class rather than as Python code, and some functionality not being present and/or simplified.

RS-485 is supported but rather than using a class to represent the settings, direct attributes can be configured.

class serial.Serial(port=None, baudrate=0, bytesize=8, parity=’N’, stopbits=1, rtscts=False, dsrdtr=False, xonxoff=False, timeout=None, inter_byte_timeout=0)

Serial objects can be created and initialised using:

# open RS232 at 9600 baud
port = serial.Serial("RS232", 9600)
port.close()

# create port, then defer the open until we configure:
port = serial.Serial()
port.port = "RS232"
port.baudrate = 9600
port.parity = 'N'
port.stopbits = 1
port.open()

A Serial object acts like a stream object and reading and writing is done using the standard stream methods:

port.read(10)       # read 10 characters, returns a bytes object
port.readall()      # read all available characters
port.readline()     # read a line
port.readinto(buf)  # read and store into the given buffer
port.write('abc')   # write the 3 characters

Individual characters can be read/written using:

port.readchar()     # read 1 character and returns it as an integer
port.writechar(42)  # write 1 character

To check if there is anything to be read, use:

port.in_waiting     # returns the number of bytrs in the input buffer
__init__(port=None, baudrate=0, bytesize=8, parity=’N’, stopbits=1, rtscts=False, dsrdtr=False, xonxoff=False, timeout=None, inter_byte_timeout=0)

Create a serial port object and open it

If no parameters are supplied then the port will not be opened until minimally a port is configured and open() is called.

Parameters:
  • port (str) – is the serial port to manage and open (ex: ‘RS232’, ‘RS485’).
  • baudrate (int) – The clock rate (when 0 the current rate will be used).
  • bytesize (int) – The number of bits per byte.
  • parity (str) – The parity, ‘E’, “N’, or ‘O’.
  • stopbits (int) – The number of stop bits: 1 or 2.
  • rtscts (bool) – Enable H/W flow control.
  • dsrdtr (bool) – Require DTR to be asserted.
  • xonxoff (bool) – Enable S/W flow control. (*)
  • timeout (float) – The time in seconds to wait for the first character (None is the max timeout of 32sec).
  • inter_byte_timeout (float) – The time in seconds to wait between characters (None is the max of 32sec, 0 means do not wait for new data).
Returns:

a Serial port object

Return type:

Serial

Note

(*) These parameters may be configured, but are not supported at this time.

close()

Close port immediately

flush()

Wait until all serial data has been sent.

ioctl(param)

Used internally to help make serial ports compatible with sockets

open()

Open a Serial port with the current settings. For instance, here’s an example that will open the ‘RS232’ port and communicate with DTR low:

from serial import Serial
s = Serial()
s.port = 'RS232'
s.baudrate = 115200
s.timeout = 0.5
s.dtr = 0
s.open()
s.write('AT\r')
print(s.read())
Raises:SerialException – The method will raise SerialException if the port is already open, or port is invalid or unassigned.
read(size=256)

Read size bytes from the serial port. If a timeout is set it may return less characters as requested. With no timeout it will block until the requested number of bytes is read.

Note

One important difference when porting code which uses PySerial is that the read() method will return up to 256 bytes by default, to get the same behaviour as PySerial’s read() method call read(1). Something else to consider is that when working with binary data, CPython code may convert the data from bytes to a str using the “latin1” character set, but that does not exist in MicroPython; instead use sl3.bytes_to_str()

Example:

import serial
with serial.Serial("RS232",9600) as port:
    port.timeout=2 #maximum time to wait before closing port
    port.inter_byte_timeout=.01 #maximum time between bytes. This makes reading port data more responsive as you do not have to wait the timeout period.
    port.reset_input_buffer() #clears buffer before reading to remove any residual data.
    buf = port.read(512)
print(buf)
Parameters:size (int) – Number of bytes to read.
Returns:Bytes read from port.
Return type:bytes
readall()

Read as much data as possible. Similiar to read() but is not limited to 256 bytes.

Returns:Bytes read from port.
Return type:bytes
readchar()

Receive a single character from the port

Returns:The character read, as an ASCII integer. Returns -1 on timeout.
Return type:int
readinto(buf, nbytes)

Read bytes into the buf. If nbytes is specified then read at most that many bytes. Otherwise, read at most len(buf) bytes. Reading in to a preallocated buffer avoids the overhead of allocating new buffers on each read.

Example 1:

# Create a bytearray and read 5 bytes in to it.
buf = bytearray(256)
# read up to 5 bytes in to buf ( do not wait )
serial_port.timeout = 0
n1 = serial_port.readinto(buf, 5)

Example 2:

# Add a dash to the buf and read 10 more bytes after that making use
# of memoryview to reference the buf without making a copy of it.
buf[n1] = chr('-')
n1 += 1
# read 10 more bytes after the dash
mv = memoryview(buf)
# read in to a slice of the memory view (no data is copied)
n2 = serial_port.readinto(mv[n1:n1+10])
# when done, we can convert from bytearray to bytes
buf_as_bytes = bytes(buf)
Parameters:
  • buf (bytearray) – A bytearray to read bytes in to.
  • nbytes (int) – May optionally specify how many bytes or leave out to to fill the buffer.
Returns:

Number of bytes read.

Return type:

int

readline()

Read a line ending in the newline character (‘n’).

Returns:Bytes read from port.
Return type:bytes
reset_input_buffer()

Flush input buffer, discarding all its contents.

reset_output_buffer()

Clear output buffer, aborting the current output and discarding the output buffer.

send_break(duration=0.25)

Send break condition. Transmit line returns to idle state after given duration.

Parameters:duration (float) – time in seconds to activate the break condition
set_buffer_size(rx_size=4096, tx_size=None)

Changes the rx and tx buffer sizes. Can be called when the port is open.

Parameters:
  • rx_size (int) – size of the desired receive buffer.
  • tx_size (int) – size of the desired transmit buffer, will be left unchanged if not specified or passed None.
write(data)

Write data to the serial port.

Parameters:data (str) – Data to send (accepts bytes, str, bytearray, memoryview).
Returns:Number of bytes written or None if the operation failed.
Return type:int
writechar(char)

Write a single character to the port.

Parameters:char (int) – ASCII value of a character to write.
baudrate = 9600

Get or set the current baudrate.

break_condition = 0

When set to True activate BREAK condition, else disable. Controls TXD. When active, no transmitting is possible.

bytesize = 8

Sets the number of bits of data transmitted (7 or 8).

cd = False

Returns as a bool the state of the CD line.

cts = False

Returns as a bool the state of the CTS line.

delay_after_tx = 0.0

Delay in seconds before clearing RTS after an RS-485 transmission ends.

delay_before_tx = 0.0

Delay in seconds before setting RTS before an RS-485 transmission ends.

dsr = False

Returns as a bool the state of the DSR line.

dsrdtr = False

When set True, read/write operations will fail if DSR is not asserted (True).

dtr = False

Set DTR line to specified state (True for On, False for Off). If the value is set before opening the serial port, then the value will be applied upon open()..

in_waiting = 0

Get the number of bytes in the input buffer.

inter_byte_timeout = None

Sets the timeout in seconds (floating point allowed) when reading data after the intial byte is read. A value of None will cause this value to be ignored.

is_open = False

Returns True if the serial port has been opened.

loopback = False

When set to True transmitted data over RS-485 is also received.

name = None

Returns the name of the selected serial port.

out_waiting = 0

Get the number of bytes in the output buffer (a value of 1 indicates that at least one byte needs to be sent).

parity = ‘N’

Configures parity bit handling (‘N’ for None, ‘E’ for Even, ‘O’ for Odd).

port = None

Get or set the serial port.

Available ports include ‘RS232’, ‘RS485’.

Warning

Opening a port can intefere with any standard operations the Satlink 3 is is performing with that port.

ri = False

Returns as a bool the state of the RING line.

rs485 = False

Enables RS-485 mode on the port. On standard serial ports, RS-485 mode will assert RTS when sending data according to the RS-485 settings.

rts = False

Set RTS line to specified state (True for On, False for Off). If the value is set before opening the serial port, then the value will be applied upon open().

rts_level_for_rx = True

Determines the RTS level after an RS-485 transmission.

rts_level_for_tx = True

Determines the RTS level during an RS-485 transmission.

rtscts = False

Enable hardware (RTS/CTS) flow control.

stopbits = 1

Determines the number of stopbits (1 or 2).

timeout = None

Sets the timeout in seconds (floating point allowed) when reading data. If an inter_byte_timeout has been set, then timeout will only apply to the first byte read. A timeout of None would traditionally wait “forever” but we limit that to no more than 32 seconds.

write_timeout = None

Not currently implemented.

xonxoff = False

Not currently implemented.