首页 > 解决方案 > 如何为传感器组合 python 脚本?

问题描述

我是 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)

有没有一种简单的方法可以将这两者结合起来?

标签: pythonmatplotlib

解决方案


您可以通过将绘图设置为交互模式来交互更改画布上的数据,如下所示:

import matplotlib.pyplot as plt
import numpy as np
import time

phase = 0
delay = 0.1
t = 0
x = np.linspace(t, t+2, 200)
data = 0.5*np.sin(x)+.5

#Setting interactive mode on plt
plt.ion()

#create new figure
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_ylim((-1.1, 1.1))
line1, = ax.plot(x, data, 'b-')

while True:
    #I generate some random data, you will use your data (from the csv)
    x = np.linspace(t, t+2, 200)
    data = np.sin(x)

    line1.set_ydata(data)
    line1.set_xdata(x)

    #Set the xlim to contain new data
    ax.set_xlim((x[0], x[-1]))

    #This shows newly set xdata and ydata on the plot
    fig.canvas.draw()

    #You need to use plt.pause otherwise the plot won't show up
    plt.pause(0.001)
    time.sleep(delay)

    #Just another variable I used to generate new data
    t += 1

有关整个教程,请参阅此链接。


推荐阅读