Html/Php Code for turning on lights using Raspberry Pi not working

1.6k views Asked by At

So I have been working on a project to turn on/off LED lights remotely through my Raspberry Pi but I have run into an issue.

My index.html code should work properly but when I press the on or off button, nothing happens. The issue is not with the actual commands (sudo python /var/www/html/scripts/lights/lampon.py or sudo python /var/www/html/scripts/lights/lampoff.py) because when I run the same command directly in the raspberry pi terminal, it works. And the rest of my code also seems to be correct... So I don't know what the problem is.

The code looks like this:

<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 /var/www/html/scripts/lights/lampon.py");
}
if (isset($_POST['LightOFF']))
{
exec("sudo python /var/www/html/scripts/lights/lampoff.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>

Any help would be appreciated. Thanks in advance.

NOTE: I am able to run the sudo command above as a normal user and the lights work but when I press the button, it doesn't work (webpage seems to load - so its doing something... but the lights do not turn on).

2

There are 2 answers

0
solomongamid On

You can do it just like this:

 <html>
 <head>
 <meta name="viewport" content="width=device-width" />
 <title>LED Control</title>
 </head>
         <body>
         LED Control:
         <form method="get" action="gpio.php">
                 <input type="submit" value="ON" name="on">
                 <input type="submit" value="OFF" name="off">
         </form>
        <?php
         $setmode17 = shell_exec("/usr/local/bin/gpio -g mode 17 out");
         if(isset($_GET['on'])){
                 $gpio_on = shell_exec("/usr/local/bin/gpio -g write 17 1");
                 echo "LED is on";
         }
         else if(isset($_GET['off'])){
                 $gpio_off = shell_exec("/usr/local/bin/gpio -g write 17 0");
                 echo "LED is off";
         }
         ?>
         </body>
 </html>

But you need to install Wiring Pi on Raspberry Pi first, to install it :

$ sudo apt-get install git-core
$ git clone git://git.drogon.net/wiringPi
$ cd wiringPi
$ ./build

I hope that i was useful :)

0
Kasador On

Well, that's the problem.

You are using PHP code inside a file called, "Index.html".

For PHP code to work it has to be in a file called, "Index.php".

The important part is that php code goes into files with an extension of .php and the same for html files.