我有一个Arduino草图,它将时间,温度值放入loggedData.dat
文件中。只需使用Arduino串行监视器查看文件就可以了。但是当我尝试使用下面的python脚本用它绘制图形时,我得到一个错误:
File "loggedData.py", line 44, in <module>
x.append(Float(p[0])) ValueError: could not convert string to float:
如果我只是通过手动输入与原始文件完全相同的值来创建名为loggedData.dat
的文件,例如:
1.00, 71.3
2.00, 71.6
3.00, 71.7
4.00, 71.8
工作正常,我得到了一个很好的图表。显然有一些东西进入loggedData.dat
文件,我无法使用串行监视器看到。有什么建议吗?
import sys, serial, time
from matplotlib import pyplot as plt
serPort = '/dev/ttyS1'
dataFile = open( "./loggedData.dat", "w" );
print "\nAttempting to open Serial Port : ", serPort, "for logging\n"
ser = serial.Serial( serPort, 9600 )
if ( ser.isOpen() == False ):
print "ERROR: Unable to open serial port ", serPort, "\n"
exit(0);
else:
print "Port ", serPort, " opened\n"
sys.stdout.flush()
print "Hit return to start logging ..."
key = sys.stdin.readline()
ser.write('1');
print "Logging started. CTRL-C to stop\n"
while True:
try:
line = ser.readline()
print line;
dataFile.write( line )
except KeyboardInterrupt: # CTRL-C triggered here
ser.write( '0' )
print "Logging Stopped\n"
break;
ser.flush()
ser.close()
dataFile.close()
print "Port ", serPort, " closed\n"
print "\nPlot graph (y/n) ?"
key = sys.stdin.read(1)
if key == 'y':
print "\nPlotting graph ...\n"
f = open( "loggedData.dat", 'r' )
lines = f.readlines()
f.close()
x = []
y = []
for line in lines:
p = line.split( ',' )
x.append( float( p[0] ) )
y.append( float( p[1] ) )
fig = plt.figure()
graph = fig.add_subplot(111)
graph.set_title( "Data logged from Arduino UNO" )
graph.plot( x, y, 'ro' )
plt.show()
print "Plot complete\n"
else:
print "Finishing\n"
time.sleep(3)
答案 0 :(得分:0)
如果ctrl字符卡在你的变量上 - 你可以尝试
x.append(Float(p[0].strip()))