【发布时间】:2021-03-11 15:20:06
【问题描述】:
我是 Python 新手,我正在尝试将两个脚本组合在一起。第一个脚本从传感器读取一个值并将其写入 .csv 文件。
#!/usr/bin/python
import csv
import spidev
import time
#Define Variables
x_value = 0
pad_value = 0
delay = 0.1
pad_channel = 0
fieldnames = ["x_value", "pad_value"]
#Create SPI
spi = spidev.SpiDev()
spi.open(0, 0)
spi.max_speed_hz=1000000
def readadc(adcnum):
# read SPI data from the MCP3008, 8 channels in total
if adcnum > 7 or adcnum < 0:
return -1
r = spi.xfer2([1, 8 + adcnum << 4, 0])
data = ((r[1] & 3) << 8) + r[2]
return data
#Write headers
with open('data.csv', 'w') as csv_file:
csv_writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
csv_writer.writeheader()
#Write values
while True:
with open('data.csv', 'a') as csv_file:
csv_writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
info = {
"x_value": x_value,
"pad_value": pad_value
}
csv_writer.writerow(info)
#Update values
x_value += 1
pad_value = readadc(pad_channel)
print(x_value, pad_value)
time.sleep(delay)
第二个脚本读取 .csv 文件并使用 matplotlib 将数据绘制到图表中。
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
plt.style.use('fivethirtyeight')
def animate(i):
data = pd.read_csv('data.csv')
x = data['x_value'].tail(600)
y = data['pad_value'].tail(600)
plt.cla()
plt.plot(x, y)
ani = FuncAnimation(plt.gcf(), animate, interval=100)
plt.tight_layout()
plt.show()
我可以分别运行这两个脚本并且它们可以工作,但我想将它们组合成一个脚本。 我试图合并它们,但是当它到达 plt.show() 时,它会显示图形但不会继续。我尝试了 plt.show(block=False),它继续,但不显示图表。
#!/usr/bin/python
import csv
import spidev
import time
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
#Define Variables
x_value = 0
pad_value = 0
delay = 0.1
pad_channel = 0
fieldnames = ["x_value", "pad_value"]
#Create SPI
spi = spidev.SpiDev()
spi.open(0, 0)
spi.max_speed_hz=1000000
def readadc(adcnum):
# read SPI data from the MCP3008, 8 channels in total
if adcnum > 7 or adcnum < 0:
return -1
r = spi.xfer2([1, 8 + adcnum << 4, 0])
data = ((r[1] & 3) << 8) + r[2]
return data
#Animate graph
def animate(i):
data = pd.read_csv('data.csv')
x = data['x_value']
y = data['pad_value']
plt.cla()
plt.plot(x, y)
plt.style.use('fivethirtyeight')
plt.tight_layout()
plt.show(block=False)
#Write headers to CSV file
with open('data.csv', 'w') as csv_file:
csv_writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
csv_writer.writeheader()
#Append values to CSV file
while True:
with open('data.csv', 'a') as csv_file:
csv_writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
info = {
"x_value": x_value,
"pad_value": pad_value
}
csv_writer.writerow(info)
#Update values
x_value += 1
pad_value = readadc(pad_channel)
print(x_value, pad_value)
time.sleep(delay)
plt.style.use('fivethirtyeight')
ani = FuncAnimation(plt.gcf(), animate, interval=100)
plt.tight_layout()
plt.show(block=False)
有没有一种简单的方法可以将这两者结合起来?
【问题讨论】:
-
您是想将两者结合起来作为将代码放在一起还是需要在另一个中使用脚本的某些功能
-
@MarioKhoury 我想制作一个脚本来读取数据,将其写入 .csv,并显示数据图表。
标签: python matplotlib