Exercise: Using Raspberry Pi from Python and Python from Pd

Objective

Use Python to access hardware via wiringPi; use Python classes from within Pd.

This exercise assumes you have the basic Raspberry Pi materials as specified in 1.c.iv.1.

Overview

The strength of Pure Data is its intrinsic parallelism and ease of incremental, interactive programming. However, Python is a great language for quick prototyping and is frequently taught as an introductory text-based programming language. The wiringpi2 module enables Python to use the wiringPi library for direct hardware access on the Raspberry Pi.

We are also providing the pdpython Pd external as a means of combining the strength of Pd and Python. It allows instances of Python classes to be created as Pd objects. Pd messages are mapped to function calls; with some care, a system can be built which maintains the real-time character of Pd. One pragmatic application is that the Python wiringPi interface is considerably more complete than the one offered by pdwiringPi.

Steps and observations

  1. Find the pwm_soft_and_hard.py script and examine the text, e.g. using the more command. It sets up the hardware PWM output and then generates a second PWM signal in software.
  2. Run the script using sudo: sudo python pwm_soft_and_hard.py
  3. Using an oscilloscope, look at the hardware PWM signal on BCM 18/Physical 12 and the software PWM signal on BCM 23/Physical 16. There is usually a substantial difference in signal stability and frequency.
  4. Stop the Python script using Control-C.
  5. Examine the contents of pd_helper.py. This is a module which can be loaded into Pd that contains a few miscellaneous test functions.
  6. Load the patch in Pd: sudo pd rpi-pdpython.pd
  7. Follow the text in the patch: it demonstrates how the Python functions are called from Pd.

Comments

The actual pdpython code in this exercise is slightly contrived in the interests of providing simplified examples. A few more examples highlighting different techniques can be found in the pdpython source at /opt/cmuphyscomp/src/pdpython/examples or online at github.

A practical example from the course is the conductor patch for assignment 1.c.v, as it uses Python data structures to keep track of clients connecting over the network. This is a natural task for Python and simpler than the equivalent in vanilla Pd.

Other Files

  1. rpi-pdpython.pd
  2. pd_helper.py
  3. pwm_soft_and_hard.py