如何在 PHP 网页上显示连接到 Raspberry Pi 的称重传感器的输出?我在 Raspberry Pi 上创建了一个网页,想要在其上显示称重传感器输出,但我的代码不起作用。不会没有输出。
任何人都可以帮我解决这个问题吗?谢谢你
Python 脚本:
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 网页:
<!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 脚本:
<?php
$weight = exec("python3 read_weight.py");
echo $weight;
?>
提前感谢您回答我的问题。
这里是用python重新加载单元格数据
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()
print(read_weight()) # Print the weight
php 脚本>>
<?php
$weight = exec("python 3 read_weight.py");
echo $weight ;
?>
在网页上显示输出
<!DOCTYPE html>
<html>
<head>
<title>Load Cell Data</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
function updateWeight() {
$.ajax({
url: 'get_weight.php', // PHP script to fetch data
success: function(data) {
$('#weight').text('Current weight: ' + data + ' grams');
}
});
}
$(document).ready(function(){
updateWeight(); // Initial call to fetch data
setInterval(updateWeight, 1000);
});
</script>
</head>
<body>
<h1>Load Cell Data</h1>
<div id="weight"></div>
</body>
</html>