Serial port programming in Python is done using a module called ‘serial’. A few basics of serial port programming is listed below:
How to open a port:
First we have to import the module ‘serial’. Create an instance of class ‘Serial’ of the module ‘serial’.
>>> import serial
>>> ser = serial.Serial(0)
This will open port number 0. To write into the port we can simply use ‘ser.write()’.
We have not set any value to the port. We can set them manually. Default values are:
port – /dev/ttyS0
baudrate – 9600
byte size – 8
parity – None
stop bit – 1
Configuring the Port:
We can configure the port by adjusting the baudrate, byte size, parity etc.
>>> ser = serial.Serial()
>>> ser.baudrate = 19200
>>> ser.port = 0
Reading from a Port:
>>> x = ser.read() #reads a byte
>>> s = ser.read(100) #reads up to 100 bytes
>>> line = ser.readline() #reads up to the ‘\n’
We must be careful while using. Readline must be given a timeout. Otherwise the port can get blocked for ever if a new line character never appear. If we provide a timeout the port will close after that particular time interval.
Closing an Opened Port:
We can test whether a port is opened or closed.
>>> ser.isOpen() #returns true if then port is open else it will return false.
>>> ser.close() #closes an opened port