Communicate data between Python and an Arduino using the USB serial bus.
The Arduino IDE and Python solve different problems well. The Arduino has easy direct access to its hardware interface, and can create and respond to electrical signals with very low latency. Python is well-suited to interactive programming, but the latency is considerable higher than on a microcontroller, and on a laptop lacks access to hardware interfaces. This exercise will demonstrate one way of coordinating Python and the Arduino to take advantage of the best features of each by linking them using a simple ASCII message protocol over the USB serial bus.
The serial communication does introduce significant latency between the Arduino and Python so this approach is strongest for systems in which Python is used for tasks such as the GUI, visual display, sequencing, and overall event control. It would not be suitable for high-bandwidth tasks such as cycling individual digital outputs to create a stepper motor waveform. However, the extensibility of the protocol means that you can add those low-level hardware behaviors to the Arduino server program and invoke them via messages.
Setting up the exercise requires a couple of preparatory steps:
The OneInOneOutASCII sketch is provided in the course distribution in the OneInOneOutASCII folder. The source code of the sketch provides details of the messaging scheme.
The Python patch is also available in the course distribution in the OneInOneOutGUI folder. This also requires the ArduinoGUI supporting library. Because of the number of files involved, it is highly recommended that you clone the git repository to download them to your laptop.
N.B. the cluster laptops include a MacPorts installation of Python which already includes the following required libraries: py27-numpy, py27-pyqt4, py27-pyqwt, and py27-serial.
This particular Arduino IDE sketch is going to serve as the basis for all the following exercises in which we connect hardware to the Arduino and control it from Python.
For a challenge, examine the source code for both the sketch and the GUI and work out how to add additional message types.