0

I am trying to turn on a LED (using the RPi.GPIO python library) if the player enters the correct number on a webpage. I'm serving up a php file using apache (that bit is ok).

snippet from '/var/www/html/index.php'

echo exec("python3 /home/pi/myStuff/number.py $player_name $player_guess");

I tried running the number.py from terminal:

python3 number.py Paul 12345

and this works fine.

When I do it via the PHP then it exits the code and the PHP is returned "PRE SETUP" (see number.py below). The problem lies with the line "GPIO.setup(7,GPIO.OUT)". As far as can work out the required permissions to set the GPIO pins are incorrect, but I've tried chmod, chown and chgrp and all the combinations I have used so far haven't worked. (chown to www-data for apache, chgrp to root, chmod to 755, and a fair few more).

number.py:

import sys
import time
import RPi.GPIO as GPIO
number = sys.argv[2]
if number == "12345":
    print("PRE SET MODE")     # added to help me debug
    GPIO.setmode(GPIO.BOARD)
    print("PRE SETUP")        # debugging
    GPIO.setup(7,GPIO.OUT)
    print("SETUP OK")         # debugging
    GPIO.output(7,1)
    print('You guessed correctly %s' % name)  # desired output to PHP 
    time.sleep(1)
    GPIO.output(7,0)
    GPIO.cleanup()
else:
    print("Better luck next time")          # output if you guess wrong

Can anyone point me in the right direction. I've tried using bash scripts (gpio mode 7 out, gpio write 7 1, ...) but this has the same problem. Any suggestions?

  • When you run the script from the command line do you need to use sudo? – Steve Robillard Jul 21 '17 at 22:56
0

Sounds like a permission issue. Have you tried something like this? Directly calling tend to have some path/env problem. I recommend using a shell script to bridge it. https://stackoverflow.com/questions/3166123/how-to-call-shell-script-from-php-that-requires-sudo

  • Thanks. Added the script to the sudoers file for www-data. The bit I wasn't expecting: "chmod" the number.py to be executable and call it directly in the php file (i.e. not use sudo python3 /path/script.py, but sudo /path/script.py) – Dangermouse Jul 22 '17 at 15:22
  • ... also add the shebang at the top of the py script! – Dangermouse Jul 22 '17 at 15:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.