Serial port programming

This is a step-by-step guide to using the serial port from a program running under Linux; it was written for the Raspberry Pi serial port with the Raspbian Wheezy distribution. However, the same code should work on other systems.

Step 1: Connect to a terminal emulator using a PC
This step is not essential, but it is invaluable for checking that the hardware is working on a new system.

Follow the instructions at RPi_Serial_Connection, so that you end up with your Pi's serial port connected to a PC, running a terminal emulator such as minicom or PuTTY.

The default Wheezy installation sends console messages to the serial port as it boots, and runs getty so you can log in using the terminal emulator. If you can do this, the serial port hardware is working.

Step 2: Test with Python and a terminal emulator
You will now need to edit files /etc/inittab and /boot/cmdline.txt as described at RPi_Serial_Connection. When you have done this - remember to reboot after editing - the terminal emulator set up in Step 1 will no longer show any output from Linux - it is now free for use by programs. Leave the terminal emulator connected and running throughout this step.

We will now write a simple Python program which we can talk to with the terminal emulator. You will need to install the PySerial package: sudo apt-get install python-serial

Now, on the Raspberry Pi, type the following code into a text editor, taking care to get the indentation correct: import serial port = serial.Serial("/dev/ttyAMA0", baudrate=115200, timeout=3.0) while True: port.write("\r\nSay something:") rcv = port.read(10) port.write("\r\nYou sent:" + repr(rcv))

Save the result as file serialtest.py, and then run it with: python serialtest.py

If all is working, you should see the following lines appearing repeatedly, one every 3 seconds, on the terminal emulator: Say something: You sent: ''

Try typing some characters in the terminal emulator window. You will not see the characters you type appear straight away - instead you will see something like this: Say something: You sent: 'abcabc'

If you typed Enter in the terminal emulator, it will appear as the character sequence \r - this is Python's way of representing the ASCII "CR" (Control-M) character.

Troubleshooting
For other problems (e.g. text appears corrupted) refer to the troubleshooting table in Step 1.