用Python读取串行数据

时间:2018-01-29 06:50:29

标签: python arduino

我正在使用Python从Arduino读取串行数据。这是我的代码。

import serial #Import Serial Library

arduino = serial.Serial('COM7',9600)
def getDistance():  
    while True:
        if (arduino.inWaiting()>0):
            Data = arduino.readline()
            list_of_pin_sensors = str(Data)        
            sensor = list_of_pin_sensors.replace('\r', '').replace('\n', '')
            ping_list = sensor.split(",")
            # print ping_list # will continue printing unless stopped
            # some output
            # ['214', '171', '19', '11', '22', '']
            # ['211', '169', '19', '11', '22', '']
            #.....
            #.....
            return ping_list
            #output only one time then function terminates
            #sample output 
            #['191', '169', '19', '11', '22', '']
            #then the program terminates

print getDistance()

如何在不破坏函数且不使用Python yield的情况下返回值?任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

您可以将值附加到列表中,然后最后返回列表。

<强>实施例

import serial #Import Serial Library

arduino = serial.Serial('COM7',9600)
def getDistance():
    result = []  
    while True:
        if (arduino.inWaiting()>0):
            Data = arduino.readline()
            list_of_pin_sensors = str(Data)        
            sensor = list_of_pin_sensors.replace('\r', '').replace('\n', '')
            ping_list = sensor.split(",")
            # print ping_list # will continue printing unless stopped
            result.append(ping_list)

    return result

print getDistance()