Weather Station with Arduino (Best Tutorial 2019)

Weather Station with Arduino

Building a Weather Station with Arduino Tutorial 2019

This blog will introduce you to the powerful features of the Arduino Yún microcontroller board. In this tutorial, you will learn how to create a simple weather station with Arduino that will send data to the cloud using the features of the web-based service Temboo.


Temboo is not 100 percent free, but you will be able to make 1000 calls to Temboo per month using their free plan. You will learn how to connect sensors that measure temperature, humidity, and light level to your Arduino Yún.


 These sensors will first be separately tested to make sure that the hardware connections you made are correct.


Then, we are going to use the Temboo Arduino libraries to send these measurements to the cloud and to different web services so that they can be accessed remotely regardless of where you are in the world.


Temboo is a web-based service that allows you to connect different web services together and proposes ready-to-use libraries for the Arduino Yún.


For example, the first thing we are going to do with Temboo is to send the data from your measurements to a Google Docs spreadsheet, where they will be logged along with the measurement data.


Within this spreadsheet, you will be able to plot this data right in your web browser and see the data that arrives getting stored in your Google Docs account.


Then, we will use Temboo again to send an automated e-mail based on the recorded data. For example, you would like to send an alert when the temperature drops below a certain level in your home, indicating that a heater has to be turned on.

 Weather Station

Finally, we will finish the blog by using Temboo to post the data at regular intervals on a Twitter account, for example, every minute. By doing this, we can have a dedicated Twitter account for your home that different members of your family can follow to have live information about your home.


After completing this blog, you'll be able to apply what you learned to other projects than just weather-related measurements. You can apply what you see in this blog to any project that can measure data, in order to log this data on the Web and publish it on Twitter.


 The Arduino Yún board is shown in the following image:

 Arduino Yún board

Hardware and software components

Of course, you need to have your Arduino Yún board ready on your desk along with a micro USB cable to do the initial programming and testing. Also, we recommend that you have a power socket to the micro USB adapter so that you can power on your Arduino Yún directly from the wall without having your computer lying around.


This will be useful at the end of the project, as you will want your Arduino Yún board to perform measurements autonomously.


You will then need the different sensors which will be used to sense data about the environment. For this project, we are going to use a DHT11 sensor to measure temperature and humidity and a simple photocell to measure light levels. 


DHT11 is a very cheap digital temperature and humidity sensor that is widely used with the Arduino platform. You can also use a DHT22 sensor, which is more precise, as the Arduino library is the same for both sensors.


There are several manufacturers for these sensors, but you can find them easily, for example, on SparkFun or Adafruit. For the photocell, you can use any brand that you wish; it just needs to be a component that changes its resistance according to the intensity of the ambient light.

DHT11 sensor

To make the DHT11 sensor and photocell work, we will need a 4.7k Ohm resistor and a 10k Ohm resistor as well. You will also need a small breadboard with at least two power rails on the side and some male-male jumper wires to make the electrical connections between the different components.


On the software side, you will need the latest beta version of the Arduino IDE, which is the only IDE that supports the Arduino Yún board (we used Version 1.5.5 when doing this project). You will also need the DHT library for the DHT11 sensor, which can be downloaded from


To install the library, simply unzip the files and extract the DHT folder to your libraries folder in your main Arduino folder.


Connecting the sensors to the Arduino Yún board

Connecting the sensors

 Before doing anything related to the Web, we will first make sure that our hardware is working correctly. We are going to make the correct hardware connections between the different components and write a simple Arduino sketch to test all these sensors individually.


 By doing this, we will ensure that you make all the hardware connections correctly, and this will help a lot if you encounter problems in the next sections of this blog that use more complex Arduino sketches.


The hardware connections required for our project are actually quite simple. We have to connect the DHT11 sensor and then the part responsible for the light level measurement with the photocell by performing the following steps:


1. First, we connect the Arduino Yún board's +5V pin to the red rail on the breadboard and the ground pin to the blue rail.


2. Then, we connect pin number 1 of the DHT11 sensor to the red rail on the breadboard and pin number 4 to the blue rail. Also, connect pin number 2 of the sensor to pin number 8 of the Arduino Yún board.


3. To complete the DHT11 sensor connections, clamp the 4.7k Ohm resistor between pin numbers 1 and 2 of the sensor.


For the photocell, first, place the cell in series with the 10k Ohm resistor on the breadboard. This pull-down resistor will ensure that during the operation if there is no light at all, the voltage seen by the Arduino board will be 0V.


Then, connect the other end of the photocell to the red rail on the breadboard and the end of the resistor to the ground. Finally, connect the common pin to the Arduino Yún board analog pin A0.


The following image made using the Fritzing software summarizes the hardware connections:

Now that the hardware connections are done, we will work on testing the sensors without uploading anything to the Web. Let's go through the important parts of the code. First, we have to import the library for the DHT11 sensor, as follows: #include "DHT.h"


Then, we need to declare a couple of variables that will store the measurements, as shown in the following code. These variables are declared as floats because the DHT sensor library returns float numbers.


