MCP3201 communicates with raspberry pi
Reference:
依照下面的block
diagram來看
CLK 與CS為input,由raspberry
pi 送入
Dout則由MCP3201根據送入的CLK,送出暫存器中的資料
用另外的miso_test大致模仿送入的情形
已經測試過沒問題
已經測試過沒問題
python
import
RPi.GPIO as
GPIO
import
time
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
sclk
= 11
miso
= 9
miso_test
= 21
ce
= 8
GPIO.setup(sclk,GPIO.OUT)
GPIO.setup(miso,GPIO.IN)
GPIO.setup(miso_test,GPIO.OUT)
GPIO.setup(ce,GPIO.OUT)
###
mode(1,1) sclk,ce idles high
GPIO.output(sclk,True)
GPIO.output(ce,True)
GPIO.output(miso_test,False)
Vref
= 3.3
while
True:
##
read enable
GPIO.output(ce,False)
rcv_data = str()
for
cnt in
range(16):
## generate 16 clock cycle
GPIO.output(sclk,False)
if
GPIO.input(miso):
rcv_data +=
'1'
else:
rcv_data +=
'0'
print
("cnt : %d"
%cnt)
print
("rcv_data : %s"
%rcv_data)
####
miso test (1V:010011011001)####
if
cnt == 3:
GPIO.output(miso_test,True)
elif
cnt == 6:
GPIO.output(miso_test,True)
elif
cnt == 7:
GPIO.output(miso_test,True)
elif
cnt == 9:
GPIO.output(miso_test,True)
elif
cnt == 10:
GPIO.output(miso_test,True)
elif
cnt == 13:
GPIO.output(miso_test,True)
else:
GPIO.output(miso_test,False)
###################
GPIO.output(sclk,True)
#capture
data B11-B0
cal_data =
rcv_data[3:15]
print
("cal_data bits : %s"
%cal_data)
#transfer
bin to dez
#implement
formular on spec p.17
cal_data =
int(cal_data,2)*(Vref/4096)
print
("voltage : %f"
%cal_data)
##
read disable
GPIO.output(ce,True)
time.sleep(0.1)
|
再擷取字串的資料的時候需要注意
字串只會取至右邊界前一個字元,並不包含右邊界
cal_data = rcv_data[3:15] ,所以需要取到第15個bit在command line上驗證一下
另一種聰明很多的方法 = =
import
RPi.GPIO as
GPIO
import
time
import
spidev
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
Vref
= 3.3
spi
= spidev.SpiDev()
spi.open(0,
0)
def
adc_mcp3201():
rcv01 =
spi.xfer2([0x00,0x00])
adcout01 = ((rcv01[0]
& 31)
<< 7)
+ ((rcv01[1] >> 1
)
print
("adcout01 adc01: %d"
%adcout01)
voltage01 =
adcout01*(Vref/4096)
print
("voltage01 adc01: %0.4f"
%voltage01)
while
True:
adc_mcp3201()
time.sleep(0.5)
|
沒有留言:
張貼留言