More features

But the aREST library actually includes more than just the basic Arduino functions. The first feature that we are going to see is the access to variables stored on the Arduino board. If you have a sensor that can be read directly using basic Arduino functions, like an analog temperature sensor, you can directly get the value from the sensor by calling the analog REST call, just as we saw in the previous section.

However, if you are using sensors that have a more complex behaviour, for example sensors that use a dedicated library, you want to store the measurement in a local variable first, before getting it with the REST API. The first step to get a variable with a REST call is to declare it in the sketch, with an alias name. Note that for the moment, only integer variables are supported by the API. This is done by the following piece of code in the exemple sketch:
Download: file
rest.variable("temperature",&temperature);
The, this value can be accessed by the REST API by typing the following command in your browser:

http://arduino.local/temperature

This is the answer you will get in your browser:

{"temperature": 24, "id": "008", "name": "mighty_cat", "connected": true}

Once again, you will note that the answer is in JSON format, so it can be processed by other programming languages like PHP.

The other feature from the API that you can use is the ability to define your own functions, so they can be called directly from a REST call. Imagine for example the case where you want to execute a sequence of command: it is much more efficient to encapsulate all these commands in a single function, instead of making several REST calls. Note that all functions must return an integer type, and take a String as the unique argument, which will contain the different parameters for the function. You can see for example the function defined in the example:
Download: file
int ledControl(String command) {
  
  // Get state from command
  int state = command.toInt();
  
  digitalWrite(7,state);
  return 1;
}
Just as the variables, the functions have to be declared with an alias so they can be called by the API:
Download: file
rest.function("led",ledControl);
The function can then be called by the REST API in your browser, using the name of the alias followed by the parameters:

http://arduino.local/led?params=1

Once you sent this REST call, you should have the confirmation that the function has been executed:

Function led has been executed

Using these features, you can define your own variables and functions and call them directly from the REST API. For now, the library only supports 2 variables and 2 functions for memory limitation reasons, but you can go inside the library files to extend these limits (at your own risks!).
This guide was first published on Apr 17, 2014. It was last updated on Apr 17, 2014. This page (More features) was last updated on Sep 14, 2019.