Using the MCP3008 ADC with a Raspberry Pi

Microchip MCP3008

This project is to read up to eight analogue values using a Raspberry Pi. The Pi, unlike an Arduino for example, has no analogue inputs of its own and so an analogue-to-digital converter is required. The Microchip MCP3008 provides eight analogue inputs and there's a four input version too, the MCP3004. The digital result from each channel is read individually by the Pi as an integer value between 0 and 1023, representing a 10-bit resolution. The voltage reference pin, Vref, must be connected to the Pi's 3.3V supply to avoid damage to the GPIO pins. This also caps Vref at 3.3V because it cannot exceed Vdd but the range 0-1023 is still covered by the range 0V to 3.3V. If you need more than 10-bit resolution then you can use the 12-bit Microchip MCP3208 instead. If you are just writing out the digital value then the program still works but you'll need to change your program if it maps the old 0-1023 range, otherwise your results will be a quarter of what they should be.

MCP3008 and connection to Pi

The connections for an MCP3008 are shown here. Vref is the voltage to be used at full scale, that is, a reading of 1023. You can scale this value down using any of the map() functions available on the Internet.

You should tie any unused inputs to ground (GND, 0V) using a 10kΩ resistor, one for each input. If you leave the inputs floating, you will read spurious values, which you could of course just ignore.

The program to read the values is really straight-forward when using the wiringPi library. You need to add #include <mcp3004.h> to your source code for the mcp3004Setup() function. There is no mcp3008.h or mcp3008Setup() function for the MCP3008 chip - the MCP3004 header file and function work for both. The program listed here reads all eight inputs but you could of course modify it to read only the input(s) you're interested in. The program also uses the usleep() function to wait for 500ms between each set of readings. The MCP3008 can make up to 200,000 conversions per second at 5V, so somewhat less at 3.3V.

Once you have installed the WiringPi library, use the following command to compile and link the program. The -lwiringPi tells the linker explicitly to include the wiringPi library - this is case-sensitive.

sudo gcc rp-mcp3008.c -o rp-mcp3008 -lwiringPi

To run the program:


Writing results as a bar chart

A modification to the program reads values and then continuously updates the screen with the results and a coloured bar chart.

The Fritzing diagram below shows the connections to the Pi's header. Note the two links on the breadboard for 3V3 and GND. Wiring diagram