Interfacing with Python

From Contiki
Revision as of 18:41, 21 March 2014 by Kwame (Talk | contribs) (Step 1)

Jump to: navigation, search

Back to Contiki Tutorials

Introduction

In this tutorial you will learn how to programmatically communicate with the Tmote Sky using the Python programming language. This will enable you to do such things as process data from your mote in real-time. In addition, you can send commands or data back to the mote to impact its operation. The possibilities are endless.

Setup

This tutorial was written and tested using the following:

  • Contiki 2.7
  • Python 2.7.3 (and pySerial)
  • Ubuntu 12.04
  • Tmote Sky

Connect the Tmote Sky to your computer using a USB cable and install the Sky Shell example. See the @Sky Shell@ tutorial for instructions on how to do this. We use this example so that we’ll have data to ensure that we are correctly reading and writing to the mote.

Step 1

Create a Python file called serial.py containing the following code:

#!/usr/bin/python
import serial
ser = serial.Serial(
   port='/dev/ttyUSB0',\
   baudrate=115200,\
   parity=serial.PARITY_NONE,\
   stopbits=serial.STOPBITS_ONE,\
   bytesize=serial.EIGHTBITS,\
   timeout=0)
print("connected to: " + ser.portstr)
ser.write("help\n");
while True:
           line = ser.readline();
           if line:
             print(line),
ser.close()

Note: This code assumes the mote you are using for this tutorial is connected to /dev/ttyUSB0. Please check this using the make motelist command as shown in the figure below. If the mote you are using is connected to a different device file, please modify the Python code accordingly.

Step 2

Run the Python code using the command:

python serial.py

You should see output similar to the following:

connected to: /dev/ttyUSB0
Available commands:
?: shows this help
binprint: print binary data in decimal format
blink [num]: blink LEDs ([num] times)
collect: collect data from the network
collect-view-data: sensor data, power consumption, network stats
echo <text>: print <text>
energy: print energy profile
exit: exit shell
hd: print binary data in hexadecimal format
help: shows this help
kill <command>: stop a specific command
killall: stop all running commands
mac <onoroff>: turn MAC protocol on (1) or off (0)
netcmd <command>: run a command on all nodes in the network
nodeid: set node ID
null: discard input
packetize: put data into one packet
power: print power profile
powerconv: convert power profile to human readable output
powertrace [interval]: turn powertracing on or off, with reporting interval <interval>
quit: exit shell
randwait <maxtime> <command>: wait for a random time before running a command
reboot: reboot the system
repeat <num> 

Understanding the Code

Back to Contiki Tutorials