0

我正在将值列表(例如 80,539,345,677)从 Arduino 发送到在我的 RPi 上运行的 Python 应用程序。我没有成功提取值并将它们分配给应用程序中的相应变量或对象。

这是我的代码:

def read_values():
  #if DEBUG:
  print "reading arduino data"
  ser = serial.Serial('/dev/ttyUSB0', 9600)
  print "receiving arduino data"
  ser_line = ser.readline()
  print ser_line
  ser.close()
  ser_list = [int(x) for x in ser_line.split(',')]

  ambientLight = ser_list[1]

  print ambientLight

  return ambientLight

我从 Python 得到的是:

reading arduino data
receiving arduino data
80,477,82,2

Traceback (most recent call last):
  File "serialXivelyTest4c.py", line 77, in <module>
run()

File "serialXivelyTest4c.py", line 63, in run
ambientLight = read_values()
  File "serialXivelyTest4c.py", line 27, in read_values
ser_list = [int(x) for x in ser_line.split(',')]
ValueError: invalid literal for int() with base 10: '8254\r80'

你可以看到我得到了值,但是它们被截断了。谁能告诉我这里哪里出错了。非常感谢。

4

1 回答 1

0

我从未使用过 Arduino,但这是我使用不同板从串行读取的方式。我用的是串行的。

import streamUtils as su  # see below

ser = su.connectPort("/dev/tty.SLAB_USBtoUART")  # make sure you have the right port name


data = ""
while True:
    try:
        data = data + ser.read(1)       # read one, blocking
        time.sleep(1)                   # give it time to put more in waiting
        n = ser.inWaiting()             # look if there is more
        if n:
            data = data + ser.read(n)   # get as much as possible
            # I needed to save the data until I had complete
            # output.  

            if data:
                # make sure you have the whole line and format
        else:
            break
    except serial.SerialException:
        sys.stderr.write("Waiting for %s to be available" % (ser.name))
        sys.exit(1)

sys.stderr.write("Closing port\n")
ser.close()

这是 streamUtils.connectPort():

import serial

def connectPort(portname):
    # connect to serial port
    ser = serial.Serial()
    ser.port = portname
    ser.baudrate = 9600
    ser.parity = serial.PARITY_NONE
    ser.stopbits = serial.STOPBITS_ONE
    ser.bytesize = serial.EIGHTBITS
    ser.timeout = 15            # need some value for timeout so the read will end

    try:
        ser.open()
    except serial.SerialException:
        sys.stderr.write("Could not open serial port %s\n" % (ser.name))
        sys.exit(1)

    return (ser)
于 2013-07-09T17:03:43.123 回答