【发布时间】:2016-01-21 07:30:51
【问题描述】:
我正在 python 中运行一个简单的 PID 控制程序。基本上是一个无限循环,从传感器读取然后计算适当的控制信号,并将诊断信息输出到终端。
但是,有时在查看诊断信息时,我想更改 PID 系数(本质上是循环使用的一些常数),方法是从循环中中断,接受用户输入,然后返回到同一个循环。我想这样做任意次数。
使用“goto”,这将是简单易行的,正是我想要的。有人可以给我一些 python 伪代码来做到这一点吗?我实在想不出该怎么做。我可以用 CTRL+C 异常处理程序中断循环,但是我不能回到主循环。
必须有一些非常简单的方法可以做到这一点,但我想不出。想法? 我的代码片段:
while True:
t0 = get_temp_deg_c(thermocouple1)
print "Hose Temperature = " + str(t0) + " deg C"
t1 = get_temp_deg_c(thermocouple2)
print "Valve Temperature = " + str(t1) + " deg C"
# write temps to file
fi.write(str(t0))
fi.write(" " + str(t1) + "\n")
error = setpoint - t0
print "Setpoint = " + str(setpoint) + " deg C"
print "Error = " + str(error) + " deg C"
percent_error = error/setpoint*100
print "Percent error = " + str(percent_error) + " %"
duty_out = p.GenOut(percent_error)
print "PID controller duty output: " + str(duty_out) + " %"
# clamp the output
if(duty_out) > 100:
duty_out = 100
if(duty_out < 0):
duty_out = 0
PWM.set_duty_cycle(PWM_pin, duty_out)
# do we need to increment the setpoint?
if( (setpoint - setpoint_precision) ... # omitted logic here
# Here we return to the top
【问题讨论】:
-
你能修改代码以在线程中运行主循环吗?
-
也许线程 while 循环可以完成工作,但我不确定线程是否允许外部线程引用。你能给我们一个实际的代码示例吗?
-
您可以构建交互式 shell,当 pid 循环在线程中运行时,用户可以在程序中查看变量,an example that will let you also throw the whole thing into the background
-
基本上,您似乎想轮询键盘的输入缓冲区?这个答案提到了一些方法。 stackoverflow.com/questions/292095/…
-
大家好,添加了包含要点的代码 sn-p。