MCP3204 Read analog data using SPI

Da raspibo.
Jump to navigation Jump to search

This experiment shows how to communicate between an Arduino (Nano in this case) and a MCP3204 using SPI.

The MCP3204 is a 4-Channel 12-Bit A/D Converters with SPI Serial Interface. Device information here: http://ww1.microchip.com/downloads/en/DeviceDoc/21298e.pdf.

You can find the SPI library reference here: https://www.arduino.cc/en/Reference/SPI

Arduino Nano specialized pins functions for SPI: 10 (SS), 11 (MOSI), 12 (MISO), 13 (SCK).

We connected the Arduino Nano to work as master.

MCP3204 Arduino.png ("this image was created with Fritzing")

The source code of the Arduino's sketch is:

/* Analog to Digital Converter */

/* Input: Analog signal to CH0 of the MCP3204
 * Output: Serial print
 */

#include  <SPI.h>

//2 byte to store 12 bits
byte byte0; //highbyte for bit11-8
byte byte1; //lowbyte for bit7-0

int cs=10; //chipselect

void setup(){
  pinMode(cs, OUTPUT);
  digitalWrite(cs, HIGH);
  SPI.begin();
  SPI.setBitOrder(MSBFIRST); //MSB goes first out
  SPI.setClockDivider(SPI_CLOCK_DIV16); //1Mhz SPI clock
  Serial.begin(9600);
}

void loop(){
  digitalWrite(cs, LOW);
  SPI.transfer(0x18); //0b0000011000 configuration bits: five 0's, startbit, sind/diff, D2,D1,D0(in this case channel 0)
  byte0=SPI.transfer(0x00); //transfer something to request data (synchronous communication)
  byte1=SPI.transfer(0x00); //transfer something to request data (synchronous communication)
  digitalWrite(cs, HIGH);

  
  uint16_t myword;
  myword = ( byte0 << 8 | byte1 ) & 0b111111111111; //cast to keep only our 12 bits
  Serial.print("merged word:");
  Serial.println(myword, DEC);

  delay(1000);
}