簡體   English   中英

如何為傳感器組合 python 腳本?

[英]How do I combine python scripts for a sensor?

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

有沒有一種簡單的方法可以將這兩者結合起來?

您可以通過將 plot 設置為交互模式來交互更改 canvas 上的數據,如下所示:

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

有關整個教程,請參閱此鏈接

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM