AlexTsp
AlexTsp

Reputation: 19

Reading and storing values in list

Currently doing project where I use raspberry pi as a monitoring device for motors. In the part of code below I'm trying to read measurements from motor controller and store them in the buffer by 5 values and after print them:

def readFromSerial(prefix, command):
    buffer = []
    ser.write(command.encode()) #send data to controller
    data = ser.readline().decode().strip() #receive data from controller
    #Checking if data is received and extracting value
    if prefix in data:
        value = int(data.split('=')[1])
        #print("Asked: " + str(command) + ". Got value: " + str(value))
        buffer.append(value)
        if len(buffer) > 5:
            print(*buffer)
            buffer = buffer[5:]
    else:
        print("Message is not received")

However when I'm trying to run the code, print(*buffer) is not printing anything in the terminal. Maybe I'm not storing values to buffer correctly but I can't figure out mistake by myself so any help is greatly appreciated.

Upvotes: 0

Views: 61

Answers (1)

Chris Doyle
Chris Doyle

Reputation: 11992

In your code you create the buffer as an empty list. You send a command to the controller and you get a response from the controller. if the prefix is in the response from the controller you split the response by = and take the 2nd element and convert it to an int.

So now you have an int stored in the variable called value. at this point the buffer is still empty. you then append that value to the buffer and the length of the buffer is 1.

you check if the length of the buffer is 5, well its not its only 1 so you dont call your print.

Then thats it, thats the end of your function, your function call returns. So your buffer only ever contains 0 or 1 elements and never reaches 5.

If you call the function again then you will create a new empty list and assign it to buffer so again the buffer is empty.

Upvotes: 1

Related Questions