One of the things that the Raspberry Pi lacks that the Arduino has in abundance is analog I/O. While teaching my Introduction to Raspberry Pi class this week, one of the topics we covered was how to use an MCP3002 2-channel 10-bit analog to digital converter with the SPI interface on the GPIO connector.
The MCP3002 is straightforward to wire up. In the picture you can see the SPI interface on the purple wires, connected to MOSI, MISO and CLK on the T-cobbler. The Chip Enable (CE) pin on the chip goes to CE0 on the T-Cobbler over the grey wire, and the 10K trimpot is wired as a voltage divider between +3.3V and GND to supply a variable voltage to ADC channel 0 (the 1K ohm resistor is there to limit the current when the trimpot is turned to zero).
Here’s some example code in Python that can return the position of the trimpot:
from __future__ import division import spidev def bitstring(n): s = bin(n)[2:] return '0'*(8-len(s)) + s def read(adc_channel=0, spi_channel=0): conn = spidev.SpiDev(0, spi_channel) conn.max_speed_hz = 1200000 # 1.2 MHz cmd = 128 if adc_channel: cmd += 32 reply_bytes = conn.xfer2([cmd, 0]) reply_bitstring = ''.join(bitstring(n) for n in reply_bytes) reply = reply_bitstring[5:15] return int(reply, 2) / 2**10 if __name__ == '__main__': print read()
The next time you are wishing for analog input to your Raspberry Pi, think of adding an MCP3002 or one of the other members of the family with more channels (MCP3004, MCP3008) or more resolution (MCP3202, MCP3302) or both (MCP3204, MCP3208, MCP3304, MCP3308).