In this chapter, we will cover:
Setting up the Arduino development environment
Options for Internet connectivity with Arduino
Interacting with basic sensors
Interacting with basic actuators
Configuring your Arduino board for the IoT
Grabbing the content from a web page
Sending data to the cloud
Troubleshooting basic Arduino issues
This first chapter of this book is focused on getting you started by connecting an Arduino board to the Web. This chapter will really be the foundation of the rest of the book, so make sure to carefully follow the instructions so you are ready to complete the exciting projects we'll see in the rest of the book.
You will first learn how to set up the Arduino IDE development environment, and add Internet connectivity to your Arduino board.
After that, we'll see how to connect a sensor and a relay to the Arduino board, for you to understand the basics of the Arduino platform. Then, we are actually going to connect an Arduino board to the Web, and use it to grab content from the Web and to store data online.
In this first recipe of the book, we are going to see how to completely set up the Arduino IDE development environment, so that you can later use it to program your Arduino board and build Internet of Things projects.
The first thing you need to do is to download the latest version of the Arduino IDE from the following address:
https://www.arduino.cc/en/Main/Software
This is what you should see, and you should be able to select your operating system:
You can now install the Arduino IDE, and open it on your computer. The Arduino IDE will be used through the whole book for several tasks. We will use it to write down all the code, but also to configure the Arduino boards and to read debug information back from those boards using the Arduino IDE Serial monitor.
What we need to install now is the board definition for the MKR1000 board that we are going to use in this book. To do that, open the Arduino boards manager by going to Tools | Boards | Boards Manager. In there, search for SAMD boards:
To install the board definition, just click on the little Install button next to the board definition.
You should now be able to select the Arduino/GenuinoMKR1000 board inside the Arduino IDE:
You are now completely set to develop Arduino projects using the Arduino IDE and the MKR1000 board. You can, for example, try to open an example sketch inside the IDE:
The Arduino IDE is the best tool to program a wide range of boards, including the MKR1000 board that we are going to use in this book. We will see that it is a great tool to develop Internet of Things projects with Arduino. As we saw in this recipe, the board manager makes it really easy to use new boards inside the IDE.
Most of the boards made by Arduino don't come with Internet connectivity, which is something that we really need to build Internet of Things projects with Arduino. We are now going to review all the options that are available to us with the Arduino platform, and see which one is the best to build IoT projects.
The first option, which has been available since the advent of the Arduino platform, is to use a shield. A shield is basically an extension board that can be placed on top of the Arduino board. There are many shields available for Arduino. Inside the official collection of shields, you will find motor shields, prototyping shields, audio shields, and so on.
Some shields will add Internet connectivity to the Arduino boards, for example, the Ethernet shield or the Wi-Fi shield. This is an image of the Ethernet shield:
The other option is to use an external component, for example, a Wi-Fi chip mounted on a breakout board, and then connect this shield to Arduino.
There are many Wi-Fi chips available on the market. For example, Texas Instruments has a chip called the CC3000 that is really easy to connect to Arduino. This is an image of a breakout board for the CC3000 Wi-Fi chip:
Finally, there is the possibility of using one of the few Arduino boards that has an onboard Wi-Fi chip or Ethernet connectivity.
The first board of this type introduced by Arduino was the Arduino Yun board. It is a really powerful board, with an onboard Linux machine. However, it is also a bit complex to use compared to other Arduino boards.
Then, Arduino introduced the MKR1000 board, which is a board that integrates a powerful ARM Cortex M0+ process and a Wi-Fi chip on the same board, all in the small form factor.
Here is an image of this board:
All the solutions above would work to build powerful IoT projects using Arduino. However, as we want to easily build those projects and possibly integrate them into projects that are battery-powered, I chose to use the MKR1000 board for all the projects in this book.
This board is really simple to use, powerful, and doesn't require any connections to hook it up with a Wi-Fi chip. Therefore, I believe this is the perfect board for IoT projects with Arduino.
Of course, there are other options to connect Arduino boards to the Web. One option that's becoming more and more popular is to use 3G or LTE to connect your Arduino projects to the Web, again using either shields or breakout boards. This solution has the advantage of not requiring an active Internet connection like a Wi-Fi router, and can be used anywhere, for example, outdoors.
In this recipe, we are going to see how to measure data coming from sensors connected to the MKR1000 board. This will really teach us the very basics of the Arduino language. As an example, we'll use a simple photocell to measure the ambient light level around the project.
For this project, you will need a few extra components in addition to the Arduino MKR1000 board and the usual breadboard and jumper wires:
Photocell (https://www.sparkfun.com/products/9088)
10K Ohm resistor (https://www.sparkfun.com/products/8374)
We are now going to assemble the project. First, place the resistor in series with the photocell on the breadboard, next to the MKR1000 board.
Now, connect the other end of the resistor to GND on the MKR1000 board, and the other end of the photocell to the VCC pin of the Arduino board. Finally, connect the middle pin between the resistor and the photocell to analog pin A0 of the MKR1000.
This is the final result:
We are now going to configure the board to read data coming from the photocell. The sketch for this part will be really simple, as we will simply print the readings of analog pin A0 on the serial port. This is the complete sketch for this part:
// Pins int sensorPin = A0; void setup() { // Serial Serial.begin(115200); } void loop() { // Reading int sensorValue = analogRead(sensorPin); // Display Serial.print("Sensor reading: "); Serial.println(sensorValue); // Wait delay(500); }
Once you have finished uploading, open the Serial monitor. You should immediately see the readings from the sensor:
Now, simply try to put your hand on top of the sensor. You should immediately see the value measured by the sensor coming down, meaning the sensor is working correctly.
This project was really simple, and illustrated how to read data from an analog pin on the MKR1000 board. In this project, we simply read data on analog pin A0, and printed the readings on the Serial monitor. As the photocell is acting as a variable resistor (depending on the ambient light level), we are directly reading a signal that changes depending on the ambient light level.
In this recipe, we are now going to see how to control the outputs of the Arduino board. This will be very useful in the rest of the book, as we will control several output devices, such as lamps.
To realize this recipe, we first need to have something to control. Here, I will just use a simple relay, but you can of course use components, such as a single LED.
This is the relay I used for this recipe:
5V relay (https://www.pololu.com/product/2480)
We are now going to assemble the project for this recipe. First, plug the MKR1000 board into the breadboard. After that, connect the relay VCC pin to the VCC pin of the Arduino board, and the GND pin to the ground of the MKR1000. Finally, connect the SIG pin of the relay to pin 5 of the Arduino board. This is the final result:
We are now going to configure the board to see how to control outputs, like this relay. To illustrate this we are going to switch the relay on and off every second. This is the complete sketch for this recipe:
// Pins int relayPin = 5; void setup() { // Set pin as output pinMode(relayPin, OUTPUT); } void loop() { // Set relay ON digitalWrite(relayPin, HIGH); // Wait delay(1000); // Set relay OFF digitalWrite(relayPin, LOW); // Wait delay(1000); }
Now, copy this sketch into the Arduino IDE and upload it to the Arduino board. Once that's done, you should immediately see (and hear) the relay switching on and off every second.
The sketch simply uses the digitalWrite()
function of the Arduino language to control the state of the pin to which the relay is connected, along with the delay()
function, therefore switching the relay on and off continuously.
You can, of course, use what you learned in this project to control other output devices, such as LEDs. We are going to see in other recipes, later in this book, how to control larger output devices, such as lamps and other home appliances.
In this recipe, we are going to finally learn how to use the on-board Wi-Fi chip that is on the MKR1000 board, and connect the board to your local Wi-Fi. This is a very important recipe, are we are going to use this in nearly every recipe of this book to build IoT projects.
Before we can use the Wi-Fi chip that is on the board, we need an Arduino library to be able to control it. The library for this chip is called the WiFi101
library and you can find it inside the Arduino library manager.
To access the library manager, simply go to Sketch | Include Library | Manage Libraries inside the Arduino IDE. Then, type wifi101
to find the library:
To install the library from there, simply click on the Install button just next to the library version.
Let's now connect the board to your Wi-Fi network. The sketch is quite long here, so I have split it into three parts.
This is the main part of the sketch, which will actually connect your chip to your local Wi-Fi network:
// Libraries #include <SPI.h> #include <WiFi101.h> // Credentials char ssid[] = "wifi-name"; // your network SSID (name) char pass[] = "wifi-pass"; // your network password int status = WL_IDLE_STATUS; // the Wifi radio's status void setup() { // Serial Serial.begin(115200); // Attempt to connect to Wifi network: while ( status != WL_CONNECTED) { Serial.print("Attempting to connect to WPA SSID: "); Serial.println(ssid); // Connect to WPA/WPA2 network: status = WiFi.begin(ssid, pass); // Wait 10 seconds for connection: delay(10000); } // you're connected now, so print out the data: Serial.print("You're connected to the network"); printCurrentNet(); printWifiData(); } void loop() { // Check the network connection once every 10 seconds: delay(10000); printCurrentNet(); }
What you actually need to change here are the following lines:
char ssid[] = "wifi-name"; // your network SSID (name) char pass[] = "wifi-pass"; // your network password
You need to change those lines to put your own Wi-Fi network's name and password. This is something you will have to do in all the sketches for the rest of this book, as we are always going to connect the Arduino board to the local Wi-Fi network.
Then, the following function will print data about your IP address:
void printWifiData() { // print your WiFi shield's IP address: IPAddress ip = WiFi.localIP(); Serial.print("IP Address: "); Serial.println(ip); Serial.println(ip); // print your MAC address: byte mac[6]; WiFi.macAddress(mac); Serial.print("MAC address: "); Serial.print(mac[5], HEX); Serial.print(":"); Serial.print(mac[4], HEX); Serial.print(":"); Serial.print(mac[3], HEX); Serial.print(":"); Serial.print(mac[2], HEX); Serial.print(":"); Serial.print(mac[1], HEX); Serial.print(":"); Serial.println(mac[0], HEX); }
And this function will print data about the current Wi-Fi network to which your Arduino board is connected:
void printCurrentNet() { // print the SSID of the network you're attached to: Serial.print("SSID: "); Serial.println(WiFi.SSID()); // print the MAC address of the router you're attached to: byte bssid[6]; WiFi.BSSID(bssid); Serial.print("BSSID: "); Serial.print(bssid[5], HEX); Serial.print(":"); Serial.print(bssid[4], HEX); Serial.print(":"); Serial.print(bssid[3], HEX); Serial.print(":"); Serial.print(bssid[2], HEX); Serial.print(":"); Serial.print(bssid[1], HEX); Serial.print(":"); Serial.println(bssid[0], HEX); // print the received signal strength: long rssi = WiFi.RSSI(); Serial.print("signal strength (RSSI):"); Serial.println(rssi); // print the encryption type: byte encryption = WiFi.encryptionType(); Serial.print("Encryption Type:"); Serial.println(encryption, HEX); Serial.println(); }
It's now time to finally test this sketch and connect your board to the Internet! You can get the whole sketch from the GitHub repository of the following book:
https://github.com/marcoschwartz/iot-arduino-cookbook
Now, make sure to change your Wi-Fi name and password inside the sketch, and then upload the sketch to the board. Immediately open the Serial monitor. This is what you should see:
If you can see something similar, congratulations, your board is now connected to your Wi-Fi network and to the Internet (assuming your Wi-Fi router is connected to the Internet).
To illustrate how the WiFi101
library is working on the MKR1000 board, we are now going to use it to grab the content of a web page, and display the result inside the Serial monitor.
You do not need any extra steps here, simply make sure that you have the WiFi101
library installed.
Let's now see the sketch for this recipe. As it is really similar to the sketch of the previous recipe, I will only highlight the main pieces of code that were added here:
You first need to define which page we are going to grab. Here, I will just make the board grab the
www.example.com
page:char server[] = "www.example.com";
Then, we need to create an instance of a Wi-Fi client:
WiFiClient client;
Then, inside the
setup()
function of the sketch, we connect to the server we defined earlier, and request the Web page:// Connect to server if (client.connect(server, 80)) { Serial.println("connected to server"); // Make a request: client.println("GET / HTTP/1.1"); client.println("Host: www.example.com"); client.println("Connection: close"); client.println(); }
Inside the
loop()
function of the sketch, we then read the data coming back from the server, and print it inside the Serial port:while (client.available()) { char c = client.read(); Serial.write(c); }
We then stop the connection with the following piece of code:
// Stop the connection if (!client.connected()) { Serial.println(); Serial.println("disconnecting from server."); client.stop(); // do nothing forevermore: while (true); }
It's now time to try this sketch! First, grab the code from the GitHub repository of this book, and then change your Wi-Fi credentials inside the code. Then, upload the code to the board, and open the Serial monitor. This is what you should see:
If you can see that, it means that the board has successfully grabbed the content of the web page and displayed it inside the Serial monitor.
The sketch uses the Wi-Fi client of the WiFi101
library, which is a very powerful object that we will use again in several chapters of this book.
In the last recipe of this chapter, we are actually going to use everything we learned so far in this chapter and apply it to a simple project: sending data to a cloud server, so it can be stored there. This is something that we are going to do many times in this book, but I wanted to give you a short overview first.
For this recipe, you will need the same configuration that we used in the recipe Interacting with basic sensors, but ? with a photocell connected to the Arduino board. Please refer to this recipe to know how to assemble the hardware for the project.
Let's now see the sketch that we will use for this chapter. It is actually very similar to the code for the previous chapter, so I will just highlight the important parts here.
As before, we define the server to which we want to connect the board. Here, we will use the dweet.io
service:
char server[] = "dweet.io";
We also define an interval on which we will send data to the dweet.io
servers:
unsigned long lastConnectionTime = 0; const unsigned long postingInterval = 10L * 1000L;
In the loop()
function, we check if it is time to send data. If so, we measure the reading from the sensor, and send this to a function that will send the data:
if (millis() - lastConnectionTime > postingInterval) { // Measure light level int sensorData = analogRead(A0); // Send request httpRequest(sensorData); }
Let's now see the details of this function:
void httpRequest(int sensorData) { // Close existing connection client.stop(); // Connect & send request if (client.connect(server, 80)) { Serial.println("connecting..."); // Send the HTTP PUT request: client.println("GET /dweet/for/myarduino?light=" + String(sensorData) + " HTTP/1.1"); client.println("Host: dweet.io"); client.println("User-Agent: ArduinoWiFi/1.1"); client.println("Connection: close"); client.println(); // Note the time that the connection was made: lastConnectionTime = millis(); } else { // if you couldn't make a connection: Serial.println("connection failed"); } }
As you can see, the function is very similar to what we did in the previous recipe. The main difference is that we pass the measured data as an argument when calling the dweet.io
server.
You can now grab the code from the GitHub repository of this book, and upload it to the board.
Then, open the Serial monitor, and this is what you should see:
If you can see the 'succeeded' message, it means that the data has been correctly stored on the server.
To check that it was actually recorded, you can now go to the following URL:
https://dweet.io/get/latest/dweet/for/myarduino
You should see the answer in JSON format, meaning data was recorded from your board.
In this part of the chapter, we are going to see what can go wrong when configuring your board and connecting it to the Internet. Indeed, some of the steps involved here are quite complex and many things can go differently than expected.
The first thing that can happen is that the board is not visible from the Arduino IDE, even if you have it connected to your computer via USB. Make sure that you are using a data USB cable: many cables nowadays are just for charging and don't actually allow data transfers. If you are using Windows, also make sure to refer to the Arduino website to install the required drivers.
If you can't connect the board to your local Wi-Fi router, make sure that you correctly entered your Wi-Fi name and password inside the sketch before uploading it to the board. The sketches of this book are made for WPA Wi-Fi networks, which are most of the networks out there. However, if you are still using a WEP network, make sure to check the Arduino WiFi101 example sketches to learn how to connect the board to a WEP network.