MCP3208 A/D converter on Pinguino 18F2550

MCP3208 A/D converter on Pinguino 18F2550

If you are working on Pinguino and want to use MPC3208 ADC for reading analog sensors then the following code will be helpful to you. This code is based on arduino example, I have ported it to pinguino 18F2550.

MCP3208 is a 12 bit ADC which means it can provide a higher resolution then the inbuilt ADC of PIC microcontroller which is 10 bit only. MCP3208 works on SPI protocol and on one side it requires 4 wires to communicate from your microcontroller and power supply, VCC & GND. On other side you connect your analog sensor, in this example I connected IDG500 gyro for x-rate and y-rate readings:

1. CS or Chip Select

2. SDO or Data Out

3. SDI or Data In

4. CLK or Clock

/*—————————————————–
Author:  Pranav Pareek — <me at pranavpareek.com>
Date: Wed Jun 26 16:06:16 2013
Description: Ported arduino code to pinguino from: http://playground.arduino.cc/Code/MCP3208
—————————————————–*/

#define SDO 9
#define SDI 0
#define CLK 1
#define CS  2
#define LED 12
void setup() {
//run once:
Serial.begin(9600);
pinMode(LED, OUTPUT);
pinMode(SDO, OUTPUT);
pinMode(CLK, OUTPUT);
pinMode(CS, OUTPUT);
pinMode(SDI, INPUT);
digitalWrite(LED,HIGH);
digitalWrite(CS,HIGH);
digitalWrite(SDO,LOW);
digitalWrite(CLK,LOW);
}

int readvalue;

int read_adc(int channel){
int adcvalue = 0;
int i = 7;
byte commandbits = 192; //command bits – start, mode, chn (3), dont care (3)

//allow channel selection
commandbits|=((channel-1)<<3);

digitalWrite(CS,LOW); //Select adc
// setup bits to be written
for (i=7; i>=3; i–){
digitalWrite(SDO,((commandbits & 1)<<i));
//cycle clock
digitalWrite(CLK,HIGH);
digitalWrite(CLK,LOW);
}

digitalWrite(CLK,HIGH);    //ignores 2 null bits
digitalWrite(CLK,LOW);
digitalWrite(CLK,HIGH);
digitalWrite(CLK,LOW);

//read bits from adc
for (i=11; i>=0; i–){
adcvalue+=digitalRead(SDI)<<i;
//cycle clock
digitalWrite(CLK,HIGH);
digitalWrite(CLK,LOW);
}

digitalWrite(CS, HIGH); //turn off device
return adcvalue;
}

void loop() {
//run repeatedly:
readvalue = read_adc(1);
Serial.println(readvalue,DEC);
readvalue = read_adc(2);
Serial.println(readvalue,DEC);
//Serial.println(” “);
delay(250);
}

MCP3208 board is available here: http://www.anceop.com/?action=page&param=viewProduct&id=68990

Leave a Reply