我正在编写一个脚本,该脚本使用计划每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
不存在:
谢谢
您必须在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)