Now that we saw the basics of the REST API for Arduino, we can use that to build a simple web application that will run in your browser, with buttons to control the two LEDs that are connected to your Arduino board.

For this part, you'll need a working web server (like Apache) running on your computer, and you will need to put all the files at the root of your web server main folder.

You can find the complete code for this part by following this link:
First, to make sure that the library is working, go in a browser and set the two LED pins to outputs:



Once this is done, we are going to code the web app. The app is basically composed of three parts:
  • An HTML page that contains the interface (I also added some CSS to make it look better)
  • A JavaScript file that handles the commands coming from the interface
  • A PHP file to communicate with the Arduino board by making REST calls
To give you some idea about what we want to build, here is the completed interface:
Let's talk about the HTML part first. The interface basically consists of these four buttons, which are defined by the following code:
<button class="relayButton" type="button" id="1" 
See this "" argument that is passed on each click of the button? This is what we are going to use in the JavaScript file to know which command to send to the Arduino board using the REST API. For this particular button, here is how it is handled by the JavaScript file:
if (clicked_id == "1"){
  $.get( "curl.php", {
    pin: "7", state: "1"} );  
You can see that every time this button is pressed, we call a file called "curl.php" which contains the functions to make the REST call to the Arduino board.

This PHP file starts by getting the pin & state to be sent to the Arduino board:
$pin = $_GET['pin'];
$state = $_GET['state'];
We then build the URL that will be called by the PHP script:
$service_url = 'http://arduino.local/digital/' . $pin . '/' . $state;
Then, we can create the cURL object that will do the REST call. cURL stands for Client URL Request Library, and this is what we will use to do like we would type the URL in a browser. This cURL object is initialised with:
$curl = curl_init($service_url);
And execute it, while storing the answer in a variable:
$curl_response = curl_exec($curl);
This last line is optional for this app, but in case we want to get back some data from the Arduino board (for example if we called a variable on the board using the REST API) we can use the echo function to print this result:
echo $curl_response;
You can now go to your web server (usually on localhost) and open the HTML file. You can try to click on the different buttons: the state of the LEDs should change instantly, just like if you would type the REST URLs in your browser.

This guide was first published on Apr 17, 2014. It was last updated on Mar 08, 2024.

This page (Application: a basic web app) was last updated on Apr 08, 2014.

Text editor powered by tinymce.