Raspberry Pi - How to control a GPIO from website
- December 05 2015
- Raspberry Pi, Cubieboard, Banana Pi, BeagleBone, Orange Pi
- 1977 Reads
- 0 Comments
Download 2 PHP files and 1 python script
If you want to control GPIO through webpage, you have to read this article.
I will describe how to control GPIO from webpage. You can download 2 PHP files and 1 python script.
I will describe two ways how to run python script which will control GPIO. First way will run python script directly from PHP.
We will turn on LED with PHP which write to the MySQL database and the cron runs our python script every minute.
In the first way we add "new" user to /etc/sudoers.tmp and we repair the error "sudo: no tty present and no askpass program specified". In the second way we create new cron process which we write to the cronetab.
In both options, the PHP writes the variable to the MySQL database and the python script reads the variable and it controls the GPIO.
The first, you have to the database database and the table lpm (led+python+mysql).
You create element id, type UNSIGNED INT and it has PRIMARY KEY. Next element will be gpio, type VARCHAR and it is NULL. And last onoff, type UNSIGNED INT and it is NULL.
The length set is not important. For INT for example 2 and VARCHAR for example 10.
You can create other database, but you have to rewrite php files and python script
Now, solution. If you use first metode (add www-data (apache) to the etc/sudoers.tmp), you must be very careful. The PHP can run python script, but if somebody uses SQL injection and he uses shell script, he can delete your disk (rm -rf).
Nevertheless, the change GPIO is immediate. If you use cron, the shortest time interval is one minute.
You have to install package python-mysqldb. You write sudo apt-get install python-mysqldb in the terminal.
If you created the database, you have to use command USE test in the phpmyadmin or in the mysql -u USER -p.
When you don't use, you will see warning Error 1046 No database Selected.
After you will add user www-data (apache) to the sudoers through terminal: sudo pkexec visudo. You write:
www-data ALL=(ALL) NOPASSWD: ALL
on the last line.
If you will see sudo: no tty present and no askpass program specified, you check your line in the sudoers.
The end, you upload 2 PHP files and 1 python script on your website. Files are download at the end of the page with comments.
Second way: running python script with crontab.
You comment one line (comments in the zmena.php file) in the zmena.php.
write in the terminal: sudo crontab -e
You write this command on the last line.
* * * * * sudo /usr/bin/python /var/www/led-python-mysql.py
The cron will run every minute. Now, restart cron.
sudo service cron restart
If you write ps aux | grep /var/www/led-python-mysql.py to the terminal, you see running process.
Schematic:
Download 2 PHP files and 1 python script