I want to read 3 analogue sensors simultaneously. I have successfully connected 2 sensors using a MCP 3002 A/D converter which is connected to CS0 of SPI 0 of raspberry pi and I have activated 3 more CS pins for SPI 1.
I have connected the 3rd sensor on SPI 1 bus on CS2 with MOSI, MISO and SCLK of respective SPI buses, but when I run the program 2 sensors give readings while the 3rd sensor just shows 0.0.

I think there is a problem with my code but i cant seem to figure it out.

I am attaching the code as well. Help will be really appreciated.

import time
import spidev
import RPi.GPIO as GPIO

spi_ch = 0

spi = spidev.SpiDev(0, spi_ch)
spi.max_speed_hz = 1200000

def read_adc(adc_ch, vref = 3.3):

    msg = 0b11
    msg = ((msg << 1) + adc_ch) << 5
    msg = [msg, 0b00000000]
    reply = spi.xfer2(msg)

    adc = 0
    for n in reply:
        adc = (adc << 8) + n

    adc = adc >> 1

    voltage = (vref * adc) / 1024

    return voltage

spi_ch1 = 2

spi1 = spidev.SpiDev(1, spi_ch)
spi1.max_speed_hz = 1200000

def read1_adc(adc1, vref = 3.3):

    msg = 0b11
    msg = ((msg << 1) + adc1) << 5
    msg = [msg, 0b00000000]
    reply = spi1.xfer2(msg)

    adc = 0
    for n in reply:
        adc = (adc << 8) + n

    adc = adc >> 1

    voltage1 = (vref * adc) / 1024

    return voltage1

    while True:
        adc_0 = read_adc(0)
        adc_1 = read_adc(1)
        print("Ch 0:", adc_0, "V  Ch 1:", adc_1, "V  ch:2" ,adc1 , "V")

  • Try using GPIOZero gpiozero.readthedocs.io/en/stable/… it's much easier to use and has all the coded needed to get sensible numeric results with about five lines of code rather than 50 lines. – Dougie Apr 27 at 20:40
  • can you please elaborate this? As far as i understood the documentation on the link you referred i still couldnt find my answer, i guess the alternative to this is to use gpiozero library and mcp 3008 which has 8 channels. Am i going in the right direction? – Basit Anwar Apr 27 at 21:21
  • from gpiozero import MCP3002 then sensor1 = mcp3002(channel=0, device=0) sensor2 = mcp3002(channel=0, device=1) then you can read the sensors with print (sensor1.value) or print (sensor2.value) -- that's five lines of code. – Dougie Apr 27 at 23:07
  • @Basit Anwar Well, if by replacing MCP3002, one MCP3008 with 8 channels can solve your problem, why bother using multiple SPI channels? Perhaps you have other reasons to use more than two SPI channel. – tlfong01 Apr 28 at 0:31
  • yes i figured it was a much better option, i already ordered one. @Dougie Thank you for your help. Thanks for the suggestion i was at first skeptical but now i am sure. I will let you guys know what worked out for me. – Basit Anwar Apr 28 at 1:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.