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

树莓派环境下,如何通过PHP向运行中的Python脚本提交修改阈值?

当然可以实现!不过直接修改运行中Python脚本的内存变量不太现实,我们得用共享数据存储的方式让PHP和Python脚本互通阈值,下面给你一步步来实现:

核心思路

让Python脚本不再依赖硬编码的阈值,而是每次循环时从外部配置文件读取阈值;PHP负责接收网页输入并更新这个配置文件,这样运行中的Python脚本就能自动获取新阈值了。


第一步:改造Python脚本

修改你的现有脚本,让它从配置文件动态读取阈值,示例代码如下:

# -*- coding: utf-8 -*-
#!/usr/bin/env python
import smbus
import time
import RPi.GPIO as gpio

# 初始化GPIO和传感器
gpio.setwarnings(False)
gpio.setmode(gpio.BOARD)
gpio.setup(29, gpio.OUT)

# 阈值配置文件路径(要放在Apache可访问的目录下,比如/var/www/html/)
THRESHOLD_FILE = "/var/www/html/threshold.conf"

# 初始默认阈值
current_threshold = 500

def get_current_threshold():
    """从配置文件读取当前阈值,读取失败则返回默认值"""
    try:
        with open(THRESHOLD_FILE, 'r') as f:
            return int(f.read().strip())
    except (FileNotFoundError, ValueError):
        return 500

try:
    # 传感器初始化(根据你的实际传感器调整,这里是I2C示例)
    bus = smbus.SMBus(1)
    while True:
        # 每次循环前更新阈值
        current_threshold = get_current_threshold()
        
        # 读取光传感器数值(替换成你实际的读取逻辑)
        light_value = bus.read_byte_data(0x23, 0x10)
        
        # 根据阈值控制灯光
        if light_value < current_threshold:
            gpio.output(29, gpio.HIGH)
        else:
            gpio.output(29, gpio.LOW)
        
        time.sleep(1)  # 每秒检测一次
finally:
    gpio.cleanup()

第二步:配置文件权限与PHP页面

首先要确保Apache用户(www-data)有权限修改配置文件,在树莓派终端执行以下命令:

# 创建配置文件
sudo touch /var/www/html/threshold.conf
# 设置文件归属为Apache用户
sudo chown www-data:www-data /var/www/html/threshold.conf
# 设置读写权限
sudo chmod 644 /var/www/html/threshold.conf
# 写入初始阈值
echo "500" | sudo tee /var/www/html/threshold.conf

然后创建PHP网页(比如/var/www/html/index.php),用来接收用户输入并更新阈值:

<!DOCTYPE html>
<html>
<head>
    <title>灯光阈值调整</title>
</head>
<body>
    <h1>设置光传感器触发阈值</h1>
    <?php
    $threshold_file = 'threshold.conf';
    $current_threshold = 500;
    
    // 读取当前阈值
    if (file_exists($threshold_file)) {
        $current_threshold = intval(file_get_contents($threshold_file));
    }
    
    // 处理表单提交
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $new_threshold = intval($_POST['threshold']);
        // 简单验证阈值范围(根据你的传感器实际输出调整)
        if ($new_threshold >= 100 && $new_threshold <= 1000) {
            file_put_contents($threshold_file, $new_threshold);
            echo "<p style='color:green;'>✅ 阈值已更新为:$new_threshold</p>";
            $current_threshold = $new_threshold;
        } else {
            echo "<p style='color:red;'>❌ 请输入100-1000之间的有效数值!</p>";
        }
    }
    ?>
    <form method="POST">
        <p>当前阈值:<?php echo $current_threshold; ?></p>
        <label>输入新阈值:</label>
        <input type="number" name="threshold" min="100" max="1000" value="<?php echo $current_threshold; ?>">
        <button type="submit">更新阈值</button>
    </form>
</body>
</html>

第三步:运行与测试

  1. 后台启动Python脚本:避免终端关闭后脚本停止,用nohup或做成系统服务:

    nohup python3 /path/to/your/modified_script.py &
    

    更稳定的方式是做成systemd服务(开机自动启动),可以创建/etc/systemd/system/light-control.service文件:

    [Unit]
    Description=Light Control Script
    After=multi-user.target
    
    [Service]
    Type=simple
    User=pi
    ExecStart=/usr/bin/python3 /path/to/your/modified_script.py
    Restart=always
    
    [Install]
    WantedBy=multi-user.target
    

    然后执行:

    sudo systemctl daemon-reload
    sudo systemctl enable light-control.service
    sudo systemctl start light-control.service
    
  2. 访问网页测试:在浏览器输入树莓派的IP地址(比如http://raspberrypi.local/index.php),调整阈值后,Python脚本会在下次循环时读取新阈值,自动调整灯光逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:00:06