Question 8.8: You want to use the serial port (Rx and Tx pins) on the Rasp......

You want to use the serial port (Rx and Tx pins) on the Raspberry Pi using Python.

Step-by-Step
The 'Blue Check Mark' means that this solution was answered by an expert.
Learn more on how do we answer questions.

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.

Related Answered Questions

Question: 8.16

Verified Answer:

The PiFace Digital (“Modules” on page 381) is an e...
Question: 8.15

Verified Answer:

Use a boost regulator module (Figure 8-10). The mo...
Question: 8.14

Verified Answer:

A typical project using a Raspberry Pi requires 5V...
Question: 8.11

Verified Answer:

Use a Pi Cobbler, a device consisting of a small p...
Question: 8.9

Verified Answer:

Install Minicom: $ sudo apt-get install minicom...
Question: 8.21

Verified Answer:

You can use the paddle terminal breakout board sho...
Question: 8.20

Verified Answer:

The Pi Plate (Figure 8-16) is a prototyping board ...
Question: 8.19

Verified Answer:

The Humble Pi (Figure 8-15) is a prototyping board...
Question: 8.17

Verified Answer:

Figure 8-13 shows a Gertboard attached to a Raspbe...