electroSome

Using UART on Raspberry Pi – Python

TTL to RS232 Converter

TTL to RS232 Converter

Contents

UART stands for Universal Asynchronous Transmitter / Receiver, a popular serial communication interface which provides full duplex communication between two devices. The term universal means that transmission speed and data format are configurable. As it is asynchronous it doesn’t need to send clock signal along with the data signals. UART uses two data lines for sending (Tx) and receiving (Rx) data. The ground of both devices should be made common.

UART Communication

Freeing up UART pins on Raspberry Pi GPIO

By default Raspberry Pi’s UART pins (GPIO 14 and 15) are configured as a serial console. It outputs all the kernel data during boot. We need to free up these pins for our use. For this launch terminal,

sudo cp /boot/cmdline.txt /boot/cmdline_bp.txt
sudo nano /boot/cmdline.txt
dwc_otg.lpm_enable=0 console=tty1 root=/dev/mmcblk0p6 rootfstype=ext4 elevator=deadline rootwait
Raspberry Pi Kernal files
sudo nano /etc/inittab
#2:23:respawn:/sbin/getty -L ttyAMA0 115200 vt100
Raspberry Pi Serial console

Now you have freed the UART pins.

You can verify whether the Pi is sending and receiving UART data by installing the tool Minicom.

sudo apt-get install minicom
Raspberry Pi Install Minicom
minicom -b 115200 -o -D /dev/ttyAMA0

Where,

Raspberry Pi Minicom terminal

Using Python

In this section we will see, How to access UART using Python.

Installing pySerial

Pyserial provides backend for serial communication using python. The module named ‘serial’ selects appropriate backend automatically.  To install pySerial, by using following command.

sudo apt-get install python-serial

Now the module serial can be imported to python by using ‘import serial‘.

Example Program

The following python program reads 10 characters from the serial port and sends back it.

import serial
ser = serial.Serial ("/dev/ttyAMA0")    #Open named port 
ser.baudrate = 9600                     #Set baud rate to 9600
data = ser.read(10)                     #Read ten characters from serial port to data
ser.write(data)                         #Send back the received data
ser.close()        

For More Information : pySerial API

Any doubts or suggestions? Comment below.

Exit mobile version