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

Python实现无Sleep/Delay的X分钟后台定时触发ESP32复位

在Python中实现无延时的ESP32定时复位(后台进程运行)

需要实现的功能:

  • 每隔X分钟触发ESP32的复位引脚
  • 程序需以后台进程形式运行
  • 严格禁止使用sleep()或其他主动延时函数

现有代码(含sleep(),需改造):

import time
def SetTime(X):
    start=time.gmtime().tm_sec
    time.sleep(1)
    count=0
    while True:
        if start==time.gmtime().tm_sec:
            count+=1
            print("1 min is Over")
            start = time.gmtime().tm_sec
            time.sleep( 1 )
        if count==X:
            break
SetTime(5)

改造后的代码(无延时+后台进程)

import time
import multiprocessing
# 根据实际硬件控制库调整,这里以树莓派GPIO为例控制ESP32复位引脚
import RPi.GPIO as GPIO

RESET_PIN = 18  # 替换为你实际连接的引脚编号

def init_gpio():
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(RESET_PIN, GPIO.OUT)
    GPIO.output(RESET_PIN, GPIO.HIGH)  # 默认高电平,保持ESP32正常运行

def trigger_reset():
    # 按照ESP32复位逻辑:拉低引脚短暂时间后恢复高电平
    GPIO.output(RESET_PIN, GPIO.LOW)
    # 不用sleep,通过时间戳判断实现0.1秒拉低
    end_time = time.time() + 0.1
    while time.time() < end_time:
        pass
    GPIO.output(RESET_PIN, GPIO.HIGH)
    print("ESP32已触发复位")

def timer_process(X):
    init_gpio()
    interval = X * 60  # 将分钟转换为秒
    last_trigger_time = time.time()
    
    try:
        while True:
            current_time = time.time()
            # 检查是否到达设定的触发间隔
            if current_time - last_trigger_time >= interval:
                trigger_reset()
                last_trigger_time = current_time
            # 加入少量空循环降低CPU占用,避免无意义空转
            for _ in range(1000):
                pass
    except KeyboardInterrupt:
        GPIO.cleanup()
    finally:
        GPIO.cleanup()

if __name__ == "__main__":
    # 设置触发间隔为5分钟,可替换为任意X值
    X = 5
    # 创建后台守护进程
    bg_process = multiprocessing.Process(target=timer_process, args=(X,))
    bg_process.daemon = True  # 主进程退出时自动结束后台进程
    bg_process.start()
    
    # 主进程可在此添加其他业务逻辑,这里用循环保持主进程运行
    try:
        while True:
            # 主进程的其他操作,比如日志记录、状态监控等
            pass
    except KeyboardInterrupt:
        bg_process.terminate()
        bg_process.join()
        GPIO.cleanup()

关键说明:

  • 无延时实现:通过对比当前时间戳与上次触发时间戳判断间隔,完全摒弃sleep()
  • 后台进程:使用multiprocessing创建守护进程,主进程可独立执行其他任务
  • 复位逻辑:根据ESP32硬件复位电路调整电平变化,确保复位有效
  • CPU优化:加入少量空循环降低空转时的CPU使用率,同时不使用主动延时

内容的提问来源于stack exchange,提问作者prasanna

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 02:55:06