如何使串口和 matplotlib 在同一个 Python scrypt 中工作

我正在基于在 Arduino 微控制器和 Raspberry Pi 计算机上构建的项目开展项目:

Arduino 从程序循环开始的那一刻开始测量时间。当用户按下按钮时它停止。该分数将通过串口发送到专门准备的 csv 文件。同一时间update()函数将从该文件中取出值并绘制实时图形和直方图。

当脚本运行时只执行一个函数时,问题就开始了。我检查了一些选项并决定尝试threading

  1. https://docs.python.org/3/library/threading.html

  2. https://docs.python.org/2/library/threading.html

  3. https://www.tutorialspoint.com/python/python_multithreading.htm

但是它可以编译,但不能正确执行。我不要求准备好的代码或链接 - 只是建议或一些提示会非常有帮助:

import pandas as pd

import matplotlib.pyplot as plt

import matplotlib.animation as animation

import serial

import datetime

import threading


fig, axes = plt.subplots(nrows=2, ncols=1)

ax1, ax2 = axes.flatten()


scores_to_read = serial.Serial ('/dev/ttyACM0', 9600)

file = open ("/home/pi/Desktop/Noc_Naukowcow/score_board.csv", 'r+')    


def update(i):

     file_data = pd.read_csv("/home/pi/Desktop/Noc_Naukowcow/score_board.csv", delimiter="\t", 

parse_dates=[0], header=None, usecols=[0, 1])

     ax1.clear()

     ax2.clear()

     ax1.plot(file_data[0],file_data[1])

     ax2.hist([file_data[1],], bins='auto', histtype='bar')

     #ax1.set_title('History')

     ax1.set_xlabel('Measurement time')

     ax1.set_ylabel('Reaction time [s]')

     #ax2.set_title('Histogram')

     ax2.set_xlabel('Reaction time [s]')

     ax2.set_ylabel('Number of results')

     ani = animation.FuncAnimation(fig, update, interval=1000)

     plt.plot()


def serial_port(file):

    file.read()

    new_score = scores_to_read.readline()

    print(new_score)

    score = new_score.decode('utf-8').strip() + "\n"

    score_time = '{:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now())

    file.write(score_time)

    file.write('\t')

    file.write(score)

    file.flush()


thread1 = threading.Thread(target=serial_port, args=(file))

thread1.start()


thread2 = threading.Thread(target=update, args=(fig))

thread2.start()


慕沐林林
浏览 172回答 1
1回答

萧十郎

该ARGS属性必须是一个元组不是一个单一的值。对于 Python,单例元组必须有一个尾随逗号,例如(foo,).要解决这个问题,请添加一个尾随逗号:thread1 = threading.Thread(target=serial_port, args=(file,))thread1.start()thread2 = threading.Thread(target=update, args=(fig,))thread2.start()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python