Parameters: |
|
---|---|
Raises: |
|
The port is immediately opened on object creation, when a port is given. It is not opened when port is None and a successive call to open() is required.
port is a device name: depending on operating system. e.g. /dev/ttyUSB0 on GNU/Linux or COM3 on Windows.
The parameter baudrate can be one of the standard values: 50, 75, 110, 134, 150, 200, 300, 600, 1200, 1800, 2400, 4800, 9600, 19200, 38400, 57600, 115200. These are well supported on all platforms.
Standard values above 115200, such as: 230400, 460800, 500000, 576000, 921600, 1000000, 1152000, 1500000, 2000000, 2500000, 3000000, 3500000, 4000000 also work on many platforms and devices.
Non-standard values are also supported on some platforms (GNU/Linux, MAC OSX >= Tiger, Windows). Though, even on these platforms some serial ports may reject non-standard values.
Possible values for the parameter timeout which controls the behavior of read():
write() is blocking by default, unless write_timeout is set. For possible values refer to the list for timeout above.
Note that enabling both flow control methods (xonxoff and rtscts) together may not be supported. It is common to use one of the methods at once, not both.
dsrdtr is not supported by all platforms (silently ignored). Setting it to None has the effect that its state follows rtscts.
Also consider using the function serial_for_url() instead of creating Serial instances directly.
Changed in version 2.5: dsrdtr now defaults to False (instead of None)
Changed in version 3.0: numbers as port argument are no longer supported
Open port.
Close port immediately.
Destructor, close port when serial port instance is freed.
The following methods may raise SerialException when applied to a closed port.
Parameters: | size – Number of bytes to read. |
---|---|
Returns: | Bytes read from the port. |
Return type: | bytes |
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.
Changed in version 2.5: Returns an instance of bytes when available (Python 2.6 and newer) and str otherwise.
Parameters: | data – Data to send. |
---|---|
Returns: | Number of bytes written. |
Return type: | int |
Raises SerialTimeoutException: | |
In case a write timeout is configured for the port and the time is exceeded. |
Write the bytes data to the port. This should be of type bytes (or compatible such as bytearray or memoryview). Unicode strings must be encoded (e.g. 'hello'.encode('utf-8').
Changed in version 2.5: Accepts instances of bytes and bytearray when available (Python 2.6 and newer) and str otherwise.
Changed in version 2.5: Write returned None in previous versions.
Flush of file like objects. In this case, wait until all data is written.
Getter: | Get the number of bytes in the input buffer |
---|---|
Type: | int |
Return the number of bytes in the receive buffer.
Changed in version 3.0: changed to property from inWaiting()
Getter: | Get the number of bytes in the output buffer |
---|---|
Type: | int |
Platform: | Posix |
Platform: | Windows |
Return the number of bytes in the output buffer.
Changed in version 2.7: (Posix support added)
Changed in version 3.0: changed to property from outWaiting()
Flush input buffer, discarding all it’s contents.
Changed in version 3.0: renamed from flushInput()
Clear output buffer, aborting the current output and discarding all that is in the buffer.
Changed in version 3.0: renamed from flushOutput()
Parameters: | duration (float) – Time to activate the BREAK condition. |
---|
Send break condition. Timed, returns to idle state after given duration.
Getter: | Get the current BREAK state |
---|---|
Setter: | Control the BREAK state |
Type: | bool |
When set to True activate BREAK condition, else disable. Controls TXD. When active, no transmitting is possible.
Setter: | Set the state of the RTS line |
---|---|
Getter: | Return the state of the RTS line |
Type: | bool |
Set RTS line to specified logic level. It is possible to assign this value before opening the serial port, then the value is applied uppon open().
Setter: | Set the state of the DTR line |
---|---|
Getter: | Return the state of the DTR line |
Type: | bool |
Set DTR line to specified logic level. It is possible to assign this value before opening the serial port, then the value is applied uppon open().
Read-only attributes:
Getter: | Device name. |
---|---|
Type: | str |
New in version 2.5.
Getter: | Get the state of the CTS line |
---|---|
Type: | bool |
Return the state of the CTS line.
Getter: | Get the state of the DSR line |
---|---|
Type: | bool |
Return the state of the DSR line.
Getter: | Get the state of the RI line |
---|---|
Type: | bool |
Return the state of the RI line.
Getter: | Get the state of the CD line |
---|---|
Type: | bool |
Return the state of the CD line
New values can be assigned to the following attributes (properties), the port will be reconfigured, even if it’s opened at that time:
Type: | str |
---|
Read or write port. When the port is already open, it will be closed and reopened with the new setting.
Getter: | Get current baud rate |
---|---|
Setter: | Set new baud rate |
Type: | int |
Read or write current baud rate setting.
Getter: | Get current byte size |
---|---|
Setter: | Set new byte size. Possible values: FIVEBITS, SIXBITS, SEVENBITS, EIGHTBITS |
Type: | int |
Read or write current data byte size setting.
Getter: | Get current parity setting |
---|---|
Setter: | Set new parity mode. Possible values: PARITY_NONE, PARITY_EVEN, PARITY_ODD PARITY_MARK, PARITY_SPACE |
Read or write current parity setting.
Getter: | Get current stop bit setting |
---|---|
Setter: | Set new stop bit setting. Possible values: STOPBITS_ONE, STOPBITS_ONE_POINT_FIVE, STOPBITS_TWO |
Read or write current stop bit width setting.
Getter: | Get current read timeout setting |
---|---|
Setter: | Set read timeout |
Type: | float (seconds) |
Read or write current read timeout setting.
Getter: | Get current write timeout setting |
---|---|
Setter: | Set write timeout |
Type: | float (seconds) |
Read or write current write timeout setting.
Changed in version 3.0: renamed from writeTimeout
Getter: | Get current inter byte timeout setting |
---|---|
Setter: | Disable (None) or enable the inter byte timeout |
Type: | float or None |
Read or write current inter byte timeout setting.
Changed in version 3.0: renamed from interCharTimeout
Getter: | Get current software flow control setting |
---|---|
Setter: | Enable or disable software flow control |
Type: | bool |
Read or write current software flow control rate setting.
Getter: | Get current hardware flow control setting |
---|---|
Setter: | Enable or disable hardware flow control |
Type: | bool |
Read or write current hardware flow control setting.
Getter: | Get current hardware flow control setting |
---|---|
Setter: | Enable or disable hardware flow control |
Type: | bool |
Read or write current hardware flow control setting.
Getter: | Get the current RS485 settings |
---|---|
Setter: | Disable (None) or enable the RS485 settings |
Type: | rs485.RS485Settings or None |
Platform: | Posix (Linux, limited set of hardware) |
Platform: | Windows (only RTS on TX possible) |
Attribute to configure RS485 support. When set to an instance of rs485.RS485Settings and supported by OS, RTS will be active when data is sent and inactive otherwise (for reception). The rs485.RS485Settings class provides additional settings supported on some platforms.
New in version 3.0.
The following constants are also provided:
A list of valid baud rates. The list may be incomplete, such that higher and/or intermediate baud rates may also be supported by the device (Read Only).
A list of valid byte sizes for the device (Read Only).
A list of valid parities for the device (Read Only).
A list of valid stop bit widths for the device (Read Only).
The following methods are for compatibility with the io library.
Returns: | True |
---|
New in version 2.5.
Returns: | True |
---|
New in version 2.5.
Returns: | False |
---|
New in version 2.5.
Parameters: | b – bytearray or array instance |
---|---|
Returns: | Number of byte read |
Read up to len(b) bytes into bytearray b and return the number of bytes read.
New in version 2.5.
The port settings can be read and written as dictionary. The following keys are supported: write_timeout, inter_byte_timeout, dsrdtr, baudrate, timeout, parity, bytesize, rtscts, stopbits, xonxoff
Returns: | a dictionary with current port settings. |
---|---|
Return type: | dict |
Get a dictionary with port settings. This is useful to backup the current settings so that a later point in time they can be restored using apply_settings().
Note that control lines (RTS/DTR) are part of the settings.
New in version 2.5.
Changed in version 3.0: renamed from getSettingsDict
Parameters: | d (dict) – a dictionary with port settings. |
---|
Applies a dictionary that was created by get_settings(). Only changes are applied and when a key is missing, it means that the setting stays unchanged.
Note that control lines (RTS/DTR) are not changed.
New in version 2.5.
Changed in version 3.0: renamed from applySettingsDict
Platform specific methods.
Warning
Programs using the following methods and attributes are not portable to other platforms!
Platform: | Posix |
---|
Configure the device for nonblocking operation. This can be useful if the port is used with select. Note that timeout must also be set to 0
Platform: | Posix |
---|---|
Returns: | File descriptor. |
Return file descriptor number for the port that is opened by this object. It is useful when serial ports are used with select.
Platform: | Posix |
---|---|
Parameters: | enable (bool) – Set flow control state. |
Manually control flow - when software flow control is enabled.
This will send XON (true) and XOFF (false) to the other device.
New in version 2.7: (Posix support added)
Changed in version 3.0: renamed from flowControlOut
Platform: | Posix (HW and SW flow control) |
---|---|
Platform: | Windows (SW flow control only) |
Parameters: | enable (bool) – Set flow control state. |
Manually control flow of outgoing data - when hardware or software flow control is enabled.
Sending will be suspended when called with False and enabled when called with True.
Changed in version 2.7: (renamed on Posix, function was called flowControl)
Changed in version 3.0: renamed from setXON
Note
The following members are deprecated and will be removed in a future release.
Deprecated since version 3.0: see in_waiting
Deprecated since version 3.0: see write_timeout
Deprecated since version 3.0: see inter_byte_timeout
Deprecated since version 3.0: see send_break()
Deprecated since version 3.0: see reset_input_buffer()
Deprecated since version 3.0: see reset_output_buffer()
Deprecated since version 3.0: see break_condition
Deprecated since version 3.0: see get_settings()
Deprecated since version 3.0: see apply_settings()
Deprecated since version 3.0: see out_waiting
Deprecated since version 3.0: see set_output_flow_control()
Deprecated since version 3.0: see set_input_flow_control()
Platform: | Windows |
---|
Attribute to configure RTS toggle control setting. When enabled and supported by OS, RTS will be active when data is available and inactive if no data is available.
New in version 2.6.
Changed in version 3.0: (removed, see rs485_mode instead)
Implementation detail: some attributes and functions are provided by the class SerialBase and some by the platform specific class and others by the base class mentioned above.
The Serial class has a Serial.rs485_mode attribute which allows to enable RS485 specific support on some platforms. Currently Windows and Linux (only a small number of devices) are supported.
Serial.rs485_mode needs to be set to an instance of rs485.RS485Settings to enable or to None to disable this feature.
Usage:
ser = serial.Serial(...)
ser.rs485_mode = serial.rs485.RS485Settings(...)
ser.write(b'hello')
There is a subclass rs485.RS485 available to emulate the RS485 support on regular serial ports.
A class that holds RS485 specific settings which are supported on some platforms.
New in version 3.0.
Parameters: |
|
---|
RTS level for transmission.
RTS level for reception.
When set to True transmitted data is also received.
Delay after setting RTS but before transmission starts (seconds as float).
Delay after transmission ends and resetting RTS (seconds as float).
A subclass that replaces the Serial.write() method with one that toggles RTS according to the RS485 settings.
Usage:
ser = serial.rs485.RS485(...)
ser.rs485_mode = serial.rs485.RS485Settings(...)
ser.write(b'hello')
Warning
This may work unreliably on some serial ports (control signals not synchronized or delayed compared to data). Using delays may be unreliable (varying times, larger than expected) as the OS may not support very fine grained delays (no smaller than in the order of tens of milliseconds).
Note
Some implementations support this natively in the class Serial. Better performance can be expected when the native version is used.
Note
The loopback property is ignored by this implementation. The actual behavior depends on the used hardware.
Warning
This implementation is currently in an experimental state. Use at your own risk.
This implements a RFC 2217 compatible client. Port names are URL in the form: rfc2217://<host>:<port>[?<option>[&<option>]]
This class API is compatible to Serial with a few exceptions:
Due to the nature of the network and protocol involved there are a few extra points to keep in mind:
Not implemented yet / Possible problems with the implementation:
Due to lack of authentication and encryption it is not suitable to use this client for connections across the internet and should only be used in controlled environments.
New in version 2.5.
This class provides helper functions for implementing RFC 2217 compatible servers.
Basically, it implements everything needed for the RFC 2217 protocol. It just does not open sockets and read/write to serial ports (though it changes other port settings). The user of this class must take care of the data transmission itself. The reason for that is, that this way, this class supports all programming models such as threads and select.
Usage examples can be found in the examples where two TCP/IP - serial converters are shown, one using threads (the single port server) and an other using select (the multi port server).
Note
Each new client connection must create a new instance as this object (and the RFC 2217 protocol) has internal state.
Parameters: |
|
---|
Initializes the Manager and starts negotiating with client in Telnet and RFC 2217 protocol. The negotiation starts immediately so that the class should be instantiated in the moment the client connects.
The serial_port can be controlled by RFC 2217 commands. This object will modify the port settings (baud rate etc.) and control lines (RTS/DTR) send BREAK etc. when the corresponding commands are found by the filter() method.
The connection object must implement a write() function. This function must ensure that data is written at once (no user data mixed in, i.e. it must be thread-safe). All data must be sent in its raw form (escape() must not be used) as it is used to send Telnet and RFC 2217 control commands.
For diagnostics of the connection or the implementation, debug_output can be set to an instance of a logging.Logger (e.g. logging.getLogger('rfc2217.server')). The caller should configure the logger using setLevel for the desired detail level of the logs.
Parameters: | data – data to be sent over the network. |
---|---|
Returns: | data, escaped for Telnet/RFC 2217 |
A generator that escapes all data to be compatible with RFC 2217. Implementors of servers should use this function to process all data sent over the network.
The function returns a generator which can be used in for loops. It can be converted to bytes using serial.to_bytes().
Parameters: | data – data read from the network, including Telnet and RFC 2217 controls. |
---|---|
Returns: | data, free from Telnet and RFC 2217 controls. |
A generator that filters and processes all data related to RFC 2217. Implementors of servers should use this function to process all data received from the network.
The function returns a generator which can be used in for loops. It can be converted to bytes using serial.to_bytes().
Parameters: | force_notification – Set to false. Parameter is for internal use. |
---|
This function needs to be called periodically (e.g. every second) when the server wants to send NOTIFY_MODEMSTATE messages. This is required to support the client for reading CTS/DSR/RI/CD status lines.
The function reads the status line and issues the notifications automatically.
New in version 2.5.
See also
RFC 2217 - Telnet Com Port Control Option
Base class for serial port exceptions.
Changed in version 2.5: Now derives from IOError instead of Exception
Exception that is raised on write timeouts.
Parity
Stop bits
Note that 1.5 stop bits are not supported on POSIX. It will fall back to 2 stop bits.
Byte size
Others
Default control characters (instances of bytes for Python 3.0+) for software flow control:
Module version:
A string indicating the pySerial version, such as 3.0.
New in version 2.3.
Changed in version 3.0: removed, use serial.tools.list_ports instead
Parameters: |
|
---|---|
Returns: | an instance of Serial or a compatible object. |
Get a native or a RFC 2217 implementation of the Serial class, depending on port/url. This factory function is useful when an application wants to support both, local ports and remote ports. There is also support for other types, see URL section.
The port is not opened when a keyword parameter called do_not_open is given and true, by default it is opened.
New in version 2.5.
This attribute is a list of package names (strings) that is searched for protocol handlers.
e.g. we want to support a URL foobar://. A module my_handlers.protocol_foobar is provided by the user:
serial.protocol_handler_packages.append("my_handlers")
s = serial.serial_for_url("foobar://")
For an URL starting with XY:// is the function serial_for_url() attempts to import PACKAGE.protocol_XY with each candidate for PACKAGE from this list.
New in version 2.6.
Parameters: | sequence – bytes, bytearray or memoryview |
---|---|
Returns: | an instance of bytes |
Convert a sequence to a bytes type. This is used to write code that is compatible to Python 2.x and 3.x.
In Python versions prior 3.x, bytes is a subclass of str. They convert str([17]) to '[17]' instead of '\x11' so a simple bytes(sequence) doesn’t work for all versions of Python.
This function is used internally and in the unit tests.
New in version 2.5.
Parameters: | sequence – bytes, bytearray or memoryview |
---|---|
Returns: | a generator that yields bytes |
Some versions of Python (3.x) would return integers instead of bytes when looping over an instance of bytes. This helper function ensures that bytes are returned.
New in version 3.0.
New in version 3.0.
Warning
This implementation is currently in an experimental state. Use at your own risk.
This module provides classes to simplify working with threads and protocols.
Protocol as used by the ReaderThread. This base class provides empty implementations of all methods.
Parameters: | transport – instance used to write to serial port. |
---|
Called when reader thread is started.
Parameters: | data (bytes) – received bytes |
---|
Called with snippets received from the serial port.
Parameters: | exc – Exception if connection was terminated by error else None |
---|
Called when the serial port is closed or the reader loop terminated otherwise.
Read binary packets from serial port. Packets are expected to be terminated with a TERMINATOR byte (null byte by default).
The class also keeps track of the transport.
Stores transport.
Forgets transport.
Parameters: | data (bytes) – partial received data |
---|
Buffer received data and search for TERMINATOR, when found, call handle_packet().
Process packets - to be overridden by subclassing.
Read and write (Unicode) lines from/to serial port. The encoding is applied.
Implement a serial port read loop and dispatch to a Protocol instance (like the asyncio.Protocol) but do it with threads.
Calls to close() will close the serial port but it is also possible to just stop() this thread and continue to use the serial port instance otherwise.
Parameters: |
|
---|
Initialize thread.
Note that the serial_instance ‘s timeout is set to one second! Other settings are not changed.
Stop the reader thread.
The actual reader loop driven by the thread. It calls Protocol.connection_made(), reads from the serial port calling Protocol.data_received() and finally calls Protocol.connection_lost() when close() is called or an error occurs.
Parameters: | data (bytes) – data to write |
---|
Thread safe writing (uses lock).
Wait until connection is set up and return the transport and protocol instances.
This class can be used as context manager, in this case it starts the thread and connects automatically. The serial port is closed when the context is left.
Returns: | protocol |
---|
Connect and return protocol instance.
Closes serial port.
Example:
class PrintLines(LineReader):
def connection_made(self, transport):
super(PrintLines, self).connection_made(transport)
sys.stdout.write('port opened\n')
self.write_line('hello world')
def handle_line(self, data):
sys.stdout.write('line received: {}\n'.format(repr(data)))
def connection_lost(self, exc):
if exc:
traceback.print_exc(exc)
sys.stdout.write('port closed\n')
ser = serial.serial_for_url('loop://', baudrate=115200, timeout=1)
with ReaderThread(ser, PrintLines) as protocol:
protocol.write_line('hello')
time.sleep(2)
Warning
This implementation is currently in an experimental state. Use at your own risk.
Experimental asyncio support is available for Python 3.4 and newer. The module serial.aio provides a asyncio.Transport: SerialTransport.
A factory function (asyncio.coroutine) is provided:
Parameters: |
|
---|---|
Platform: | Posix |
Get a connection making coroutine.
Example:
class Output(asyncio.Protocol):
def connection_made(self, transport):
self.transport = transport
print('port opened', transport)
transport.serial.rts = False
transport.write(b'hello world\n')
def data_received(self, data):
print('data received', repr(data))
self.transport.close()
def connection_lost(self, exc):
print('port closed')
asyncio.get_event_loop().stop()
loop = asyncio.get_event_loop()
coro = serial.aio.create_serial_connection(loop, Output, '/dev/ttyUSB0', baudrate=115200)
loop.run_until_complete(coro)
loop.run_forever()
loop.close()