title: How to read SPI values from MCP3202 on raspberry pi 3b+?
body: <p>I am trying to program raspberry pi 3 to read spi values from the ADC (mcp3202)</p>
  
  <p>I referred to this </p>
  
  <blockquote>
    <p><a href="https://learn.sparkfun.com/tutorials/python-programming-tutorial-getting-started-with-the-raspberry-pi/experiment-3-spi-and-analog-input" rel="nofollow noreferrer">https://learn.sparkfun.com/tutorials/python-programming-tutorial-getting-started-with-the-raspberry-pi/experiment-3-spi-and-analog-input</a></p>
  </blockquote>
  
  <p>but the tutorial used <a href="https://i.stack.imgur.com/gTiqq.png" rel="nofollow noreferrer">mcp3002 10bit ADC</a> which is different from this <a href="https://i.stack.imgur.com/8nnir.png" rel="nofollow noreferrer"><strong>mcp3202 12bit ADC</strong></a> which i am trying to implement </p>
  
  <p>So what changes do I need to make in this</p>
  
  <pre><code>def read_adc(adc_ch, vref = 3.3):
  
      # Make sure ADC channel is 0 or 1
      if adc_ch != 0:
          adc_ch = 1
  
      # Construct SPI message
      #  First bit (Start): Logic high (1)
      #  Second bit (SGL/DIFF): 1 to select single mode
      #  Third bit (ODD/SIGN): Select channel (0 or 1)
      #  Fourth bit (MSFB): 0 for LSB first
      #  Next 12 bits: 0 (don't care)
      msg = 0b11
      msg = ((msg &lt;&lt; 1) + adc_ch) &lt;&lt; 5
      msg = [msg, 0b00000000]
      reply = spi.xfer2(msg)
  
      # Construct single integer out of the reply (2 bytes)
      adc = 0
      for n in reply:
          adc = (adc &lt;&lt; 8) + n
  
      # Last bit (0) is not part of ADC value, shift to remove it
      adc = adc &gt;&gt; 1
  
      # Calculate voltage form ADC value
      voltage = (vref * adc) / 1024
  
      return voltage
  </code></pre>