对于我学校的化学研究项目,我们使用的是 ADS8320 数据表:here , 以非常快的速度从电位器读取电压读数。我们正在使用树莓派 3,并尝试通过 Pi 上的 GPIO 和 SPI 引脚获取数据。我能够在 python 中使用这段代码来做到这一点:
import time
import os
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
start = time.time()
PIN_CLK = 11
PIN_DO = 9
PIN_DI = 10
PIN_CS = 8
GPIO.setup(PIN_DI, GPIO.OUT)
GPIO.setup(PIN_DO, GPIO.IN)
GPIO.setup(PIN_CLK, GPIO.OUT)
GPIO.setup(PIN_CS, GPIO.OUT)
def getADC(channel):
GPIO.output(PIN_CS, True) #used to clear last transmission
GPIO.output(PIN_CS, False) #Bringing cs to low
GPIO.output(PIN_CLK, False) #starting the clock
for i in [1,1,channel]: #start of a new bit assignment
if (i==1):
GPIO.output(PIN_DI, True)
else:
GPIO.output(PIN_DI,True)
GPIO.output(PIN_CLK, True)
GPIO.output(PIN_CLK, False)
ad = 0
for i in range (18):
GPIO.output(PIN_CLK, True)
GPIO>output(PIN_CLK, False)
ad <<= 1
if (GPIO.input(PIN_DO)):
ad |= 0x1
GPIO.output(PIN_CS, True) #reset
return ad
if __name__ == "__main__":
while True:
bitReading = getADC(0)
Data = float(bitReading/65535.0*3.3)
getTime = float(time.time() - start)
print ("%.5f" % getTime + "," + "%.5f" % Data)
time.sleep(0)
此代码的主要问题是虽然我能够接收数据,但它比我预期的要慢得多。从数据表上看,它的运行频率约为 100Khz,但问题是目前它的运行频率为毫秒。我将如何加速这段代码?我是一个完全的编码初学者,我拥有的大部分工作代码都来 self 通过谷歌搜索找到的网站。我看过关于 spidev 的东西,但我不确定如何实现它们。对此的任何帮助都会很棒,因为我是化学专业而不是 comp sci 专业,所以我对这个问题深有感触。如果您有任何疑问或者我遗漏了任何重要信息,请告诉我!
请您参考如下方法:
在大多数情况下,看起来您的想法是正确的。根据我对规范的理解,我更改了你的 getADC 函数,我不确定你在“开始新的位分配”部分做了什么。
我没有任何东西可以测试,所以我不确定这是否有效,但它节省了几个时钟周期,删除它并清理更多函数以读取数据。
如下所示,您可以做的另一件事是等待将原始 ADC 读数转换为 float ( float 通常需要大量时间/处理能力)。因此,只需阅读一些时间,将数据存储起来,然后格式化并稍后输出。我不确定这是否适用于您的应用程序,但这是一个想法。
希望这能有所帮助,至少您应该尝试等待转换为 float 并输出。
import time
import os
import RPi.GPIO as GPIO
PIN_CLK = 11
PIN_DO = 9
PIN_DI = 10
PIN_CS = 8
def init_gpio():
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(PIN_DI, GPIO.OUT)
GPIO.setup(PIN_DO, GPIO.IN)
GPIO.setup(PIN_CLK, GPIO.OUT)
GPIO.setup(PIN_CS, GPIO.OUT)
def getADC(channel):
# A falling CS signal initiates the conversion and data transfer
GPIO.output(PIN_CS, False)
# After the fifth falling DCLOCK edge
# DOUT is enabled and outputs a LOW value for one clock period
# So after 6 clock periods, we have data
for i in range(0, 6):
GPIO.output(PIN_CLK, True)
GPIO.output(PIN_CLK, False)
# For the next 16 DCLOCK periods,
# DOUT outputs the conversion result, most significant bit first
ad = 0
for i in range(0, 16):
# Get next data bit
ad <<= 1
# Get to next bit by advancing clock
GPIO.output(PIN_CLK, True)
GPIO.output(PIN_CLK, False)
GPIO.output(PIN_CS, True) # reset
return ad
if __name__ == "__main__":
init_gpio()
start = time.time()
results = []
# Run for 60 seconds
while ((time.time() - start) < 60):
results.append(getADC(0))
for result in results:
# This was slowing you down
# You could capture data and then output it like this
Data = float(result / 65535.0 * 3.3)
getTime = float(time.time() - start)
print("%.5f" % getTime + "," + "%.5f" % Data)
