With a little Python script I'm able to detect a button state that is connected in my Raspberry board. This is the script:
#!/usr/bin/env python
import os
import RPi.GPIO as GPIO
import time
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(12, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
try:
while True:
if(GPIO.input(12) == 1):
print 'Btn on'
os.system('date')
time.sleep(5)
else:
os.system('clear')
print 'Waiting'
time.sleep(2)
except KeyboardInterrupt:
GPIO.cleanup()
In this way, using PuTTY, or directly in the Raspberry terminal, I can easily detect the state of this button.
Now I would create the same thing but in PHP. I need to create a PHP web page that will be in the var/www/html
directory of my Raspberry, and should just show me the same thing. When I press the button, I will get a simple echo "Btn on" with the timestamp, and if not pressed just another echo with "Waiting".. Is it possible? I tried directly exec
the Python script, in PHP, in this way:
$command = escapeshellcmd('sudo -u www-data python btn.py');
$output = shell_exec($command);
echo $output;
but it's not working. Any idea?
It does not work because shell_exec
waits for the python script to finish before it returns. However, the python script obviously does not reach the end because of the infinite loop. The simplest fix would be to poll the button status once with the python script and do any looping in php. Alternatively the python can write to a fifo file, from which the php script can read - but then be careful, because if you leave the python script running, it will fill the memory of the raspberry.
You have to create a simple web API from your python snippet and Flask
for example.
A single route like:
@app.route('/')
def get_GPIO_state():
# Your GPIO status verification code here
return True # return proper state here
Expose this simple web API on another port than your web server. The advantage is you can monitor as much GPIO you want from separate or single route.
Now to get the info on your web page, with some javascript/jquery (or anything else that allow you to manipulate your web page), get the route you've just created and get the result.
You can then with DOM
manipulation change the contents of a part of your web page, updating the button status.
Otherwise, you can open a socket from your javascript (client-side so), and make your python script send updated data on real-time.
To update the web page contents, the same method applies than the previous possibility. (something based on getElementById()
for example to manipulate the DOM
).
Hope it helps.