
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
How do I access the serial (RS232) port in Python?
To access the serial port in Python, use the pyserial module, which Python Serial Port Extension for Win32, OSX, Linux, BSD, Jython, IronPython.
Let us see the 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.
To install pyserial, use pip
pip install pyserial
At first import the required libraries.
import time import serial
Then, configure the serial connections.
ser = serial.Serial( port='Enter Port', baudrate=9600, parity=serial.PARITY_ODD, stopbits=serial.STOPBITS_TWO, bytesize=serial.SEVENBITS )
Get keyboard input using the input()
input = 1 while 1: # get keyboard input input = input(">> ") if input == 'exit': ser.close() exit()
If input is not equal to exit, send the character to the device using the write()
else: ser.write(input + '\r\n') out = ''
Wait one second before reading output.
time.sleep(1) while ser.inWaiting() > 0: out += ser.read(1) if out != '': print ">>" + out
- Related Articles
- Difference Between Serial and Parallel Port
- How do I access subdocuments in MongoDB queries?
- How do I access values created by serializeArray in jQuery?
- How do we access command line arguments in Python?
- How do I access SQLite database instance on iPhone
- TCP/IP port in SAP HANA to access Index server
- TCP/IP port in SAP HANA to access Statistics server
- How do we access class attributes using dot operator in Python?
- TCP/IP port in SAP HANA to access SAP HANA XS Engine
- How do I get the parent directory in Python?
- How can I do "cd" in Python?
- How do I Install MySQLdb in Python?
- How do I write JSON in Python?
- How do I clear the regular expression cache in Python?
- How do I find the current module name in Python?

Advertisements