|
Edited by nopnop2002 at 2017-4-12 22:21
I tried this circuit.(I want OPI Fritzing parts)
Left :MCP3204
Right :MCP3002
It work fine by this code.
Please try.
- /*
- * Read MPC3002/MCP3204 with wiringPiSPIDataRW
- */
- #include <stdio.h>
- #include <stdlib.h>
- #include <wiringPi.h>
- #include <wiringPiSPI.h>
- #define DEBUG 1
- #define SPI0 0 // /dev/spidev0.0
- #define CS0 8 // Slave1 ChipSelect
- #define CS1 9 // Slave2 ChipSekect
- int main(int argc, char **argv){
- int retCode;
- int i;
- int a2dChannel = 0; // analog channel
- int a2dVal = 0;
- float a2dVol = 0;
- float Vref = 3.3;
- unsigned char data[3];
- if (argc == 2) {
- printf("argv[1]=%s\n",argv[1]);
- a2dChannel=atoi(argv[1]);
- }
- if (wiringPiSetup() == -1) {
- printf("wiringPiSetup Error\n");
- }
- pinMode(CS0,OUTPUT);
- pinMode(CS1,OUTPUT);
- digitalWrite(CS0,HIGH);
- digitalWrite(CS1,HIGH);
- // SPI channel 0 = /dev/spidev0.0
- if (wiringPiSPISetup(SPI0, 1000000) < 0)
- {
- printf("SPISetup failed:\n");
- }
- for(i=0;i<10;i++) {
- digitalWrite(CS0,LOW); // Activate MCP3002
- data[0] = 0b01100000 |( ((a2dChannel & 0x03) << 4)); // first byte transmitted -> start bit
- data[1] = 0; // third byte transmitted....don't care
- if(DEBUG)printf("[MCP3002]data[write]=%02x-%02x\n",data[0],data[1]);
- retCode=wiringPiSPIDataRW (SPI0,data,sizeof(data));
- if(DEBUG)printf("[MCP3002]wiringPiSPIDataRW=%d\n",retCode);
- if(DEBUG)printf("[MCP3002]data[read]=%02x-%02x\n",data[0],data[1]);
- a2dVal = (data[0]<< 8) & 0b1100000000; //first 2 bit
- a2dVal |= (data[1] & 0xff);
- a2dVol = (float)a2dVal/1023 * Vref;
- printf("[MCP3002]a2dVal=%d\n",a2dVal);
- printf("[MCP3002]a2dVol=%f[V]\n",a2dVol);
- digitalWrite(CS0,HIGH);
- sleep(1);
- digitalWrite(CS1,LOW); // Activate MCP3204
- data[0] = 0b00000110 |( ((a2dChannel & 0x04) >> 2)); // first byte transmitted -> start bit -> (SGL/DIF = 1, D2=0)
- data[1] = 0b00000000 |( ((a2dChannel & 0x03) << 6)); // second byte transmitted -> (D1=D0=0)
- data[2] = 0; // third byte transmitted....don't care
- if(DEBUG)printf("[MCP3204]data[write]=%02x-%02x-%02x\n",data[0],data[1],data[2]);
- retCode=wiringPiSPIDataRW (SPI0,data,sizeof(data));
- if(DEBUG)printf("[MCP3004]wiringPiSPIDataRW=%d\n",retCode);
- if(DEBUG)printf("[MCP3204]data[read]=%02x-%02x-%02x\n",data[0],data[1],data[2]);
- a2dVal = (data[1]<< 8) & 0b111100000000; //first 4 bit
- a2dVal |= (data[2] & 0xff);
- a2dVol = (float)a2dVal/4095 * Vref;
- printf("[MCP3204]a2dVal=%d\n",a2dVal);
- printf("[MCP3204]a2dVol=%f[V]\n",a2dVol);
- digitalWrite(CS1,HIGH);
- sleep(1);
- }
- }
Copy code
|
This thread contains more resources
You need to Log in to download or view,No account?
Register
x
|