Skip to content

Instantly share code, notes, and snippets.

@yuasatakayuki
Created June 5, 2015 09:05
Show Gist options
  • Save yuasatakayuki/39561e71cc1f7cd0c2ca to your computer and use it in GitHub Desktop.
Save yuasatakayuki/39561e71cc1f7cd0c2ca to your computer and use it in GitHub Desktop.
AD conversion using MCP3208 on Raspberry Pi convers
/*
* Before running this program, execute the following initialization command:
* > gpio load spi
*
* Expected result:
* > pi@raspberrypi:~$ ./read_mcp3208
*
* wiringPiSPISetup status = 3
* wiringPiSPIDataRW status = 3
* data[0]=00
* data[1]=03
* data[2]=f8
* Voltage = 0.620V
* Temperature = 31.38degC
*
*/
#include <wiringPiSPI.h>
#include <stdio.h>
int main(int argc, char* argv[]){
//initialize SPI
int status; status=wiringPiSPISetup(0, 500000);
printf("wiringPiSPISetup status = %d\n",status);
//send AD conversion command to MCP3208
unsigned char data[3]={0x06,0x00,0x00};
status=wiringPiSPIDataRW(0,data,3);
printf("wiringPiSPIDataRW status = %d\n",status);
for(size_t i=0;i<3;i++){
printf("data[%d]=%02x\n",i,data[i]);
}
//convert obtained ADC value to voltage
short adcValue=(data[1]&0x07)*0x100+data[2];
const double ADCMax=4096.0;
const double Vref=2.5;//V
double voltage=adcValue/ADCMax*Vref;
printf("Voltage = %.3fV\n",voltage);
//then to temperature
const double lm60Coefficient=0.00625; //V/deg
const double lm60Offset=0.424; //V
double temp=(voltage-lm60Offset)/lm60Coefficient;
printf("Temperature = %.2fdegC\n",temp);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment