Serial communication using pySerial
Serial communication is still taken care of in embedded systems. Recently, Linux boards that can be used for embedding such as Raspberry Pi have come out, so it is convenient to be able to use serial communication from Python.
Install Since it is registered on PyPi, install it using pip or easy_install.
$ pip install pyserial
or
$ easy_install -U pyserial
Very easy if you just output characters
>>> import serial
>>> ser = serial.Serial('/dev/ttyUSB0', 9600) #Set the device name and baud rate and open the port
>>> ser.write("hello") #output
>>> ser.close() #Port close
Since timeout can be set easily, it can be easily set to non-blocking form.
>>> import serial
>>> ser = serial.Serial('/dev/ttyS0', timeout=0.1) #Set timeout in seconds (default):None)Baud rate is 9600 by default
>>> c = ser.read() #Read one character
>>> str = ser.read(10) #Also read the number of characters specified, but only the amount that can be read
>>> line = ser.readline() #Line end'¥n'Lead up to
>>> ser.close()
Official documentation Welcome to pySerial’s documentation
Recommended Posts