Problem Getting a PHP Script on a Raspberry Pi to execute a Python Script that turns a motor-ThrowExceptions

Exception or error:

Im a trying to make an automated light switch. To do this I am using a stepper motor. The goal is for the me to be able to access my raspberry pi from a browser and using 2 simple buttons, “Turn on” and “Turn off”, control the motor which will turn the light switch. I have written this simple python script to turn the motor, which has been tested from the Pi and works perfectly. It is called stepper.py and it is located in /var/www/html:

    import RPi.GPIO as GPIO
    import time
    GPIO.setmode(GPIO.BOARD)
    control_pins = [7,11,13,15]
    for pin in control_pins:
     GPIO.setup(pin, GPIO.OUT)
     GPIO.output(pin, 0)
    halfstep_seq = [
    [1,0,0,0],
    [1,1,0,0],
    [0,1,0,0],
    [0,1,1,0],
    [0,0,1,0],
    [0,0,1,1],
    [0,0,0,1],
    [1,0,0,1]
    ]

    for i in range(256):
     for halfstep in range(8):
      for pin in range(4):
      GPIO.output(control_pins[pin], halfstep_seq[halfstep][pin])
     time.sleep(0.001)

    GPIO.cleanup()
    print "Motor Rotation Completed"

Also in /var/www/html I have an index.html and index.php pages:

index.html:


<!DOCTYPE html>
 <html lang="en" dir="ltr">
 <head>
  <meta charset="utf-8">
  <title>Smart Light Switch</title>
 </head>
 <body>

  <h1>Smart Light Switch</h1>

  <form action="index.php" method="post">
    <input type="submit" name="on" value="Turn Lights On">
    <input type="submit" name="off" value="Turn Lights Off">
  </form>

 </body>
</html>




index.php:


<?php
 if ($_SERVER['REQUEST_METHOD'] == "POST" and isset($_POST['on']))
 {
  lightOn();
 } elseif ($_SERVER['REQUEST_METHOD'] == "POST" and isset($_POST['off']))
 {
  lightOff();
 }

 function lightOn()
 {
  $command = escapeshellcmd('python stepper.py');
  $output = shell_exec($command);
  echo "Light Turned On";

 }

 function lightOff()
 {
  echo "Light Turned Off";
 }

?>

Essentially the HTML just displays the 2 buttons and on the click it goes to the php file where the functions are successfully reached. However, the script to turn the stepper motor does not get executed. I have looked online and it would seem that what I have is the correct way to execute a python script from php, but it doesn’t work.

How to solve:

Leave a Reply

Your email address will not be published. Required fields are marked *