如何从串口arduino读取python上收到的整数字符串

时间:2013-07-09 16:47:39

标签: python serial-port arduino list-comprehension pyserial

我正在将一个值列表(例如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'

你可以看到我正在获得价值,但他们被截断了。有谁能告诉我我在哪里出错了。非常感谢。

1 个答案:

答案 0 :(得分: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)