Wednesday, September 21, 2016

Programming the i2c Bus in Python

Reference

There's a useful reference on the Raspberry Pi website targeted at kids using the Raspberry Pi, that has a tutorial on GPIO programming in Python.

Python

To program the Raspberry Pi I chose to use Python 2.7.4 which was pre-installed with the JESSIAN Linux OS.  I wrote and tested the code using the simple Idle IDE application which came pre-installed with the Raspberry Pi's Linux operating system.  Be sure to use the correct version of Idle ... Idle is for Python 2.7 and Idle3 is for Python 3.0.

When I wrote the final code I also worked in the PyCharm IDE on my Mac because I like its code formatting features.  PyCharm can be used to edit code on a different computer using SSH.

Python's smbus Library

The first thing I had to do before beginning to code was to install the Python smbus library, which provides a high level abstraction from the specific pin voltages that need to be set to communicate on the i2c bus.  It's important to note here that I'm using Python 2.7 and the Idle IDE (ie not Idle 3 which is for Python 3.x).  The smbus library does not install the same way with Python 3, and may need manual packaging).

This was installed from the Raspberry Pi's Linux command line using:

sudo apt-get install python-smbus

The smbus library when used in python has three important commands:

bus = smbus.SMBus(n) 
... is used to instantiate an smbus object that can then be used to execute commands.  From reading various articles, early Raspberry Pi devices used n=0, and later ones used n=1.  This  is the same value that is passed in the i2c-detect command, which by trial and error I worked out should be n=1.

Once the smbus object has been instantiated, there are commands to write and read data to / from the bus.

To activate a device on the bus, we must write to its control register.   The command to do this is:
bus.write_byte_data(bus_address, control_register, value)

To read data from a device  we use:
bus.read_byte_data(bus_address, data_register)

Checking For Responses

Next I wrote three short scripts to sample each of the sensors and print out the results.

Accelerometer:

Gyroscope:

 Magnetometer / Compass



Results:





Fantastic!  I'm now reading values from all three devices, so now I can write a some useful code to capture a sequence of readings.


Reference

The most helpful reference for this project has been Ozzmaker.  It certainly does not provide a straight lift-out for two reasons - this blog uses a different sensor board, and programs in C rather than my preferred Python.



No comments:

Post a Comment