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

Python延时处理及树莓派温度应用10分钟阈值窗口实现求助

Hey there! Let's work through that 10-minute threshold logic you're stuck on. Since you're new to Python, I'll break this down simply and give you actionable code that fits with your existing tkinter setup.

The Core Problem

You need to track how long the temperature stays above your threshold (10°C) — not just trigger the relay immediately when it goes over. If the temp dips below even once, you should reset that timer and start over.

Key Concepts to Use

Since we're using tkinter, we can't use time.sleep() (it would freeze your UI). Instead, we'll use tkinter's after() method to run our temperature check every 3 seconds, and we'll track the start time of when the temp first exceeds the threshold.

Step-by-Step Code Implementation

Here's how to integrate this logic into your existing app. I'll include placeholder functions for reading the sensor and controlling the relay — just swap those out with your actual code.

import tkinter as tk
import time

class TempMonitorApp:
    def __init__(self, root):
        self.root = root
        self.root.title("Raspberry Pi Temp Monitor")
        
        # UI Element for displaying temperature
        self.temp_display = tk.Label(root, font=('Arial', 16), text="Current Temp: -- °C")
        self.temp_display.pack(pady=20)
        
        # Configuration Settings (tweak these as needed)
        self.TEMP_THRESHOLD = 10  # Your threshold temperature
        self.CHECK_INTERVAL = 3000  # Check temp every 3 seconds (in milliseconds)
        self.WAIT_PERIOD = 10 * 60 * 1000  # 10 minutes in milliseconds
        
        # Tracking Variables
        self.threshold_start = None  # Will store the first time temp exceeds threshold
        self.relay_is_active = False  # Avoid redundant relay triggers
        
        # Start the temperature checking loop
        self.check_temperature()

    def read_ds18b20_temp(self):
        # Replace this with your actual DS18B20 reading code
        # Example: Read from the sensor file path on Raspberry Pi
        # For testing, return a random temp between 8-12°C
        import random
        return round(random.uniform(8, 12), 1)

    def turn_on_ac_relay(self):
        # Replace this with your relay activation code
        if not self.relay_is_active:
            print("✅ AC Activated: Temperature stayed above threshold for 10 minutes!")
            self.relay_is_active = True

    def turn_off_ac_relay(self):
        # Replace this with your relay deactivation code
        if self.relay_is_active:
            print("❌ AC Deactivated: Temperature back below threshold.")
            self.relay_is_active = False

    def check_temperature(self):
        current_temp = self.read_ds18b20_temp()
        # Update the UI with current temp
        self.temp_display.config(text=f"Current Temp: {current_temp} °C")
        
        now_ms = time.time() * 1000  # Convert current time to milliseconds

        if current_temp > self.TEMP_THRESHOLD:
            # Temperature is above threshold
            if self.threshold_start is None:
                # First time exceeding threshold — record the time
                self.threshold_start = now_ms
                print(f"⚠️ Temperature exceeded {self.TEMP_THRESHOLD}°C at {time.ctime(now_ms/1000)}")
            else:
                # Calculate how long we've been above threshold
                time_elapsed = now_ms - self.threshold_start
                if time_elapsed >= self.WAIT_PERIOD:
                    # We've hit the 10-minute mark — activate the relay
                    self.turn_on_ac_relay()
        else:
            # Temperature is below threshold — reset everything
            if self.threshold_start is not None:
                print("🔄 Temperature back to normal — resetting timer.")
                self.threshold_start = None
            # Turn off the relay if it's active
            self.turn_off_ac_relay()

        # Schedule the next temperature check in 3 seconds
        self.root.after(self.CHECK_INTERVAL, self.check_temperature)

if __name__ == "__main__":
    root = tk.Tk()
    app = TempMonitorApp(root)
    root.mainloop()

What This Code Does

  • Tracks Threshold Duration: When the temp first goes over 10°C, it saves that time. If the temp stays above, it checks how much time has passed.
  • Resets on Normal Temp: If the temp drops below the threshold at any point, it resets the timer and turns off the relay.
  • Non-Blocking UI: Uses tkinter's after() method to keep the UI responsive while checking temperatures every 3 seconds.
  • Avoids Redundant Triggers: The relay_is_active variable ensures we don't keep calling the relay activation code over and over once it's already on.

Quick Tips for Testing

  • To test without waiting 10 minutes, change self.WAIT_PERIOD to 30000 (30 seconds) temporarily.
  • Make sure your DS18B20 is properly set up on your Raspberry Pi (you'll need to enable 1-Wire interface via raspi-config and load the necessary kernel modules).
  • For relay control, double-check your GPIO pin wiring — use a transistor or relay module to avoid damaging your Pi's GPIO pins.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 09:07:54