In Part 1 I described how to connect the Raspberry Pi, MCP23017 and Arduino to the same I2C bus. In this part I’ll show you how to control a servo from the Pi via an Arduino over I2C.
To clarify you don’t need the MCP23017 to be present for this circuit to work, its just there to demonstrate having multiple devices on the I2C bus.
I’ve connected a cheap Chinese servo from eBay up to the Arduino. Its hooked up to pin 9 (PWM enabled) and the 5v+gnd rails on the breadboard.
On the Arduino I’m running the sketch below, it listens for events over I2C on address 0×03. If it receives 2 bytes, the first of which is 1 (servo identifier) it moves the servo to the position specified in the second byte.
Running on the Raspberry Pi is a tiny Python script that takes a number from a user and sends it to the Arduino over I2C. This uses the Python SMBUS library, available in Debian / Raspbian (via the python-smbus package).
#! /usr/bin/pythonimport smbus
bus = smbus.SMBus(0)
print"Not a number"if pos !=None:
Here’s a video of it in action:
In part 3 I’ll look at how to send values (such as temperatures) from the Arduino back to the Raspberry Pi over I2C.
This week I’ve been trying to get a Raspberry Pi on the same I2C bus as both an MCP23017 I/O Expander and an Arduino.
There are already lots of tutorials online for hooking up your Raspberry Pi to an MCP23017 (such as Nathan Chantell’s), but I couldn’t find any using I2C to connect the Pi and Arduino, only via the USB which I’d rather not do.
The I2C lines on Pi run at 3.3v, to safely connect these to multiple 5v I2C slaves the levels need changing, to do this I built a bi-directional level shifter using a pair of 2N7000 MOSFETs.
Below you can see the circuit laid out in Fritzing, a 10k pull-up resistor is used on each of the 3.3 and 5v SDA and SCL lines.
Using i2cdetect on the Pi you can see the MCP23017 at 0×20 and the Arduino on address 0×03:
Finally got around to moving the odd bits of content off my old homepage and setup a blog, various people have been nagging for me to write about what I get up to, so I thought I might as well give it a go.
Over the next couple of week I’m planning on writing about how I’ve redesigned the integration behind Feedtoby and also my adventures with the Raspberry Pi.