Serial communication with Raspberry pi

Randu picture Randu · Jul 9, 2013 · Viewed 32.4k times · Source

How can we do serial communication using the raspberry pi with a python script to send/receive data to my laptop? If yes can we use the RS232 cable to connect to the TX/RX ports on the raspberry pi directly? If yes, what pins must be used from the RS232 cable? It would be help full if anyone can post a example python script?

Since my first aim is to send/receive data to the laptop to/from the raspberry pi, i'm using a RS232 to USB cable at both end to connect to the laptop as well as the raspberry pi.

Answer

Cugomastik picture Cugomastik · Jul 7, 2014

RS-232/RS-485 to PC and USB to PC

For RS-232

1) Download Putty.

2) Buy a Serial Port RS232 to TTL Converter Module and a RS-232 serial cable for PC.

3) Follow the steps in Connection to a microcontroller or other peripheral on this link. Actually read the whole thing for better understanding.

4) Power your converter module with either 3.3V (pin 1) or 5.0V (pin 2), connect Rxd pin of the module to Rxd (pin 8) on Rpi and Txd pin to Txd (pin 10) on Rpi.

5) Connect your RS-232 (from PC) cable to the converter module

Now you are ready to do some coding in Python. But before that make sure that you have the library called serial for python to create the communication. You can easliy get it via terminal by typing sudo apt-get install python-serial. Also you will see the baudrate in the code is 7200. It could be less or more depending on the synchronization. Also make sure that baudrate should be same in putty and COM1, which is the port that RS-232 is connected to your PC. You can check and set it from device manager in Windows. By the way, timeout is the time gap between each message you are receiving.

In case you can't run the code from idle (that happens for some libraries), do it in terminal. For that go to the folder where you keep your python code and type python name.py.

    import serial
    import time


    def readlineCR(port):
        rv = ""
        while True:
        ch = port.read()
        rv += ch
        if ch == '\r' or ch == '':
             return rv


    port = serial.Serial("/dev/ttyAMA0", baudrate = 7200, timeout = 2)

    while True: 
         rcv = readlıneCR(port)
         port.write("I typed: " + repr(rcv))
         print(rcv)

For USB serial to PC

You have two options

First, you can buy a USB dongle for RS-232/RS-485 so that you would not use GPIO pins. But it is better to get a USB hub for all mouse, keyboard and dongle.

Second and easier, you can buy a FTDI USB to TTL converter and use GPIOs to have a serial communication with Rpi. The code for this is exactly the same the one with above. Connection for this is easy.

Module -- Rpi

Txd -- > Txd

Rxd -- > Rxd

Gnd ---> Gnd