简体   繁体   中英

Read serial data in Python

I am reading serial data from Arduino using Python. Here is my code.

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

How do I return the values without breaking the function and not using Python yield ? Any help is appreciated.

You can append the value to a list and then return the list in the end.

Ex:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM