【问题标题】:PHP with 2 buttons that control relayPHP 带有 2 个控制继电器的按钮
【发布时间】:2018-05-24 05:27:12
【问题描述】:

使用我的 Raspberry PI 3,我试图通过互联网控制双继电器,Python 代码没问题,我测试了它们,它们工作得很好。问题是 PHP 代码,我不知道如何制作网站。我只想显示 2 个按钮,一个打开继电器,一个关闭继电器,我在互联网上找到了一个,这是代码:

<html>
<head>
<meta charset="UTF-8" />
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>


<?php
if (isset($_POST['LightON']))
{
exec("sudo python /home/pi/relay1on.py");
}
if (isset($_POST['LightOFF']))
{
exec("sudo python /home/pi/relay1off.py");
}
?>

<form method="post">
<button class="btn" name="LightON">Light ON</button>&nbsp;
<button class="btn" name="LightOFF">Light OFF</button><br><br>
</form>


</html>

我用代码做了一个 nano(最初它是用来打开和关闭灯的,当然还有继电器,只是编辑了一点,所以当按下按钮时它会执行我需要的 python)并把它放进去/var/www/html/

我得到了我应该得到的东西,但按钮不起作用。我可以触摸它们,但页面只是刷新,继电器什么也不做。 如果有人可以帮助我,我会很感激。在此先感谢

【问题讨论】:

  • 你应该使用 input type='radio' 和提交按钮而不是按钮来获取一个值。
  • 感谢您的回答,我会尝试然后回来反馈,再次感谢您。

标签: php raspberry-pi


【解决方案1】:

这是一个 php 脚本:light.php

<?php
  if(isset($_POST['light']) && $_POST['light'] == "on")
  {
    exec("sudo python /home/pi/relay1on.py");
    echo "Light on!";
  }
  if(isset($_POST['light']) && $_POST['light'] == "off")
  {
    exec("sudo python /home/pi/relay1off.py");
    echo "Light off!";
  }
?>

这是 index.html 页面:

<html>
  <head>
    <meta charset="UTF-8" />
  </head>
  <body>
    <button id="btnLightON" class="btn">Light ON</button>
    <button id="btnLightOFF" class="btn">Light OFF</button>

    <script>
      var buttonLightON = document.getElementById("btnLightON");
      var buttonLightOFF = document.getElementById("btnLightOFF");

      buttonLightON.onclick = function()
      {
        Light(true);
      }
      buttonLightOFF.onclick = function()
      {
        Light(false);
      }


      function Light(b)
      {
        var http = new XMLHttpRequest();
        var url = "light.php";
        var params = "";
        if(b == true)
        {
          params = "light=on"
        }
        else if(b == false)
        {
          params = "light=off"
        }
        http.open("POST", url, true);

        http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

        http.onreadystatechange = function()
        {
            if(http.readyState == 4 && http.status == 200) {
                console.log(http.responseText);
            }
        }
        http.send(params);
      }
    </script>
  </body>

</html>

我是用 XMLHttpRequests 做的,所以它会在不重新加载页面的情况下执行 php 代码。 在 Light ON 按钮的情况下,它会向 light.php 发送一个 POST 请求,参数为 light=on,而在其他按钮的情况下,除了参数 light=off 之外,其他相同。 php 代码将为每个案例执行正确的 python 脚本并编写一条消息,您可以在控制台中看到。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多