int lightLevel;
float humidity;
float temperature;
Also, we can define the sensor pin and sensor type as follows:
#define DHTPIN 8
#define DHTTYPE DHT11
Create the DHT instance as follows:
Now, in the setup() part of the sketch, we need to start the serial connection, as follows:
Next, in order to initialize the DHT sensor, we have the following:
In the loop() part, we are going to perform the different measurements. First, we will calculate the temperature and humidity, as follows:
float humidity = dht.readHumidity();
float temperature = dht.readTemperature();
Then, measure the light level, as follows:
int lightLevel = analogRead(A0);
Finally, we print all the data on the serial monitor, as shown in the following code:
Serial.print("Temperature: ");
Serial.print("Humidity: ");
Serial.print("Light level: ");
Repeat this every 2 seconds, as shown:


The complete sketch for this part can be found at openhomeautomation/geeky-projects-yun/tree/master/blog1/sensors_ test.


 Now it's time to test the sketch and upload it to the Arduino board. Then, open the serial monitor and you should have the data that comes from the sensors being displayed.


If you can see the different measurements being displayed, it means that you have made the correct hardware connections on your breadboard and that you can proceed to the next sections of this blog.


If it is not the case, please check all the connections again individually by following the instructions in this section. Please make sure that you haven't forgotten the 4.7k Ohm resistor with the DHT sensor, as the measurements from this sensor won't work without it.


[Note: You can free download the complete Office 365 and Office 2019 com setup Guide for here]


 Creating a Temboo account

The next step in this project is to create and set up an account on the web service Temboo, so you can use the wide range of services provided by Temboo to upload data to Google Docs and to use their Gmail and Twitter libraries. This account will actually be used in the whole blog for the other projects as well.


To do so, the first step is to simply go to the Temboo website at the main page, simply enter your e-mail address to register and click on Sign up, You will then be asked to enter some basic information about your account, such as your account name.


Then, you will be prompted to create your first app. Ensure that you save the details of your account, such as the name of your first app and the key that will be given to you; we are going to need it for the rest of this blog.


In case you need to get these values again or create a new application, you can always access this data in the My Account section of the Temboo website by clicking on the MANAGE button below APPLICATIONS. 


We are now all set to start using the Temboo libraries that are made specifically for the Arduino Yún board and to upload some data to the cloud.


Sending data to Google Docs and displaying it

In this section, we are going to use our first Temboo library (called a Choreo) to upload the measurements of the Arduino Yún to the Web and log the data into a Google Docs spreadsheet.


First, let's have a look at what a Choreo is and how you can generate the code for your Arduino Yún board. If you go to the main Temboo page, you will see that you can choose different platforms and languages, such as Arduino, JavaScript, or Python.


Each of these links will allow you to select a Choreo, which is a dedicated library written for the platform you chose and can interface with a given web service such as Google Docs.


For the Arduino platform, Temboo even offers to generate the entire code for you. You can click on the Arduino icon on the Temboo website and then click on Arduino Yún; you will get access to a step-by-step interface to generate the code.


However, as we want to get complete control of our device and write our own code, we won't use this feature for this project.


Google Docs is really convenient as it's an online (and free) version of the popular Office software from Microsoft. The main difference is that because it's all in the cloud, you don't have to store files locally or save them—it's all done online.


For our project, the advantage is that you can access these files remotely from any web browser, even if you are not on your usual computer. You just need your Google account name and password and can access all your files.


If you don't have a Google account yet, you can create one in less than five minutes at This will also create an account for the Gmail service, which we will also use later. Please make sure that you have your Google Docs username and password as you are going to need them soon.


Before we start writing any Arduino code, we need to prepare a Google Docs spreadsheet that will host the data. Simply create a new one at the root of your Google Docs account; you can name it whatever you wish (for example, Yun). This is done from the main page of Google Docs just by clicking on Create.


In the spreadsheet, you need to set the name of the columns for the data that will be logged; that is, Time, Temperature, Humidity, and Light level.


Now, let's start building the Arduino sketch inside the Arduino IDE. We first need to import all the necessary libraries, as follows:

  • #include <Bridge.h>
  • #include <Temboo.h>
  • #include <Process.h>


The Bridge library is something that was introduced for the Arduino Yún board and is responsible for making the interface between the Linux machine of the Yún and the Atmel processor, where our Arduino sketch will run. With this library, it's possible to use the power of the Linux machine right inside the Arduino sketch. 


The Process library will be used to run some programs on the Linux side, and the Temboo file will contain all the information that concerns your Temboo account. Please go inside this file to enter the information corresponding to your own account. This is as shown in the following code:

#define TEMBOO_ACCOUNT "temboo_account_name" // Your Temboo account name

#define TEMBOO_APP_KEY_NAME " temboo_app_name " // Your Temboo app key name

#define TEMBOO_APP_KEY " temboo_api_key " // Your Temboo app key


Note that we also included a debug mode in the sketch that you can set to true if you want some debug output to be printed on the serial monitor. However, for autonomous operation of the board, we suggest that you disable this debugging mode to save some memory inside Yún.


In the sketch, we then have to enter the Google Docs information. You need to put your Google username and password here along with the name of the spreadsheet where you want the data to be logged, as shown in the following code:

const String GOOGLE_USERNAME = "yourUserName"; const String GOOGLE_PASSWORD = "yourPassword"; const String SPREADSHEET_TITLE = "Yun";


In the setup() part of the sketch, we are now starting the bridge between the Linux machine and the Atmel microcontroller by executing the following line of code:

