我是编程的新手,几周后做了一些简单的程序;比如从arduino捕获串行数据并将其保存到文本文件中。 现在我想结合几件事。我想使用python捕获串行数据,提示输入端口和文件名,获取数据并实时绘制,然后当arudino不再连接时,保存并关闭文件。这是我到目前为止的代码。
问题是图表根本不是实时的。传感器几乎没有变化。我有时也会得到一个matplotlib折旧警告。我想知道是否有快速修复或者我是否遗漏了一些关键的东西。非常感谢你!
import numpy
import matplotlib.pyplot as plt
import math
import time
import pylab
from drawnow import drawnow
import csv
import serial
import os
import glob
import sys
filename = raw_input("Save file as: ")
saveFile = open(filename, 'w')
print "Available ports: "
def serial_port():
if sys.platform.startswith('win'):
ports = ['COM%s' % (i + 1) for i in range (256)]
elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
ports = glob.glob('/dev/tty/[A-Za-z]*')
elif sys.platform.startswith('darwin'):
ports = glob.glob('/dev/tty.*')
else:
raise EnvironmentError('Unsupported Platform')
result = []
for port in ports:
try:
s = serial.Serial(port)
s.close()
result.append(port)
except (OSError, serial.SerialException):
pass
return result
if __name__ == '__main__':
print serial_port()
serialport = raw_input("Enter Port: ")
port1 = serialport
print "Connecting to port...", port1
arduino1 = serial.Serial(port1, 115200)
print "Arduino Detected"
#create arrays with the following names
Time = []
analog0 = []
analog1 = []
voltage0 = []
voltage1 = []
Temp = []
RH = []
#reading data from the serial port
#telling Matplot.lib to plot live data
plt.ion()
#creates a function to make a plot we want
def Fig1():
plt.plot(analog0, 'r-')
plt.title("Analog0 Data")
plt.ylim(405, 425)
plt.grid(True)
plt.ylabel("analog")
plt.xlabel("milliseconds")
x = os.path.exists(port1)
while x==0:
arduinoString = arduino1.readline()
saveFile.write(arduinoString)
dataArray = arduinoString.split(',')
time = float(dataArray[0])
a0 = float(dataArray[1])
a1 = float(dataArray[2])
v0 = float(dataArray[3])
v1 = float(dataArray[4])
temp = float(dataArray[5])
rh = float(dataArray[6])
#filling our arrays with those new data values (floats)
Time.append(time)
analog0.append(a0)
analog1.append(a1)
voltage0.append(v0)
voltage1.append(v1)
Temp.append(temp)
RH.append(rh)
drawnow(Fig1)
plt.pause(0.00010)
else:
saveFile.close()