Sunday, 31 January 2016

Raspberry Pi XMOS SPI communication using Python

As mentioned in the previous post, we are planning to control the servos using a XMOS multicore microcontroller. The startKIT board has a Raspberry Pi compatible 26 pin header (old models, but still compatible to the upper part of the new 40 pin).

An SPI communication example project can be found at XMOS startKIT: Building an XMOS and Raspberry Pi Robot XMP-1. As shown in this website, we first enable access to the RPi SPI hardware using the interface executed from the command:

  1. sudo raspi-config  

We update Rpi modules (may take several minutes):

  1. sudo apt-get update
  2. sudo apt-get upgrade
  3. sudo reboot

And install Python SPI module:

  1. sudo apt-get install python2.7-dev
  2. wget
  3. unzip
  4. rm
  5. cd py-spidev-master
  6. sudo python install

Bear in mind that this setup is only Python 2 compatible (not Python 3). Access to any GPIO is also conditioned to sudo privileges. To open the compatible Python command promp we do:

  1. sudo idle $

The example also provides sample code for both XMOS (complete project) and RPi (C# code for gcc compiling and java script). The XMOS sample code implements a SPI slave that expects messages based on a TLV (TagLenghtValue) protocol to set the PWM duty cicles of 8 XMOS outputs.

Interface the a compatible TLV message in Python for this example is easy. We need to set the SPI mode, frequency and send the expected bytes. The following code (a Python 2 script) implements a basic servo control that turns it from 0 to 180 degrees in slow steps than quickly comes back to 0 quickly:

  1. import spidev
  2. import time
  4. spi = spidev.SpiDev()
  6. spi.mode = 3
  7. spi.max_speed_hz = 25000000
  9. count = 110
  10. while True:
  11.       tx = [2, 0, 16, (count & 0xff00) >> 8, count & 0x00ff, 0, 110, 0, 110, 0, 110, 0, 110, 0, 110, 0, 110, 0, 110]
  13.       print("Sending ", tx)
  14.       resp = spi.xfer2(tx)
  15.       print("Received ", resp)
  16.       count += 10
  17.       if count > 510: count = 110
  18.       time.sleep(0.05)

We now plan to implement a servo control library based on a similar TLV protocol to stack movement requests that will be executed one after another, being able to receive multiple movements in a row. This will require both coding in Python and in XC (XMOS programming language).

Team Pi over 4
Filipe T
Post #2

No comments:

Post a Comment