We are also starting a date process so that we can also log the data of when each measurement was recorded, as shown in the following code:
time = millis();
if (!date.running()) {


The date will be in the format: date of the day followed by the time. The dating process we are using here is actually a very common utility for Linux, and you can look for the documentation of this function on the Web to learn more about the different date and time formats that you can use.


Now, in the loop() part of the sketch, we send the measurements continuously using the following function:

runAppendRow(lightLevel, temperature, humidity);


Let's get into the details of this function. It starts by declaring the Choreo (the Temboo service) that we are going to use:

TembooChoreo AppendRowChoreo;


The preceding function is specific to Google Docs spreadsheets and works by sending a set of data separated by commas on a given row. There are Choreos for every service that Temboo connects to, such as Dropbox and Twitter.


Please refer to the Temboo documentation pages to get the details about this specific Choreo.


After declaring the Choreo, we have to add the different parameters of the Choreo as inputs. For example, the Google username, as shown in the following line of code:

AppendRowChoreo.addInput("Username", GOOGLE_USERNAME);


The same is done with the other required parameters, as shown in the following code:

AppendRowChoreo.addInput("Password", GOOGLE_PASSWORD); AppendRowChoreo.addInput("SpreadsheetTitle", SPREADSHEET_TITLE);


The important part of the function is when we actually format the data so that it can be appended to the spreadsheet. Remember, the data needs to be delimited using commas so that it is appended to the correct columns in the spreadsheet, as shown in the following code:

String data = "";
data = data + timeString + "," + String(temperature) + "," + String(humidity) + "," + String(lightLevel);
The Choreo is then executed with the following line of code:
unsigned int returnCode =;


The function is then repeated every 10 minutes. Indeed, these values usually change slowly over the course of a day, so this is useless to the data that is logging continuously.


Also, remember that the number of calls to Temboo is limited depending on the plan you chose (1000 calls per month on a free plan, which is approximately 1 call per hour). This is done using the delay function, as follows: delay(600000);


For demonstration purposes, the data is logged every 10 minutes. However, you can change this just by changing the argument of the delay() function.

The complete code for this part can be found at geeky-projects-yun/tree/master/blog1/temboo_log.


You can now upload the sketch to the Arduino Yún board and open the Google Docs spreadsheet to see what's happening. It's all synchronized live with the Google Docs servers, so you do not need to refresh anything. After a while, you should see the first set of measurements being logged.


In order to show you what can be done using this project, we used the integrated chart capabilities of Google Docs to plot this data using the measurements that we obtained for over 24 hours.


Now, to actually plot some data, you can simply use the Insert charts function of Google Docs. We chose the simple Line graph for our data. The following screenshot shows the results for temperature and humidity:


We did the same for light level measurements

These charts can be placed automatically in their respective sheets inside your spreadsheet and will, of course, be updated automatically as new data comes in. You can also use the sharing capabilities of Google Docs to share these sheets with anyone, so they can also follow the measurements of your home.


Creating automated e-mail alerts

In this part, we are not only going to build on what we did in the previous section with Google Docs but also create some automated e-mail alerts on top with a Google account. This time, we will use the Temboo library that interfaces directly with Gmail, in this case, to automatically send an e-mail using your account.


 What we will do is program the Arduino Yún board to send an e-mail to the chosen address if the temperature goes below a given level, for example, indicating that you should turn on the heating in your home.


Compared to the previous Arduino sketch, we need to add the destination e-mail address. I used my own address for testing purposes, but of course, this destination address can be completely different from the one of your Gmail account.


For example, if you want to automatically e-mail somebody who is responsible for your home if something happens, execute the following line of code:

const String TO_EMAIL_ADDRESS = "your_email_address";


Please note that sending an e-mail to yourself might be seen as spam by your Gmail account. So, it's advisable to send these alerts to another e-mail of your choice, for example, on a dedicated account for these alerts.


We also need to set a temperature limit in the sketch. In my version of the project, it is the temperature under which the Arduino Yún will send an e-mail alert, but you can, of course, modify the meaning of this temperature limit, as shown in the following line of code:

int temperature_limit = 25.0;


In the loop() part of the sketch, what changes compared to the sketch of the previous section is that we can compare the recorded temperature to the limit. This is done with a simple if statement:

if (temperature < temperature_limit) {

if (debug_mode == true){Serial.println("Sending alert");} sendTempAlert("Temperature is too low!");


Then, the alert mechanism occurs in the new function called sendTempAlert that is called if the temperature is below the limit.


The function also takes a string as an argument, which is the content of the message that will be sent when the alert is triggered. Inside the function, we start again by declaring the type of Choreo that we will use.


This time, the Choreo that we will use is specific to Gmail and is used to send an e-mail with the subject and body of the message, as shown in the following line of code:


TembooChoreo SendEmailChoreo;

Just as the Choreo we used to log data into Google Docs, this new Choreo requires a given set of parameters that are defined in the official Temboo documentation. We need to specify all the required inputs for the Choreo, for example, the e-mail's subject line that you can personalize as well, as shown in the following line of code:

SendEmailChoreo.addInput("Subject", "ALERT: Home Temperature");

The body of the message is defined in the following line of code:

SendEmailChoreo.addInput("MessageBody", message);


Note that the message variable is the one passed in the loop() part of the sketch and can be personalized as well, for example, by adding the value of the measured temperature. Finally, the Choreo is executed with the following line of code:;

The complete code for this part can be found at temboo_alerts.


Now, you can compile and update the sketch to your Yún. You can also go to the Gmail interface to check for new e-mails. If the temperature indeed drops below the value that you set as a limit, the following is what you should receive in your inbox:


Again, you can play with this sketch and create more complex alerts based on the data you measured. For example, you can add the humidity and light level in the mix and create dedicated limits and alerts for these values. You can also program Arduino Yún so that it e-mails you the data itself at regular intervals, even if no temperature limit is reached.


Making your Arduino Yún board tweet sensor data


Arduino Yún board tweet sensor data

Finally, in the last part of this project, we will make your Arduino Yún board send its own messages on Twitter. You can even create a new Twitter account just for your Yún board, and you can tell people you know to follow it on Twitter so that they can be informed at all times about what's going on in your home!


The project starts on the Twitter website because you have to declare a new app on Twitter. Log in using your Twitter credentials and then go to https://apps.


Now, click on Create New App to start the process, You will need to give some name to your app. For example, we named our MyYunTemboo. You will need to get a lot of information from the Twitter website.


The first things you need to get are the API key and the API secret. These are available in the API Keys tab.


Make sure that the Access level of your app is set to Read, Write, and Direct Messages. This might not be active by default, and in the first tests, my Arduino board did not respond anymore because I didn't set these parameters correctly. So, make sure that your app has the correct access level.


Then, you are also going to need a token for your app. You can do this by going to the Your access token section. From this section, you need to get the Access token and the Access token secret. Again, make sure that the access level of your token is correctly set.


We can now proceed to write the Arduino sketch, so the Arduino Yún board can automatically send tweets. The Twitter Choreo is well known for using a lot of memory on the Yún, so this sketch will only tweet data without logging data into your Google Docs account.


I also recommend that you disable any debugging messages on the serial port to preserve the memory of your Yún. In the sketch, you first need to define your Twitter app information, as shown in the following code.

const String TWITTER_ACCESS_TOKEN = "yourAccessToken"; const String TWITTER_ACCESS_TOKEN_SECRET = " yourAccessTokenSecret";

const String TWITTER_API_KEY = " yourApiKey";

const String TWITTER_API_SECRET = " yourApiKeySecret";


Then, the sketch will regularly tweet the data about your home with the following function: tweetAlert(light level, temperature, humidity);

This function is repeated every minute using a delay() function, as follows: delay(60000);


Of course, this delay can be changed according to your needs. Let's see the details of this function. It starts by declaring the correct Choreo to send updates on Twitter: TembooChoreo StatusesUpdateChoreo;


Then, we build the text that we want to tweet as a string. In this case, we just formatted the sensor data in one string, as shown in the following code:

String tweetText = "Temperature: " + String(temperature) + ",
Humidity: " + String(humidity) + ", Light level: " + String(light);
The access token and API key that we defined earlier are declared as inputs:
StatusesUpdateChoreo.addInput("AccessToken", TWITTER_ACCESS_TOKEN);
StatusesUpdateChoreo.addInput("AccessTokenSecret", TWITTER_ACCESS_TOKEN_SECRET);
StatusesUpdateChoreo.addInput("ConsumerKey", TWITTER_API_KEY);


The text that we want to tweet is also simply declared as an input of the Twitter Choreo with the string variable we built earlier:

StatusesUpdateChoreo.addInput("StatusUpdate", tweetText);


The complete code for this part can be found at twitter.


Now that the Arduino sketch is ready, we can test it. You can simply upload the code to your Arduino Yún, and wait for a moment. Your board should automatically connect to the Twitter feed that you chose and print the data as a new message


If nothing shows up on your Twitter account, there are several things that you can check. I already mentioned memory usage; try to disable the debug output on the serial port to free some memory.


Also, make sure that you have entered the correct information about your Twitter app; it is quite easy to make a mistake between different API keys and access tokens.


For this project, I used the Twitter account of my website dedicated to home automation, but of course, you can create a dedicated Twitter account for the project so that many people can follow the latest updates about your home! 


You can also combine the code from this part with the idea of the previous section, for example, to create automated alerts based on the measured data and post messages on Twitter accordingly.


Creating a Remote Energy Monitoring and Control Device

In the second project of the blog, we will continue to use the features of the Arduino Yún to connect to the Web using the web service Temboo.


One thing people usually want to do in home automation is to follow the energy consumption of their electrical devices and turn them on or off remotely, for example, using their smartphones or tablets.


Of course, many devices that currently exist can measure energy consumption on a power socket as well as being able to switch the device that is connected to this socket on and off.


These devices are now very compact and easy to connect to a local Wi-Fi network, and these can also communicate with mobile devices using Bluetooth. Many large electronics manufacturers have developed their own solutions, and everyone can now buy these products and install them in their homes.


In this project, we are going to build our own do-it-yourself version of such a device and build a power switch and energy meter in order to turn an electrical device on and off as well as to follow its energy consumption.


The following are the main highlights of this blog:

• Connecting a relay to one of the Arduino Yún digital outputs and using the Yún REST API to command this relay from a web browser


• Using an analog current sensor to get a measurement of the instant current consumption from the device that is connected to the relay, and calculate the instant power consumption from this measurement


• Sending this data to a Google Docs spreadsheet so that it can be accessed remotely from any web browser or from the Google Docs mobile app, and calculating the energy consumption and some other useful data such as the total energy cost of the device connected to your project

• Creating a simple web interface to control the lamp using your computer or any smartphone or tablet


The required hardware and software components

The first part of this project is to get the required parts that we are going to use for our energy consumption meter and power switch project. Apart from the Arduino Yún board, which will be the "brain" of the project, you will need to have two main parts ready on your desk when building the project.


These parts are the relay module, which we will use to switch the lamp on and off, and the analog current sensor, which is used to measure the power and later the energy consumption of the lamp.


A relay is basically an electromagnetic switch used in projects where we need to switch a really large voltage (110V or 230V) using a small voltage as the command signal (5V from the Arduino board). For the relay, we used a basic 5V relay module from Polulu, which can switch up to 10A and is more than enough for many home appliances such as lamps.


(In Europe, with 230V, you can connect up to 2300W.) The module itself is simply a relay mounted on a printed circuit board along with the required components that are necessary to operate the relay and some large headers and traces to carry up to 10A if necessary. It uses an Omron G5LE-14-DC5 relay. The following image is the relay used:


Of course, you can use any equivalent relay module. Just make sure that it can be switched on/off using a digital 5V signal like we have on the Arduino Yún board and that it can switch at least 5A, just to be safe for this project.


The lamp we are using in this project only uses around 130 mA, but you may want to connect larger devices to your project later. If you want to build your own module from a relay, you simply need to add a diode in series with the relay to protect your Arduino board when the relay is switching.


Do not attempt to use a relay alone on a breadboard along with the required components to operate it.


The small tracks on the breadboard cannot support high currents and voltages and you will run into serious safety issues if you do so, such as the potential meltdown of these tracks, which can lead to a fire. So, use a dedicated relay module for this project.


Then, you need a current sensor to get the instant current consumption of the lamp. We used a module from ITead Studio, which is basically a breakout board for the ACS712 sensor.


A breakout board is simply a board that is composed of a printed circuit board, the chip itself, and all the components required to make the chip work, such as resistors and capacitors.


This sensor delivers an analog signal as an output, which is proportional to the measured current. This signal can then easily be converted to the corresponding current on the Arduino Yún board. We will acquire this analog signal using one of the integrated analog-digital converters of the Yún board.


Note that there are also noninvasive current sensors that you can simply clip around the cable you want to measure, but these are usually bigger and don't integrate well with Arduino projects. 


Just as for the relay module, you can use any equivalent current sensor for this project. The important parameters to be considered are the maximum current that can flow through the sensor (5A for the one we used) and the sensitivity of the sensor (185 mV/A for the one we used).


If these two parameters are similar to the sensor I used in this project, or if they are better, you can use the sensor.


You also need to connect the lamp to the project in some way. Of course, one way would be to directly cut the power cable of the lamp and connect the lamp directly to our project, but I don't like this option because it's quite messy.


As I mentioned in the introduction of this project, I don't want you to touch your lamp or another device in any way, and I want you to be able to connect your lamp again to the power socket in the wall if you want to.


I used two power cables so that I can connect my project to the wall socket on one side and connect the lamp to the project on the other side, just as I would do with a commercial device bought off the shelf.


The following is what I used for the power cable where I will plug the lamp: The following is the power cable I will use to connect the project to the wall plug:


Note that some power plugs have three cables (the additional cable being for the ground connection), but as we will be working with small loads such as lamps, the third cable is not necessary for this project.


On the hardware side, I also used a small piece of a breadboard to make the power connections of the relay and the current sensor (because the Arduino Yún board only has one 5V pin).


But of course, you can use a full-size breadboard to make these connections. On the software side, you will need the latest beta version of the Arduino IDE, which is the only one that supports the Arduino Yún board (I used Version 1.5.5 while doing this project).


Connecting the components to the Yún board

We are now going to connect the relay module and the current sensor to the Arduino Yún board, connect the power cable that will power up the lamp and finally connect everything to the power socket in the wall.


Building a Weather Station Connected to the Cloud, as it involves more steps and uses a higher voltage that requires you to take some precautions. So, please be careful and follow all the steps.


The first step is to put the Arduino Yún board, the relay module, and the current sensor board close to each other, as shown in the following image:

Arduino relay module

Creating a Remote Energy Monitoring and Control Device

Then, we are going to connect the power supply of the relay module and the current sensor. As I said earlier in this blog, the Arduino Yún board only has one 5V pin. This is why I connected the 5V pins of the two modules to a small piece of a breadboard first and then connected this breadboard to the Arduino 5V pin.


After this, we have to connect the ground pins of the two modules to the ground pin on the Arduino Yún board as shown in the following image. The Arduino Yún board has two ground pins on the board, so you don't have to use the breadboard for this.


To finish with the connection between the two modules, we need to connect their respective signal pins to the Arduino board. The relay will be controlled via pin number 8 of the Arduino Yún board, so connect the signal pin of the relay module to pin number 8 of the Yún board.


The current sensor has an analog output, so it has to be connected to one analog input on the Arduino board in order to acquire the signal using one of the Yún integrated analog-to-digital converters.


This converter will acquire the analog signal that comes from the sensor and transforms it into digital values that range from 0 to 1023 (which correspond to a 10-bit precision).


Connect the output pin of the current sensor module to pin number A0 of the Arduino Yún board, That's basically all for the low-power part. Now, we will focus on connecting the project to the two power supply cables so that we can plug the project into the wall plug and plug the lamp to the project. 


Finally, it's time to power up everything. You can plug your Arduino Yún board in to your computer via a USB cable (if you want to upload sketches directly and want space for your computer to be around the project) or via a wall power socket to a USB adapter (if you plan to upload the sketches via Wi-Fi and leave the project to work on its own).


Then, plug the lamp or the device that you want to control into the female power plug of the project. To finish, connect the male power plug to the power socket in the wall.


Be careful while performing this step: make sure that no electrical conductors are exposed, all screw terminals are correctly screwed and are holding the cables firmly, and no bare electrical conductors touch each other.


Testing your hardware connections

Now that the connections are done, we are going to test everything before we start sending energy consumption data to the cloud and building the interface to control the relay. We are going to test the different modules as if the project was already in operation.


For the entire duration of the tests, we are going to connect the project to the power socket in the wall and to the lamp that we want to control. This way, we will ensure that all the hardware connections are correct before moving further.


The relay, for example, will be controlled via Wi-Fi using the Arduino Yún REST API, just as it will be in the final version of the project.


Basically, we will just send a command from your web browser to directly set the value of the pin to which the relay is connected. Later in the project, we will make this call via a graphical user interface instead of actually typing the command in a browser.


For the current sensor, we are going to simply read the value measured on the analog pin A0 using the analog-to-digital converter of the Yún, convert it to a usable current, and then calculate the value of the effective current and the effective power as we already know the value of the effective voltage (110V or 230V depending on where you live).


Let's first have a look at the Arduino code. It starts by importing the right libraries, as shown in the following code. We need the Bridge library so that we can use the functions from the onboard Linux machine of the Yún, and the YunServer and YunClient libraries so that we can receive external commands using the REST API.


REST APIs are usually only used by web developers, but Arduino actually proposes a sketch that implements such an API for the Arduino Yún. This sketch is directly accessible in the library that comes with the Arduino Yún, and in this project, I used a modified version of this reference sketch.

#include <Bridge.h>

#include <YunServer.h>

#include <YunClient.h>

To use the REST API of the Yún, we need to create a YunServer instance, as shown in the following line of code. This server will run continuously and wait for incoming commands. YunServer server;


We also need to define the pins that our sensors are connected to, as shown in the following lines of code:

  • #define CURRENT_SENSOR A0
  • #define RELAY_PIN 8


One important part of the sketch is to declare the value of the effective voltage, which will be used later to calculate the effective power of the device, as shown in the following line of code. This value depends on where you are located (for example, 230 for Europe, and 110 for the USA):

float effective_voltage = 230;
In the setup() part, we need to start the bridge between the Arduino microcontroller and the Linux machine as follows:
We also need to start the web server as follows:


Then, the last and most important part of the setup() function is to calibrate the sensor in order to determine which value is returned when the current is null. This is done by the following line of code: zero_sensor = getSensorValue();


Let's dive into this function. We could simply get one measurement from the current sensor but that would be a bad idea. Indeed, the value that you get from the sensor varies slightly over time, around an average that we actually want to measure.


This is typical behavior when using analog sensors that have important sensitivities such as the one we are using here. This is why the function basically samples and averages the signal over several measurements with the following lines of code:

for (int i = 0; i < nb_measurements; i++) { sensorValue = analogRead(CURRENT_SENSOR); avgSensor = avgSensor + float(sensorValue);
avgSensor = avgSensor/float(nb_measurements);
After these measurements, we return the average as follows:
return avgSensor;


This way, we are sure to get a stable value of the sensor reading every time. This value is then used throughout the whole sketch as a reference value for the current sensor readings.


For example, if the measured value is equal to this reference, we will know that the current in the lamp is null. The actual sensor reading during the operation of the project uses the same function, so we always get a stable measurement.


Now, comes the loop() part of the sketch. It actually consists of two parts: in the first part, we will receive incoming connections on the Yún web server that we started earlier, and in the second part, we will print out the measurements that come from the current sensor.


For the web server part, we can listen for connections as follows:

YunClient client = server.accept();
If a client is detected, we process the request with the following code:
if (client) {
// Process request process(client);
// Close connection and free resources. client.stop();


I won't detail the Process function as it is the same as in the Bridge example for the Arduino Yún that we used earlier (this is available as an example in the Yún Bridge library).


To know more about the Yún REST API, you can visit the official Arduino documentation on the Arduino website at Arduino Yun.


Now, we will write the part of the sketch that is responsible for the current measurements. It starts when you get a stable measurement, just as we did earlier for the null current as follows: float sensor_value = getSensorValue();


I won't get into the details of this function as it is the same as which we used to get the value for the null current. We can now do some calculations on this measured value. First, we need to convert it to a usable current value as follows:



This is the amplitude of the current, which is a sinusoidal current. This formula can be found in the datasheet of the sensor as well as on the ITead Studio website.


Because we know this information about the current, to get the effective current, we simply need to divide it by the square root of two as follows: effective_value=amplitude_current/1.414;


To get the effective power, we then need to transform this current in amperes by dividing the value by 1000 and multiplying it with the effective voltage. I also added an absolute value operator so that the power is always positive, even when you connect the current sensor to measure negative currents, as follows: abs(effective_value*effective_voltage/1000);


The sketch ends by printing all these values on the Serial monitor and repeats itself every 50 milliseconds.

The complete sketch for this part is available on the GitHub repository of the blog at


Now you can upload the sketch to the Arduino board. Remember that at this point, the Arduino Yún board should be powered by either your computer or a USB power adapter, the lamp should be plugged to the project in the female power cord, and the project itself should be plugged into the wall socket.


The relay is quite easy to test; you just need to go to your web browser and type in the right command. The REST API of the Yún works by typing the name of your Arduino Yún board followed by .local. Then, if it is followed by Arduino/, you can directly use commands to change the value of the Arduino pins.


For example, to change the value of the relay pin to 1, you need to add digital/8/1. The preceding command means that you are calling the command digitalWrite(8, HIGH) using the REST API. You should instantly hear the relay switch and see the light turn on.


Try again by adding a 0 after the command instead of a 1; the relay should switch again and turn the light off. Don't worry, as later in the project, we'll build a nice graphical interface so that you don't have to write this command every time.


Now we are going to check the measurements coming from the current sensor. Make sure that the lamp is off, reset the Arduino microcontroller to be sure that the sketch starts from the beginning again, and then open the Serial monitor.


To do this, the Arduino Yún board has to be connected to your computer via the USB cable. The first thing you should see is the measurement for a null current as follows: Sensor value: 493.05


Then, the sketch continuously displays the value of the sensor reading, current amplitude, effective current, and effective power. Even if the current is null, remember that we average the sensor readings over several measurements, so there can be minor fluctuations in the value, as shown in the following code:

Sensor value: 492.87
Current amplitude (in mA):4.5
Current effective value (in mA)3.2
Effective power (in W):0.7


If you then turn the lamp on using the REST call in your browser, you should instantly see a change in the current and power readings as follows:

Sensor value: 486.52
Current amplitude (in mA):-163.1
Current effective value (in mA)-115.4
Effective power (in W):26.5


If you can see these values and your relay is responding to the REST calls in your browser, it means that your hardware is working correctly and you can proceed to the next step.


If it doesn't work, the first step is to check the different connections of the current sensor and relay module. Also check that you have selected the correct Serial speed in the Serial monitor so that it matches the speed defined in the sketch.


Sending data to Google Docs

The first step is to set up a Google Docs spreadsheet for the project. Create a new sheet, give it a name (I named mine Power for this project, but you can name it as you wish), and set a title for the columns that we are going to use.


Time, Interval, Power, and Energy (that will be calculated from the first two columns), We can also calculate the value of the energy using the other measurements. From theory, we know that over a given period of time, energy is power multiplied by time; that is, Energy = Power * Time.


However, in our case, power is calculated at regular intervals, and we want to estimate the energy consumption for each of these intervals. In mathematical terms, this means we need to calculate the integral of power as a function of time.


We don't have the exact function between time and power as we sample this function at regular time intervals, but we can estimate this integral using a method called the trapezoidal rule.


It means that we basically estimate the integral of the function, which is the area below the power curve, by a trapeze. The energy in the C2 cell in the spreadsheet is then given by the formula:

Energy= (PowerMeasurement + NextPowerMeasurement)*TimeInverval/2.

Concretely, in Google Docs, you will need the formula, D2 = (B2 + B3)*C2/2.


The Arduino Yún board will give you the power measurement, and the time interval is given by the value we set in the sketch. However, the time between two measurements can vary from measurement to measurement.


This is due to the delay introduced by the network. To solve this issue, we will transmit the exact value along with the power measurement to get a much better estimate of energy consumption.


Then, it's time to build the sketch that we will use for the project. The goal of this sketch is basically to wait for commands that come from the network, to switch the relay on or off, and to send data to the Google Docs spreadsheet at regular intervals to keep track of the energy consumption.


We will build the sketch on top of the sketch we built earlier so I will explain which components need to be added. First, you need to include your Temboo credentials using the following line of code: #include "TembooAccount.h"


Since we can't continuously measure the power consumption data (the data transmitted would be huge, and we will quickly exceed our monthly access limit for Temboo!), like in the test sketch, we need to measure it at given intervals only.


However, at the same time, we need to continuously check whether a command is received from the outside to switch the state of the relay. This is done by setting the correct timings first, as shown in the following code:

int server_poll_time = 50;

int power_measurement_delay = 10000;

int power_measurement_cycles_max = power_measurement_delay/server_ poll_time;


The server poll time will be the interval at which we check the incoming connections. The power measurement delay, as you can guess, is the delay at which the power is measured.


However, we can't use a simple delay function for this as it will put the entire sketch on hold. What we are going to do instead is to count the number of cycles of the main loop and then trigger a measurement when the right amount of cycles have been reached using a simple if statement. The right amount of cycles is given by the power measurement cycles_max variable.


You also need to insert your Google Docs credentials using the following lines of code:

const String GOOGLE_USERNAME = "yourGoogleUsername"; const String GOOGLE_PASSWORD = "yourGooglePass"; const String SPREADSHEET_TITLE = "Power";


In the setup() function, you need to start a dating process that will keep a track of the measurement date. We want to keep a track of the measurement over several days, so we will transmit the date of the day as well as the time, as shown in the following code:

time = millis();

if (!date.running()) {
In the loop() function of the sketch, we check whether it's time to perform a measurement from the current sensor, as shown in the following line of code:
if (power_measurement_cycles > power_measurement_cycles_max)
If that's the case, we measure the sensor value, as follows:
float sensor_value = getSensorValue();


We also get the exact measurement interval that we will transmit along with the measured power to get a correct estimate of the energy consumption, as follows:

measurements_interval = millis() - last_measurement; last_measurement = millis();


We then calculate the effective power from the data we already have. The amplitude of the current is obtained from the sensor measurements as shown earlier. Then we can get the effective value of the current by dividing this amplitude by the square root of 2.


Finally, as we know the effective voltage and that power is current multiplied by voltage, we can calculate the effective power as well, as shown in the following code:

// Convert to current

// Calculate power
float effective_power = abs(effective_value * effective_voltage/1000);


After this, we send the data with the time interval to Google Docs and reset the counter for power measurements, as follows:

runAppendRow(measurements_interval,effective_power); power_measurement_cycles = 0;


 Building a Weather Station Connected to the Cloud. Let's quickly go into the details of this function. It starts by declaring the type of Temboo library we want to use, as follows:

TembooChoreo AppendRowChoreo;
Start with the following line of code:
We then need to set the data that concerns your Google account, for example, the username, as follows:
AppendRowChoreo.addInput("Username", GOOGLE_USERNAME);
The actual formatting of the data is done with the following line of code:
data = data + timeString + "," + String(interval) + "," + String(effectiveValue);
Here, interval is the time interval between two measurements, and effectiveValue is the value of the measured power that we want to log on to Google Docs. The Choreo is then executed with the following line of code:;
Finally, we do this after every 50 milliseconds and get an increment to the power measurement counter each time, as follows:


The code for this part is complete. You can now upload the sketch and after that, open the Google Docs spreadsheet and then just wait until the first measurement arrives. 


After a few moments, I got several measurements logged on my Google Docs spreadsheet. I also played a bit with the lamp control by switching it on and off so that we can actually see changes in the measured data. I used the built-in plotting capabilities of Google Docs to plot the power consumption over time on a graph.


From the data you get in this Google Docs spreadsheet, it is also quite easy to get other interesting data. You can, for example, estimate the total energy consumption over time and the price that it will cost you. The first step is to calculate the sum of the energy consumption column using the integrated sum functionality of Google Docs.


Then, you have the energy consumption in Joules, but that's not what the electricity company usually charges you for. Instead, they use kWh, which is basically the Joule value divided by 3,600,000.


The last thing we need is the price of a single kWh. Of course, this will depend on the country you're living in, but at the time of writing this blog, the price in the USA was approximately $0.16 per kWh.


To get the total price, you then just need to multiply the total energy consumption in kWh with the price per kWh. This is the result of the data I recorded. Of course, as I only took a short sample of data, it cost me nearly nothing in the end


You can also estimate the on/off time of the device you are measuring. For this purpose, I simply added an additional column next to Energy named On/Off.

I simply used the formula =IF(C2<2;0;1).


It means that if the power is less than 2W, we count it as an off state; otherwise, we count it as an on state. I didn't set the condition to 0W to count it as an off state because of the small fluctuations over time from the current sensor.


Then, when you have this data about the different on/off states, it's quite simple to count the number of occurrences of each state, for example, on states, using =COUNTIF(E:E,"1").


I applied these formulas in my Google Docs spreadsheet, and the following screenshot is the result with the sample data I recorded:

It is also very convenient to represent this data in a graph. For this, I used a pie chart, which I believe is the most adaptable graph for this kind of data.


With the preceding kind of chart, you can compare the usage of a given lamp from day to day, for example, to know whether you have left the lights on when you are not there.


Building an interface to switch the lights on/off remotely

Now that our project automatically logs data concerning the energy consumption on Google Docs, it's time to go back to the relay control. For now, we tested the relay by going into a web browser and typing the correct REST function with the name of the pin we want to change.


However, that's not very convenient. You don't want to type something in your web browser every time you want to turn a light on in your home. What we would like to have instead is a nice graphical interface with buttons that can be pressed to turn a light on or off.


It would be even better if this interface could be accessed not only from a web browser on your computer but also from any smartphone or tablet in your home. That's exactly what we are going to build now.


We need several components to do so, and we will mix several programming languages to build the best graphical interface possible. We will use HTML for the main page that will host the on/off button, JavaScript to handle the actions of this button, and PHP to transmit the correct command to the Arduino server.


We are also going to use some CSS to make the interface look much better and automatically adapt itself to the device you are using, such as a smartphone.


First, let's deal with the HTML code. We need to import the jQuery library and the file that will contain all the JavaScript code, as follows:

<script class='lazy' data-src="jquery-2.0.3.min.js"></script>

<script class='lazy' data-src="script.js"></script>
Also, import the CSS style file, as follows:
<link rel="stylesheet" type="text/css" href="style.css">
The core of this HTML file is to create two buttons; one button to switch the relay on and the other to switch it off again. The following, for example, is the code for the On button:
<input type="button" id="on" class="commandButton" value="On" onClick="relayOn()"/>


Now, if you were to actually take this file as it is, it would look really bad as some default styles would be applied to the buttons. That's why we attached a CSS file to make the interface look a bit better. For example, I decided to center align the main form that contains the two buttons, as follows:

#relay {

text-align: center;