Meanwhile, I think I found the right combination of bits and bytes to obtain correct values from the MCP3002. Any hints are highly welcome, though! As I'm still new to programming, this is a very first approach. I am sorry not to be able to supply a class yet.
Code: Select all
from machine import SPI, Pin
spi = SPI(1, baudrate=1000000, polarity=0, phase=0)
spi.init
cs = Pin(15, Pin.OUT)
cs.value(0)
cs.value(1)
cs.value(0)
# Control & Data Registers:
# See datasheet for more information
# send 8 bit control :
# X, Strt, SGL|!DIFF, ODD|!SIGN, MSBF, X, X, X
# 0, 1, 1=SGL, 0 = CH0 , 0 , 0, 0, 0 = 96d
buffer = bytearray([96,0])
print("MOSI - first Byte:",bin(buffer[0]))
print("MOSI - second Byte:",bin(buffer[1]),"\n")
#print(bin(buffer[2]))
read = bytearray(2)
spi.write_readinto(buffer,read)
cs.value(1)
spi.deinit()
# receive 10 bit data :
# receive data range: 000..3FF (10 bits)
# MSB first: (set control bit in cmd for LSB first)
# spidata[0] = X, X, X, X, X, 0, B9, B8
# spidata[1] = B7, B6, B5, B4, B3, B2, B1, B0
# LSB: mask all but B9 & B8, shift to left and add to the MSB
print("MISO / raw - first Byte: ",bin(read[0]))
print("MISO / altered - first Byte: ",bin((read[0] & 3) << 8))
print("MISO - second Byte, OK as it is: ",bin(read[1]))
print("MISO / altered - all together: ",bin(((read[0] & 3) << 8) + read[1]))
value = (((read[0] & 3) << 8) + read[1])
print("ADC-value: ",value)
print("measured Voltage: ",((3.305/1023.0)*value),"V")