gpt4 book ai didi

Python 变量覆盖自身

转载 作者:太空宇宙 更新时间:2023-11-03 17:16:38 26 4
gpt4 key购买 nike

我有以下代码块。 fanSensor() 会自动运行,但如果我调用 fanOn()fanOverride 会将其自身设置回 0。有人可以帮我弄清楚我要做什么吗?做错了吗?

..顺便说一句,休眠 while 循环线程会节省处理能力吗?..

import RPi.GPIO as GPIO
import os
import time
import _thread

fanOnTemp = 57
fanOffTemp = 54
fanPin = 40
currentTemp = 0.0
fanOverride = 0

GPIO.setmode(GPIO.BOARD) #Labels the pins by order on the board
GPIO.setup(fanPin, GPIO.OUT) #Allows control of fanPin

def getFanState():
print(GPIO.input(fanPin)) #Prints the state of the fanPin

def fanOn():
GPIO.output(fanPin, 1) #Set fanPin on
fanOverride = 1

def fanOff():
GPIO.output(fanPin, 0) #Set fanPin off
fanOverride = 0

def getTempF():
print(Temp()*(9/5)+32)

def getTemp():
print(Temp())

def Temp():
seconds=10
x=0
for i in range(0,seconds):
temp=((os.popen('vcgencmd measure_temp').readline()).replace("temp=","").replace("'C\n",""))
x+=float(temp)
time.sleep(1) #Sleep the thread for 1 second
x=x/seconds #Calculate the average temperature
return(x)

def fanSensor():
while 1:
time.sleep(5)
currentTemp = float((os.popen('vcgencmd measure_temp').readline()).replace("temp=","").replace("'C\n",""))
print ("Fan Temperature: %.2f" % currentTemp) #removes all but 2 decimal places
print ("Fanoverride: "+str(fanOverride))
if fanOverride == 0: #Check for fan override on
if currentTemp > fanOnTemp:
GPIO.output(fanPin, 1)
elif currentTemp < fanOffTemp:
GPIO.output(fanPin, 0)

_thread.start_new(fanSensor,())

最佳答案

假设算法正确,如果您需要两个函数共享其状态(即作用于同一个变量),则需要将 fanOverride 声明为全局

def fanOn():
global fanOverride
GPIO.output(fanPin, 1) #Set fanPin on
fanOverride = 1

def fanOff():
global fanOverride
GPIO.output(fanPin, 0) #Set fanPin off
fanOverride = 0

看看this SO Q&A有关全局的更多信息

关于Python 变量覆盖自身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33599951/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com