In this section, we are going to build the Arduino sketch that we will use to control the switch via WiFi.
To do so, we are going to use the aREST library that implements a REST API for Arduino. This way, we can have an easy access to the pins of the Arduino board, and also to the variable in which the power measurement is stored.
Note that only the most important parts of the code are detailed here, please get to the complete sketch on GitHub to have the complete code that you can upload to the Arduino board.
It starts by including all the required libraries:
#include <Adafruit_CC3000.h> #include <SPI.h> #include <CC3000_MDNS.h> #include <aREST.h>
And declaring the pin on which the powerswitch module is connected:
const int relay_pin = 8;
aREST rest = aREST();
#define LISTEN_PORT 80
Adafruit_CC3000_Server restServer(LISTEN_PORT);
MDNSResponder mdns;
pinMode(relay_pin,OUTPUT);
rest.set_id("001"); rest.set_name("smart_lamp");
if (!mdns.begin("arduino", cc3000)) { while(1); }
restServer.begin(); Serial.println(F("Listening for connections..."));
In the loop() function of the sketch, we update the MDNS server:
mdns.update();
And process any incoming connection using the aREST library:
Adafruit_CC3000_ClientRef client = restServer.available(); rest.handle(client);
Note that you can find all the code for this part inside the GitHub repository of the project:
https://github.com/marcoschwartz/arduino-wifi-powerswitch
It’s now time to test this sketch on our project. Download the code from the GitHub repository, and make sure that you modify the name and the password of the WiFi network on which the WiFi chip will connect to. Then, upload the code to the Arduino board, and open the Serial monitor. This is what you should see:
Now, close the Serial monitor, and open your web browser. You can now make direct calls to the REST API running on the board to control the pins of the Arduino board. For example, to turn the switch on, just type:
To switch the device off again, just type:
Note that these commands will work from any devices connect to the same local network as the Arduino board. For example, you can use your smartphone to control your Arduino board with the same commands.
If it doesn’t work, the first thing to do is to use the IP address of the board in place of the arduino.local name. You can get the IP address of the board by looking at the messages displayed on the Serial monitor when starting the project: