Monday, March 31, 2014

Sending and Receiving Data from an Arduino Through a Webpage

I thought it would be kind of cool to be able to control an Arduino remotely so I hacked up a bunch of code that allows me to do this. The website can control multiple Arduino's at one time and recognizes them by their unique IDs that they send.

Basically, what you need is:

A computer running Linux
A webserver, Apache is nice with ability to run Javascript and Perl
Perl
An Arduino

How it works is like this:
1. Arduino sends data to the Serial port that is polled by computer_interface.pl and written to a file that is plotted using gnuplot to display on the webpage
3. Webpage uses web_interface.cgi to write data to a file that is read by computer_interface.pl and sent to Arudino
2. Arduino is polling Serial port to receive data and uses the data to modify variables that can change how the Arduino operates.


What this code was written for was having an Arduino controller multiple pieces of equipment in a Scientific lab but it can be ported to use for many other things.

Here is the Arduino Code: http://pastebin.com/f8eBJc7R
Here is the computer_interface.pl: http://pastebin.com/yGNMCH54
Here is the webinterface.cgi: http://pastebin.com/qpUZ5n9A
Here is the gnoplot formatting file should be in the same directory as computer_interface.pl: http://pastebin.com/1BWNaAc4
HTML file: http://pastebin.com/e2Fpkrfi
HTML CSS: http://pastebin.com/1YUnWS0Q
HTML Javascript: http://pastebin.com/kNvEVa0d

1. Install gnuplot: apt-get install gnuplot or yum install gnuplot
2. Put the HTML files in /var/www/html
3. Setup Perl execution on your webserver  (http://stackoverflow.com/questions/560749/how-do-i-configure-apache2-to-run-perl-cgi-scripts)
4. Make sure you Arduino has code loaded and is plugged in.
5. Run computer_interface.pl in background and make sure the gnuplot file is in the same directory
6. Use!

The webpage refreshes every 30 seconds you can change this in example.html.

The Javascript is just for giving the webpage a tabbed format to run multiple devices. This can easily be removed and changed so that you don't need the CSS or Javascript files.