RaspberryPi Web server: GPIO access

Controlling the RaspberryPi GPIO remotely, over a network or across the internet, seems like an interesting trick.

I copied some code from the net and gave it a try, but unfortunately it didn't want to play.

So I went back to basics and created my own simple test routine.

The web server

I built a fresh web server by installing Lighttpd and PHP as described in this earlier post. My new server can only be accessed on my personal network, and this is by using a browser on another networked computer.

The RaspberryPi web server IP is (in my case) 192.168.0.22 and I've set the lighttpd port to 9080. So the url: 192.168.0.22:9080/ takes me to the /var/www folder on the web server.

In order to communicate with the GPIO I also installed Gordon Henderson's wiringPi as covered in this post.

My php test program (which I've added to /var/www) is called gpio_test.php and looks like this:

RaspberryPi Web server GPIO access

It basically reads the current output level (or status) of GPIO pin 7, and tries to invert it (e.g. toggle “0” to “1” or “1” to “0”). So each time I refresh the page in the web browser, I should see the output change state.

I haven't actually bothered to connect a light to pin 7, and it doesn't matter which GPIO pin I choose for this test.

When this is run by remotely entering: 192.168.0.22:9080/gpio_test.php in a web browser, I get this simple black on white page:-
The program returns an error code each time it tries to read the state of GPIO Pin 7. Error code 127 is “command not found” and this is happening because the user account does not have permission to access the GPIO.

By adding “sudo” to each of the execute commands like this:
…the output changes slightly to this:-

Now the error code is 1 which is a pretty non-specific Linux error, but I think it is being returned because I'm not providing a password after sudo. Obviously I don't want to code-in a password, but I can add the user to sudoers.

The “user” on the web server is called www-data, so I can open /etc/sudoers as root and add this line at the end of the file:-

 

For more detail: RaspberryPi Web server: GPIO access


About The Author

Ibrar Ayyub

I am an experienced technical writer holding a Master's degree in computer science from BZU Multan, Pakistan University. With a background spanning various industries, particularly in home automation and engineering, I have honed my skills in crafting clear and concise content. Proficient in leveraging infographics and diagrams, I strive to simplify complex concepts for readers. My strength lies in thorough research and presenting information in a structured and logical format.

Follow Us:
LinkedinTwitter

Leave a Comment

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

Scroll to Top