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

树莓派PHP网页显示Load Cell输出故障求助

问题:树莓派PHP网页无法展示称重传感器数据

在树莓派上搭建了PHP网页,希望展示连接的Load Cell(称重传感器)输出数据,但当前代码无任何输出,相关代码如下,请求排查解决:

Python脚本(read_weight.py)

from hx711 import HX711

hx = HX711(dout_pin=5, pd_sck_pin=6)
hx.set_reading_format("MSB", "MSB")
hx.set_reference_unit(1)
hx.reset()
hx.tare()

def read_weight():
    return hx.get_weight()

while True:
    weight = read_weight()
    print("Current weight:", weight)

PHP网页(index.html)

<!DOCTYPE html>
<html>
<head>
    <title>Load Cell Weight</title>
</head>
<body>
    <h1>Current Weight:</h1>
    <div id="weight"></div>
    <script>
        function updateWeight() {
            var xhttp = new XMLHttpRequest();
            xhttp.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                    document.getElementById("weight").innerHTML = this.responseText;
                }
            };
            xhttp.open("GET", "get_weight.php", true);
            xhttp.send();
        }
        setInterval(updateWeight, 1000);
        updateWeight();
    </script>
</body>
</html>

PHP脚本(get_weight.php)

<?php
$weight = exec("python3 read_weight.py");
echo $weight;
?>

排查与解决步骤
  • 先单独验证Python脚本:在树莓派终端直接运行python3 read_weight.py,观察是否有重量输出。如果没有:

    • 确认HX711库已正确安装(可通过pip3 install hx711重新安装);
    • 检查传感器的DOUT、PD_SCK引脚是否对应接在树莓派的GPIO5、GPIO6上;
    • set_reference_unit(1)未校准,实际使用前需要校准参考值(可参考HX711库文档校准步骤)。
  • 修改Python脚本适配PHP调用:原脚本中的while True会无限循环,PHP的exec会等待脚本结束才返回结果,导致一直卡住。修改脚本为单次读取后退出:

    from hx711 import HX711
    
    hx = HX711(dout_pin=5, pd_sck_pin=6)
    hx.set_reading_format("MSB", "MSB")
    hx.set_reference_unit(1) # 后续需校准为实际参考值
    hx.reset()
    hx.tare()
    
    def read_weight():
        return hx.get_weight()
    
    if __name__ == "__main__":
        weight = read_weight()
        print(weight) # 只输出纯数值,方便PHP处理
    
  • 检查PHP运行权限:树莓派上Web服务(Apache/Nginx)以www-data用户运行,需确保该用户有权限:

    • 运行Python脚本:在终端执行sudo -u www-data python3 /path/to/read_weight.py,看是否正常输出;
    • 访问GPIO:将www-data用户添加到gpio组,执行sudo usermod -aG gpio www-data,重启Web服务生效。
  • 修正PHP脚本的路径问题:exec中的脚本路径如果不是当前PHP脚本所在目录,需使用绝对路径,比如:

    <?php
    $weight = exec("python3 /var/www/html/read_weight.py");
    echo $weight;
    ?>
    
  • 查看Web服务错误日志:若以上步骤仍未解决,查看错误日志排查细节:

    • Apache日志路径:/var/log/apache2/error.log
    • Nginx日志路径:/var/log/nginx/error.log

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 05:50:01