Interfacing Tiva C LaunchPad with Python

In this section, we will look at how to connect Tiva C LaunchPad with Python to receive data from Launchpad in a PC.

The PySerial module can be used for interfacing Launchpad to Python. The detailed documentation of PySerial and its installation procedure for Windows, Linux, and OS X can be found here : http://pyserial.sourceforge.net/pyserial.html

PySerial is available in the Ubuntu package manager and it can be easily installed in Ubuntu using the following command in the Terminal:

    $ sudo apt-get install python-serial  

After installing the python-serial package, we can write Python code to interface Launchpad. The interfacing code is given in the following section.

The following code imports the Python serial module and the sys module. The serial module handles the serial ports of Launchpad and performs operations such as reading, writing, and so on. The sys module provides access to some variables used or maintained by the interpreter and to functions that interact strongly with the interpreter. It is always available:

#!/usr/bin/env python 
import serial 
import sys 

When we plug Launchpad to the computer, the device registers on the OS as a virtual serial port. In Ubuntu, the device name looks like /dev/ttyACMx. Here, x can be a number; if there is only one device, it will probably be 0. To interact with Launchpad, we need to handle this device file only.

The following code will try to open the serial port /dev/ttyACM0 of Launchpad with a baud rate of 115200. If it fails, it will print Unable to open serial port:

try: 
    ser = serial.Serial('/dev/ttyACM0',115200) 
except: 
    print "Unable to open serial port" 

The following code will read the serial data until the serial character becomes a new line ('n') and prints it on the Terminal. If we press Ctrl + C on the keyboard, to quit the program, it will exit by calling sys.exit(0):

while True: 
    try: 
        line = ser.readline() 
        print line 
    except: 
        print "Unable to read from device" 
        sys.exit(0) 

After saving the file, change the permission of the file to executable using the following command:

    $ sudo chmod +X script_name
    $ ./ script_name  

The output of the script will look like this:

Output of the ultrasonic distance sensor in Energia serial monitor
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.38.125