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

时间:2018-09-11 09:44:46

标签: python multithreading raspberry-pi

我正在基于基于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()

我得到了一些警告:

Exception in thread Thread-1:
Traceback (most recent call last):
  File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.5/threading.py", line 862, in run
    self._target(*self._args, **self._kwargs)
TypeError: serial_port() takes 1 positional argument but 11 were given

这个[...] TapeError: serial port_() takes 1 positional argument but 11 were given说的是csv文件中的11条记录-对吗?

1 个答案:

答案 0 :(得分:0)

args 属性必须是一个元组,而不是单个值。使用Python时,单例元组必须带有尾随逗号,例如(foo,)

要解决此问题,请添加结尾逗号:

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

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