mcp3204.py
1#!/usr/bin/python 2# 3# MCP3204/MCP3208 sample program for Raspberry Pi 4# 5# how to setup /dev/spidev?.? 6# $ suod modprobe spi_bcm2708 7# 8# how to setup spidev 9# $ sudo apt-get install python-dev python-pip 10# $ sudo pip install spidev 11# 12import spidev 13import time 14 15class MCP3208: 16 def __init__(self, spi_channel=0): 17 self.spi_channel = spi_channel 18 self.conn = spidev.SpiDev(0, spi_channel) 19 self.conn.max_speed_hz = 1000000 # 1MHz 20 21 def __del__( self ): 22 self.close 23 24 def close(self): 25 if self.conn != None: 26 self.conn.close 27 self.conn = None 28 29 def bitstring(self, n): 30 s = bin(n)[2:] 31 return '0'*(8-len(s)) + s 32 33 def read(self, adc_channel=0): 34 # build command 35 cmd = 128 # start bit 36 cmd += 64 # single end / diff 37 if adc_channel % 2 == 1: 38 cmd += 8 39 if (adc_channel/2) % 2 == 1: 40 cmd += 16 41 if (adc_channel/4) % 2 == 1: 42 cmd += 32 43 44 # send & receive data 45 reply_bytes = self.conn.xfer2([cmd, 0, 0, 0]) 46 47 # 48 reply_bitstring = ''.join(self.bitstring(n) for n in reply_bytes) 49 # print reply_bitstring 50 51 # see also... http://akizukidenshi.com/download/MCP3204.pdf (page.20) 52 reply = reply_bitstring[5:19] 53 return int(reply, 2) 54 55if __name__ == '__main__': 56 spi = MCP3208(0) 57 58 count = 0 59 a0 = 0 60 61 while True: 62 count += 1 63 a0 += spi.read(0) 64 65 if count == 10: 66 print "ch0=%04d" % (a0/10) 67 count = 0 68 a0 = 0
下のコメントの
def readAverage(self, adc_channel=0, nAverage=128, bDebug=0): raw = 0 for i in range(nAverage): raw += self.read(adc_channel) fMean = raw / nAverage if bDebug: print('nAverage={:d}: mean value={:7.2f}ticks'.format(nAverage, fMean)) return fMean
を追加し、
if __name__ == '__main__': spi = MCP3208(spi_channel=0) while True: a0 = spi.readAverage(0, nAverage=256) print('rawValues: {:7.2f}'.format(a0)) #time.sleep(0.5)
mainを修正しました。
このサイトのプログラムを使って、距離センサから受け取った値を表示してみています。
小数点第二位まで表示するようになっていると思ったのですが、小数点以下は全部0になっていました。
小数点以下も表示して欲しいのですが、プログラムを見てもよく分かりません。
どなたか分からないでしょうか。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/09/28 00:29
2017/09/28 00:31
2017/09/28 00:38
2017/09/28 00:40
2017/09/28 00:42