gpt4 book ai didi

python - 不断更新全局变量只打印第一个值

转载 作者:太空宇宙 更新时间:2023-11-04 00:49:46 25 4
gpt4 key购买 nike

我正在尝试在 7 段显示器上显示来自温度传感器的温度。两者都连接到我的 Raspberry Pi。我需要将当前温度存储在一个变量中,当然它总是在变化。

我的问题是变量只打印脚本运行时的温度。它不会随着温度的变化而变化。

import os
import time

os.system('modprobe wl-gpio')
os.system('modprobe wl-therm')

temp_sensor = '/sys/bus/w1/devices/28-0316201553ff/w1_slave'

temp_f = 0

def temp_raw():
f = open(temp_sensor, 'r')
lines = f.readlines()
f.close()
return lines


def read_temp():
lines = temp_raw()
while lines[0].strip()[-3:] != 'YES':
time.sleep(0.2)
lines = temp_raw()

temp_output = lines[1].find('t=')
if temp_output != -1:
temp_string = lines[1].strip()[temp_output + 2:]
temp_c = float(temp_string) / 1000.0
temp_f = temp_c * 9.0 // 5.0 + 32.0
global temp_f
temp_f = int(temp_f)



read_temp()
while True:
print(temp_f)
time.sleep(1)

# Below is what I will eventually need to run in order to display the digits on my 7-segment display.
'''
while True:
print( map(int,str(temp_f)) )
time.sleep(1)
'''

最佳答案

您只读取一次温度并在 while 循环中一遍又一遍地显示相同的值。您应该定期重新读取循环内的温度:

while True:
read_temp()
print(temp_f)
time.sleep(1)

如果温度读取操作需要太多功率,较大的 sleep 值可能会有所帮助。

关于python - 不断更新全局变量只打印第一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37605970/

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