SPI_ADC

Similar to the SPI_DAC write up, this example is a very basic demo explaining how to read in an analog signal over the SPI bus on the Arduino platform using Microchip’s MCP3201 12-bit ADC chip.  If you have not read that example and are not familiar with how to use the SPI bus, then I would recommend reading that first.  I will not go into as much detail on this page as that one.  When combining this write up with the ADC2DAC write up, the end result should be obvious: higher resolution 12-bit analog input and output signals with an Arduino.  The only downfall of the MCP3201 is that its operating temperature range (-40°C to +85°C) is not as high as the MCP4921 (-40°C to +125°C).

The parts you need…

    • MCP3201
    • generic potentiometer ( 1kohm or greater)
    • some wire
    • breadboard / protoboard

How to wire it up…

MCP3201 Pin —> Arduino Connection
1 Vref —> 5 volt refernce – can come from Arduino 5V pin
2 IN+ —> Analog voltage input signal (ADC)
3 IN- —> Ground
4 Vss —> Ground
5 CS —> Arduino pin 9
6 Dout —> Arduino pin 12
7 SCK —> Arduino pin 13
8 Vdd —> 5 volt power supply – can come from Arduino 5V pin

For the potentiometer, hook up one lead to ground, the other to the Arduino 5V, and the variable output to IN+ (pin 2) on the MCP3201.

SPI_ADC_2Serial_bb

Code without any comments…

#include <SPI.h>

const int chipSelectPinADC = 9;
unsigned int result = 0;
byte inByte = 0;

void setup()
{
Serial.begin(9600);
SPI.begin();
SPI.setBitOrder(MSBFIRST);
SPI.setClockDivider(SPI_CLOCK_DIV4);
pinMode(chipSelectPinADC, OUTPUT);
digitalWrite(chipSelectPinADC, HIGH);
}

void loop()
{
digitalWrite(chipSelectPinADC, LOW);
result = SPI.transfer(0x00);
result = result << 8;
inByte = SPI.transfer(0x00);
result = result | inByte;
digitalWrite(chipSelectPinADC, HIGH);
result = result >> 1;
result = result & 0b0000111111111111;
Serial.println(result);
delay(1000);
}

How does it work…

Start by downloading the code here with all the comments to explain each line.  As I’m writing this up, this is only the third SPI device that I’ve written any code to work with.   If you don’t have an oscilloscope, I would really recommend trying to get one somehow if you are doing anything with SPI that isn’t a copy and paste project.  Check out my suggestions here.  If you did have an oscilliscope you would see something similar to what is described in Figure 6-1 from the MCP3201 datasheet:

MCP3201_SPIexplained

Leave a Reply