You want to use the serial port (Rx and Tx pins) on the Raspberry Pi using Python.
Install the PySerial library:
$ sudo apt-get install python-serial |
Before you can use the library for your own Python serial projects, you need to disable the Raspberry Pi’s serial console by following Recipe 8.7.
Discussion
The library is pretty easy to use. Creating a connection uses the following syntax:
ser = serial.Serial(DEVICE, BAUD) |
Where DEVICE is the device for the serial port (/dev/ttyAMA0) and BAUD the baud rate as a number, not a string. For example:
ser = serial.Serial(‘/dev/ttyAMA0’, 9600) |
Once a connection is established, you can send data over serial like this:
ser.write(‘some text’) |
Listening for a response normally involves a loop that reads and prints, as illustrated in this example:
while True: print(ser.read()) |
See Also
You will need to use this technique in recipes that connect hardware to the serial port, such as Recipe 11.10.