Given below is the python code for 10 bit adc (mcp3002) which is connected to raspberry pi. What changes should i make to utilize this code for 12 bit adc (mcp3202-b)?
It would be very helpful if someone would explain this code to me as well.
Thanks in advance.
def readadc(adcnum, clockpin, mosipin, misopin, cspin):
if ((adcnum > 1) or (adcnum < 0)):
return -1
GPIO.output(cspin, True)
GPIO.output(clockpin, False) # start clock low
GPIO.output(cspin, False) # bring CS low
commandout = adcnum << 1;
commandout |= 0x0D # start bit + single-ended bit + MSBF bit
commandout <<= 4 # we only need to send 4 bits here
for i in range(4):
if (commandout & 0x80):
GPIO.output(mosipin, True)
else:
GPIO.output(mosipin, False)
commandout <<= 1
GPIO.output(clockpin, True)
GPIO.output(clockpin, False)
adcout = 0
# read in one null bit and 10 ADC bits
for i in range(11):
GPIO.output(clockpin, True)
GPIO.output(clockpin, False)
adcout <<= 1
if (GPIO.input(misopin)):
adcout |= 0x1
GPIO.output(cspin, True)
adcout /= 2 # first bit is 'null' so drop it
return adcout
You can probably try changing the line:
for i in range(11):
to
for i in range(13):
also using xrange instead of range would be better.
In the loop you read GPIO pin 10 times and catch its value. adcout
is being shifted to left (<<=
(ilshift
) is integer left shift), populating next (LSB) bits with zeros. So at the beginning the adcout
is binary 0b1
, then 0b10
, 0b100
, 0b1000
, 0b10000
and so on (assuming only the first bit is set). If the given pin is set to one, you toggle recently appended zero to one. That's how the value is being read.