使用预定函数变量

Using a scheduled function variable

我正在编写一个脚本,该脚本使用计划每 X 秒 运行 定义的函数。预定函数工作正常,问题是我无法在下游使用它,特别是将变量 g 添加到名为 numlist 的列表中。我该怎么做?

使用的代码:

import serial
import numpy as np
import time
from random import randint
import matplotlib.pyplot as plt
import schedule

ser = serial.Serial('COM1', 115200)

def read_serial_port():
    global g
    ser.flushInput()
    x = ser.readline().decode("utf_8").rstrip('\n\r')
    g=float(x)
    print(g)

rate_in_seconds = 0.5
schedule.every(rate_in_seconds).seconds.do(read_serial_port)

numlist = [0]

start_time = int(round(time.time()))
timelist = [start_time]

speed = []

while True:
    schedule.run_pending()
    time.sleep(1)

    for x in range(0, 10):
        elapsed_time = int(round(time.time() - start_time))
        numlist.append(g)
        print(numlist[-1])
    # timelist.append(elapsed_time)
        timelist.append(int(round(time.time())))

        x = numlist[-1]
        y = numlist[len(numlist)-2]
        t1 = timelist[-1]
        t2 = timelist[len(timelist)-2]

    # speed calculation
        kmh = abs((x-y)/(t2-t1))*3.6
        speed.append(kmh)

    # brake distance calculation
        d = (kmh ** 2)/(250*0.8)
        print('speed', speed[-1], 'km/h')
        print('total distance:', numlist[-1], 'm')
        print('breaking distance:', d, 'm')

        if d >= numlist[-1]:
            print('run!')
            print('\n')


#plt.plot(speed)
#plt.show()

当我运行它时,它一直说变量g不存在:

Error message

谢谢

您必须在 read_serial_port() 函数之外定义变量 g。 比如 -

g = None  # or something else

def read_serial_port():
    global g    # global g here actually means, it is pointing to the variable out of the function and the manipulation will impact on g variable declared outside of the function 
    ser.flushInput()
    x = ser.readline().decode("utf_8").rstrip('\n\r')
    g=float(x)
    print(g)