从arduino读取串行数据 - 语法错误无效

时间:2014-03-20 18:06:36

标签: python arduino pyserial

我试图编写一个python脚本来读取arduino串口的值并将其写入文件,以便我可以记录数据。

arduino代码冗长而复杂,但我使用Serial.println()将一个整数打印到串口(位于/ dev / ttyACM0)

import sys
import serial
import getpass
import datetime
import instrumentDriver

"""location of the arduino"""
location = '/dev/ttyACM0'

"""Connect to the arduino"""
arduino = instrumentDriver.serialDevice(location)

"""Successfully connected!"""
filename = str(sys.argv[1])
dataFile = open(filename+'.dat','w')

"""The main loop -- data is taken here and written to file"""
while True:
    try:
        datum = arduino.read()
        print datum
        dataFile.write(datetime.datetime.now().strftime("%Y-%m-%d"))
        dataFile.write('\t')
        dataFile.write(datum)
        dataFile.write('\n')
    except:
        dataFile.close()
        break

instrumentDriver.py只是pySerial的包装器:

class serialDevice:
    def __init__(self,location):
        self.device = location
        self.port = serial.Serial(location,9600)

    def write(self,command):
        self.port.write(command)

    def read(self):
        return self.port.readline()

我几年前就使用过这段代码而且工作正常,但现在似乎失败了,我并不完全确定原因。我在第45行得到了一个SyntaxError:

scottnla@computer-1 ~/Documents/sensorTest $ python readSerial.py file
  File "readSerial.py", line 45
    print datum
        ^
SyntaxError: invalid syntax

我尝试更改了print语句,但无论我打印什么,我都会遇到语法错误 - 我推测问题实际上可能是arduino.read()行。< / p>

非常感谢任何建议!

1 个答案:

答案 0 :(得分:1)

还有一个缩进问题;改写如下,它应该运行:

import sys
import datetime

class serialDevice:
       def __init__(self,location):
              self.device = location
              self.port = sys.stdin # changed to run on terminal

       def write(self,command):
              self.port.write(command)

       def read(self):
              return self.port.readline()

"""location of the arduino"""
location = '/dev/ttyACM0'

"""Connect to the arduino"""
arduino = serialDevice(location)

"""Successfully connected!"""
filename = str(sys.argv[1])
dataFile = open(filename+'.dat','w')

"""The main loop -- data is taken here and written to file"""
while True:
    try:
        """retrieve the raw analog number from the arduino's ADC"""
        datum = arduino.read()
        """write it to file, along with a timestamp"""
        print datum
        dataFile.write(datetime.datetime.now().strftime("%Y-%m-%d"))
        dataFile.write('\t')
        dataFile.write(datum)
        dataFile.write('\n')
    except KeyboardInterrupt:
        """this allows for the user to CTRL-C out of the loop, and closes/saves the file we're writing to."""
        dataFile.close()
        break
相关问题