Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How do I access the serial (RS232) port in Python?
To access the serial (RS232) port in Python, use the pyserial module, which provides Python Serial Port Extension for Win32, OSX, Linux, BSD, Jython, and IronPython.
PySerial Features
- Access to the port settings through Python properties
- Support for different byte sizes, stop bits, parity and flow control with RTS/CTS and/or Xon/Xoff
- Working with or without receive timeout
- The files in this package are 100% pure Python
- The port is set up for binary transmission. No NULL byte stripping, CR-LF translation etc.
Installation
To install pyserial, use pip ?
pip install pyserial
Basic Serial Port Setup
First, import the required libraries ?
import time import serial
Configure the serial connection with your specific port settings ?
ser = serial.Serial(
port='/dev/ttyUSB0', # Replace with your port (COM1, COM2, etc. on Windows)
baudrate=9600,
parity=serial.PARITY_ODD,
stopbits=serial.STOPBITS_TWO,
bytesize=serial.SEVENBITS
)
Complete Example: Interactive Serial Communication
Here's a complete example that demonstrates reading and writing to a serial port ?
import time
import serial
# Configure serial connection
ser = serial.Serial(
port='/dev/ttyUSB0', # Change to your port
baudrate=9600,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout=1
)
print("Serial port opened. Type 'exit' to quit.")
while True:
# Get keyboard input
user_input = input(">> ")
if user_input == 'exit':
ser.close()
print("Serial port closed.")
break
# Send data to serial device
ser.write((user_input + '\r\n').encode('utf-8'))
# Wait and read response
time.sleep(1)
response = ""
while ser.in_waiting > 0:
response += ser.read(1).decode('utf-8')
if response:
print("Response: " + response.strip())
Common Port Names
| Operating System | Port Format | Example |
|---|---|---|
| Windows | COM ports | COM1, COM2, COM3 |
| Linux | /dev/ttyUSB* or /dev/ttyACM* | /dev/ttyUSB0, /dev/ttyACM0 |
| macOS | /dev/tty.usbserial-* | /dev/tty.usbserial-14130 |
Key Methods
-
serial.Serial()? Creates a serial port object -
write()? Sends data to the serial device -
read()? Reads data from the serial device -
in_waiting? Returns number of bytes waiting in buffer -
close()? Closes the serial connection
Conclusion
PySerial provides a simple way to communicate with RS232 devices in Python. Remember to match the baud rate, parity, and other settings with your target device for successful communication.
Advertisements
