0

I'm trying to use an IR sensor with Raspberry Pi and I have this function to read a specific channel from the ADC MCP3008. When I try to read any other channel but channel 0, it doesn't work. What I mean is, if I call the function to read the channel 2, I can only get the accurate distance from channel 0. Other channels give me gibberish. The problem isn't from the ADC because I have another code that doesn't use SPI and I can read from any channel, I just don't use it because I can only get measurements from lower distances.


PS.: I deleted my last post because I asked the wrong question.

int ADC_analogRead(int channel){
    int dataADC = 0;
    int handlerSpi = 0;
    char buffer[3]; //bytes to read and send from/to ADC

    if (channel > 7 || channel < 0)
        return -1;

    handlerSpi = spiOpen(0, 100000, 0); // opens SPI channel 0 at 100 kbps, in mode 0

    /* MCU Transmitted Data - page 21 figure 6-1 from datasheet */
    buffer[0] = 1;           // Start bit
    buffer[1] = 128 + channel; // SGL/Diff + Channel to read
    buffer[2] = 0;           // Don't care
    cout << "buffer[1]: " << (unsigned int)buffer[1] << "\n"; 
    spiXfer(handlerSpi, buffer, buffer, 3); // This function sends 3 bytes to ADC from variable buffer and after sending, it read 3 bytes to buffer variable

    /* MCU Received Data */
    /* buffer[0] -> don't cares
       buffer[1] -> first 5 bits are don't cares, 6 bit is null bit and 7/8 are data
       buffer[2] -> all data bits
    */
    dataADC = (((buffer[1] & 3) << 8) | buffer[2]); // binary math to read 10 bits ADC data

    spiClose(handlerSpi);
    return dataADC;}

1 Answer 1

1

You need to correctly encode the channel to be read in the command.

buffer[1] = (8+channel)<<4;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.