You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python嵌套While循环故障:树莓派Zero晨昏灯光控制脚本排查

Raspberry Pi 晨昏自动灯脚本问题排查与修复

原代码核心问题

  1. 时间变量未实时更新:now、dawn、dusk仅在脚本启动时初始化一次,后续不会随时间刷新,导致时间判断永远停留在启动时刻的状态。
  2. 变量名冲突:导入的astral.sun模块中的dawn、dusk、midnight函数被同名变量覆盖,无法后续调用函数重新计算次日晨昏时间。
  3. 无效循环逻辑:内层while循环没有更新now值,也无延时,会持续占用CPU且无法正常退出;midnight的判断逻辑错误,未触发次日晨昏时间的重新计算。

修复后的代码

#!/usr/bin/python

import pendulum
from time import sleep
from gpiozero import LED
from astral import LocationInfo
from astral.sun import dusk as get_dusk, dawn as get_dawn, midnight as get_midnight

# 初始化硬件与位置信息
home = LocationInfo("Mons-en-Baroeul", "France", "Europe/Paris", 50.6, 3.1)
blue = LED(23)
red = LED(24)

def lights_on():
    blue.on()
    red.on()

def lights_off():
    blue.off()
    red.off()

def update_sun_times():
    """更新当日晨昏与午夜时间"""
    today = pendulum.now('Europe/Paris').date()
    dawn_time = get_dawn(home.observer, date=today)
    dusk_time = get_dusk(home.observer, date=today)
    midnight_time = get_midnight(home.observer, date=today)
    return dawn_time, dusk_time, midnight_time

# 初始获取当日时间
dawn_time, dusk_time, midnight_time = update_sun_times()

while True:
    now = pendulum.now('Europe/Paris')
    
    # 检查是否需要更新次日晨昏时间
    if now >= midnight_time:
        dawn_time, dusk_time, midnight_time = update_sun_times()
    
    # 根据当前时间控制灯光
    if dawn_time <= now < dusk_time:
        lights_on()
    else:
        lights_off()
    
    # 每分钟检查一次,降低CPU占用
    sleep(60)

修复说明

  • 变量名区分:将导入的函数重命名为get_dawn、get_dusk、get_midnight,避免与时间变量冲突。
  • 实时更新时间:主循环中每次都刷新now的值,并在过了午夜后调用update_sun_times获取次日的晨昏时间。
  • 优化循环逻辑:替换嵌套while为简单的条件判断,加入sleep(60)每分钟检查一次,减少资源消耗。
  • 模块化函数:新增update_sun_times函数统一处理晨昏时间计算,代码更清晰易维护。

内容的提问来源于stack exchange,提问作者Gé Fa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 20:20:29