簡體   English   中英

在Python中讀取串行數據

[英]Read serial data in Python

我正在使用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情況下返回值? 任何幫助表示贊賞。

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

例如:

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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM