从Arduino读取串行数据 -- 语法错误

0 投票
1 回答
2192 浏览
提问于 2025-04-17 23:11

我正在尝试写一个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行我遇到了一个语法错误:

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

我尝试过修改打印语句,但无论我打印什么,都会出现语法错误——我猜问题可能出在arduino.read()这一行。

如果能给点建议,我将非常感激!

1 个回答

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

撰写回答