Dylan Cornell
Dylan Cornell

Reputation: 9

MCP3008 raspberry pi ADC error

I am getting an error when reading from the mcp3008 ADC. The function below returns 127 when receiving a 3.3V input. Since it is a 10 bit ADC, it should return 1023.

I have defined my pin numbers correctly, and included both stdio.h and wiringPi.h. Any help is appreciated.

int main(void) {

    int adcValue = 0;

    wiringPiSetup();

    pinMode(csPin, OUTPUT); 
    pinMode(sclkPin, OUTPUT);
    pinMode(mosiPin, OUTPUT); 
    pinMode(misoPin, INPUT);

    while(1) {
        delay(10);
        adcValue = readADC(CHAN0);
        if (adcValue == -1)
            printf("Error reading from %i \n", CHAN0);
        else
            printf("Chan0: %i \n", adcValue);
    }

}

int readADC(int adcChan) {

    // Variables
    unsigned char dataOut = 0;
    unsigned char adcout = 0;
    int i, j = 0;

    if ((adcChan > 7) || (adcChan < 0)) {
        return -1;
    }

    digitalWrite(csPin, HIGH);

    digitalWrite(sclkPin, LOW);
    digitalWrite(csPin, LOW); 

    dataOut = adcChan;
    dataOut |= 0x18; 
    dataOut <<= 3; 

    for (i = 0; i < 5; i++) {
        if (dataOut & 0x80) {
            digitalWrite(mosiPin, HIGH);
        } else {  
            digitalWrite(mosiPin, LOW);
        }

        dataOut <<= 1;
        digitalWrite(sclkPin, HIGH);
        digitalWrite(sclkPin, LOW);
    }
    adcout = 0;
    for (j = 0; j < 12; j++) {
        digitalWrite(sclkPin, HIGH);
        digitalWrite(sclkPin, LOW);
        adcout <<= 1;
        if (digitalRead(misoPin)) {
            adcout |= 0x1;
        }
    } 

    digitalWrite(csPin, HIGH);

    adcout >>= 1; 
    return adcout;
}

Upvotes: 0

Views: 1309

Answers (3)

Morten Larsen
Morten Larsen

Reputation: 503

use python and spidev module! It will look something like!

import spidev

spi = spidev.SpiDev()
spi.open(0,0)

def read(ch):
    adc = (spi.xfer2([1,(8+ch)<<4,0])
    data = ((adc[1]&3 << 8) + adc[2]

This should give u proper readings from the mcp3008 chip. I am currently using this chip in a sensor module for connecting my analog sensors. Ch is the channel on the mcp3008 (0-7)

Upvotes: 1

ElderBug
ElderBug

Reputation: 6145

Your adcout is a char and can't hold the 10-bit value. Use an unsigned int instead. Also, you should not shift back your value with adcout >>= 1;, it's already good.

Upvotes: 2

Vagish
Vagish

Reputation: 2547

You are returning a variable unsigned char adcout = 0; which of a size 8 bits NOT 10 bits. Also you are right shifting it by 1 before returning,So most probably you are getting :

255 Right shifted by 1 = 127.

Upvotes: 1

Related Questions