简体   繁体   English

While循环不会实时更新

[英]While loop doesn't update real time

I wrote this code using python for raspberry pi. 我使用python为树莓派编写了此代码。 But I am struggling with the code. 但是我在代码方面苦苦挣扎。 The while loop doesn't break. while循环不会中断。

w=1
z=0

def auto_1(w,z):
    w=1
    z=0
    return w,z

def manual_1(w,z):
    w=0
    z=1
    return w,z

GPIO.add_event_detect(Manual, GPIO.RISING, callback=lambda *i: manual_1(w,z), bouncetime=300)
GPIO.add_event_detect(Auto, GPIO.RISING, callback=lambda *i: auto_1(w,z), bouncetime=300)

while w==1:
      print("Auto")
      pfr_mains_1(PFRMains,PFRGen,GenStartOut,MainsCont,GenCont)
      pfr_mains_0(PFRMains,PFRGen,GenStartOut,MainsCont,GenCont)
      time.sleep(3)
      if w==0:
         break

The while loop doesn't break even though the "manual" event detected. 即使检测到“手动”事件,while循环也不会中断。 The code runs fine but the loop does not break when an event detected. 代码运行正常,但是在检测到事件时循环不会中断。 It seems the w value does not get updated from the initial value. 似乎w值没有从初始值更新。 But I have no clue what to do. 但是我不知道该怎么办。 Please help me with this.Thank you. 请帮助我。谢谢。

Your main script body is using the global variable w. 您的主要脚本主体正在使用全局变量w。 However, the two functions you defined have each their own local variable w. 但是,您定义的两个函数各自具有自己的局部变量w。 Anything these functions do to w stays inside the respective function. 这些函数对w所做的任何事情都保留在各自的函数内部。

You could declare w as global in both functions to always access the global w, but that's not really good practice. 可以在两个函数中都将w声明为全局变量,以始终访问全局w,但这并不是真正的好习惯。 It would be better to assign the functions' result to the global w. 将函数的结果分配给全局w会更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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