In this chapter you will
This chapter will show you how to connect your Arduino to the outside world via the internet. This allows you to broadcast data from your Arduino and remotely control your Arduino from a web browser.
To build these internet-related projects, you will need some common hardware, a cable, and some information.
Let’s start with the hardware. You’ll need an Ethernet shield with the W5100 controller chip. You have two options to consider: you can use the genuine Arduino-brand Ethernet shield, as shown in Figure 21-1, or you can use an Arduino Uno–compatible board with integrated Ethernet hardware, such PMD Way part 328497, as shown in Figure 21-2. The latter is a good choice for new projects or when you want to save physical space and money. As you can see, the integrated board has the connectors for Arduino shields, a USB port, an Ethernet socket, and a microSD card socket.
Regardless of your choice of hardware, you’ll also need a standard 10/100 CAT5, CAT5E, or CAT6 network cable to connect your Ethernet shield to your network router or internet modem.
In addition, you’ll need the IP address of your network’s router gateway or modem, which should look something like this: 192.168.0.1. You’ll also need your computer’s IP address in the same format as your router’s IP address.
Finally, if you want to communicate with your Arduino from outside your home or local area network, you’ll need a static, public IP address. A static IP address is a fixed address assigned to your physical internet connection by your internet service provider (ISP). Your internet connection may not have a static IP address by default; contact your ISP to have this activated if necessary. If your ISP cannot offer a static IP or if it costs too much, you can get an automated redirection service that offers a hostname that can divert to your connection’s IP address through a third-party company, such as No-IP (http://www.noip.com/) or Dyn (https://account.dyn.com/). Now let’s put our hardware to the test with a simple project.
In projects in previous chapters, we gathered data from sensors to measure temperature and light. In this project, you’ll learn how to display those values on a simple web page that you can access from almost any web-enabled device. This project will display the values of the analog input pins and the status of digital inputs 0 to 9 on a simple web page, functionality that will serve as the basis for a remote monitoring station.
Using this framework, you can add sensors with analog and digital outputs, such as temperature, light, and switch sensors, and then display the sensors’ status on a web page.
Here’s what you’ll need to create this project:
Enter the following sketch, but don’t upload it yet:
/* Project 60 – Building a Remote Monitoring Station
created 18 Dec 2009 by David A. Mellis, modified 9 Apr 2012 by Tom Igoe
modified August 2020 by John Boxall
*/
#include <SPI.h>
#include <Ethernet.h>
1 IPAddress ip(xxx,xxx,xxx,xxx); // Replace this with your project's IP address
2 byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
EthernetServer server(80);
void setup()
{
// Start the Ethernet connection and server
Ethernet.begin(mac, ip);
server.begin();
for (int z=0; z<10; z++)
{
pinMode(z, INPUT); // set digital pins 0 to 9 to inputs
}
}
void loop()
{
// listen for incoming clients (incoming web page request connections)
EthernetClient client = server.available();
if (client) {
// an HTTP request ends with a blank line
boolean currentLineIsBlank = true;
while (client.connected()) {
if (client.available()) {
char c = client.read();
if (c == '
') && currentLineIsBlank) {
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println("Connection: close");
client.println();
client.println("<!DOCTYPE HTML>");
client.println("<html>");
// add a meta refresh tag, so the browser pulls again every 5 sec:
3 client.println("<meta http-equiv="refresh" content="5">");
// output the value of each analog input pin onto the web page
for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
int sensorReading = analogRead(analogChannel);
4 client.print("analog input ");
client.print(analogChannel);
client.print(" is ");
client.print(sensorReading);
client.println("<br />");
}
// output the value of digital pins 0 to 9 onto the web page
for (int digitalChannel = 0; digitalChannel < 10; digitalChannel++)
{
boolean pinStatus = digitalRead(digitalChannel);
client.print("digital pin ");
client.print(digitalChannel);
client.print(" is ");
client.print(pinStatus);
client.println("<br />");
}
client.println("</html>");
break;
}
if (c == '
') {
// you're starting a new line
currentLineIsBlank = true;
}
else if (c != '
') {
// you've gotten a character on the current line
currentLineIsBlank = false;
}
}
}
// give the web browser time to receive the data
delay(1);
// close the connection:
client.stop();
}
}
We’ll discuss this sketch in more detail a bit later. First, before uploading the sketch, you’ll need to enter an IP address for your Ethernet shield so that it can be found on your local network or modem. You can determine the first three parts of the address by checking your router’s IP address. For example, if your router’s address is 192.168.0.1, change the last digit to something random and different from that of other devices on your network, using a number between 2 and 254 that isn’t already in use on your network. Enter the altered IP address at 1 in the sketch, like so:
IPAddress ip(192, 168, 0, 69); // Ethernet shield's IP address
Once you’ve made that change, save and upload your sketch. Next, insert the Ethernet shield into your Arduino if required, connect the network cable to your router or modem and the Ethernet connector, and power on your Arduino board.
Wait about 20 seconds. Then, using a web browser on any device or computer on your network, enter the IP address from 1. If you see something like Figure 21-3, the framework of your monitoring station is working correctly.
If this project doesn’t work for you, try the following:
Once your monitoring station is working, you can return to the most important parts of the sketch. The code from the beginning until 3 is required because it loads the necessary libraries and starts the Ethernet hardware in void setup()
. Prior to 3, the client.print()
statements are where the sketch sets up the web page to allow it to be read by the web browser. From 3 on, you can use the functions client.print()
and client.println()
to display information on the web page as you would with the Serial Monitor. For example, the following code is used to display the first six lines of the web page shown in Figure 19-3:
client.print("analog input ");
client.print(analogChannel);
client.print(" is ");
client.print(sensorReading);
At 4, you see an example of writing text and the contents of a variable to the web page. Here you can use HTML to control the look of your displayed web page, as long as you don’t overtax your Arduino’s memory. In other words, you can use as much HTML code as you like until you reach the maximum sketch size, which is dictated by the amount of memory in your Arduino board. (The sizes for each board type are described in Table 13-2 on page 234.)
One thing to notice is the MAC address that networks can use to detect individual pieces of hardware connected to the network. Each piece of hardware on a network has a unique MAC address, which can be changed by altering one of the hexadecimal values at 2. If two or more Arduino-based projects are using one network, you must enter a different MAC address for each device at 2. If your shield has a MAC address included with it, use that value.
Finally, if you want to view your web page from a device that is not connected to your local network, such as a tablet or phone using a cellular connection, then you’ll need to use a technique called port forwarding in your network router or modem, provided by an organization such as the previously mentioned No-IP or Dyn. Port forwarding is often unique to the make and model of your router, so do an internet search for “router port forwarding” or visit a tutorial site such as http://www.wikihow.com/Port-Forward for more information.
Now that you know how to display text and variables on a web page, let’s use the Arduino to tweet.
In this project, you’ll learn how to make your Arduino send tweets through Twitter. You can receive all sorts of information that can be generated by a sketch from any device that can access Twitter. If, for example, you want hourly temperature updates from home while you’re abroad or even notifications when the kids come home, this can offer an inexpensive solution.
Your Arduino will need its own Twitter account, so do the following:
Here’s what you’ll need to create this project:
Enter the following sketch, but don’t upload it yet:
// Project 61 - Creating an Arduino Tweeter
#include <SPI.h>
#include <Ethernet.h>
#include <Twitter.h>
// Ethernet shield settings
1 IPAddress ip(192,168,0,1); // Replace this with your project's IP address
2 byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
3 Twitter twitter("insertyourtokenhere");
// Message to post
4 char msg[] = "I'm alive!";
void setup()
{
delay(1000);
Ethernet.begin(mac, ip);
// or you can use DHCP for automatic IP address configuration
// Ethernet.begin(mac);
Serial.begin(9600);
Serial.println("connecting ...");
}
void loop()
{
5 if (twitter.post(msg)) {
int status = twitter.wait(&Serial);
if (status == 200) {
Serial.println("OK.");
} else {
Serial.print("failed : code ");
Serial.println(status);
}
} else {
Serial.println("connection failed.");
}
while (1);
}
As with Project 60, insert your IP address at 1 and modify the MAC address if necessary at 2. Then insert the Twitter token between the double quotes at 3. Finally, insert the text that you want to tweet at 4. Now upload the sketch and connect your hardware to the network. (Don’t forget to follow your Arduino’s Twitter account with your own account!) After a minute or so, visit your Twitter page or load the app on a device, and the message should be displayed, as shown in Figure 21-4.
When you’re creating your Arduino tweeter, keep in mind that you can send no more than one tweet per minute and that each message must be unique. (These are Twitter’s rules.) When sending tweets, Twitter also replies with a status code. The sketch will receive and display this in the Serial Monitor using the code at 5. Figure 21-5 shows an example.
If you receive a 403 message like this, either your token is incorrect or you’re sending tweets too quickly. (For a complete list of Twitter error codes, see https://finderrorcode.com/twitter-error-codes.html.)
You can control your Arduino from a web browser in several ways. After doing some research, I’ve found a method that is reliable, secure, and free: Teleduino.
Teleduino is a free service created by New Zealand Arduino enthusiast Nathan Kennedy. It’s a simple yet powerful tool for interacting with an Arduino over the internet. It doesn’t require any special or customized Arduino sketches; instead, you simply enter a special URL into a web browser to control the Arduino. You can use Teleduino to control digital output pins and servos or to send I2C commands, and more features are being added all the time. In Project 62, you’ll learn how to configure Teleduino and remotely control digital outputs from a web-enabled device.
Before starting your first Teleduino project, you must register with the Teleduino service and obtain a unique key to identify your Arduino. To do so, visit https://www.teleduino.org/tools/request-key/ and enter the required information. You should receive an email with your key, which will look something like this: 187654321Z9AEFF952ABCDEF8534B2BBF
.
Next, convert your key into an array variable by visiting https://www.teleduino.org/tools/arduino-sketch-key/. Enter your key, and the page should return an array similar to that shown in Figure 21-6.
Each key is unique to a single Arduino, but you can get more keys if you want to run more than one Teleduino project at a time.
Here’s what you’ll need to create this project:
Assemble your hardware and connect an LED to digital pin 8, as shown in Figure 21-7.
Projects in Teleduino use only one sketch, which is included with the Teleduino library. Here’s how to access the sketch:
Now connect your hardware to the network and watch the LED. After a minute or so, it should blink a few times and then rest. The number of blinks represents the status of the Teleduino service, as shown in Table 21-1.
Table 21-1: Teleduino Status Blink Codes
Number of blinks | Message |
1 | Initializing |
2 | Starting network connection |
3 | Connecting to the Teleduino server |
4 | Authentication successful |
5 | Session already exists |
6 | Invalid or unauthorized key |
10 | Connection dropped |
If you see five blinks, then another Arduino is already programmed with your key and connected to the Teleduino server. At 10 blinks, you should check your hardware and internet connections. Once the Arduino has connected, it should blink once every 5 seconds or so. Because the status LED is controlled by digital pin 8, you can’t use that pin for any other purpose while you’re using Teleduino.
To control your Teleduino remotely, you can use any device with a web browser. However, you first need to set the mode for each digital pin you wish to control. The command to control the Arduino is sent by entering a URL that you create:
http://us01.proxy.teleduino.org/api/1.0/328.php?k={YOURKEY}&r=definePinMode&pin=<X>&mode=<Y>
You’ll need to change three parameters in the URL. First, replace {
YOURKEY}
with the long alphanumeric key you received from the Teleduino site. Next, replace <
X>
with the digital pin number you want to control. Third, change the <
Y>
to 1
to set up the digital pin as an output.
Now you can control the digital pin remotely. The command to do this is:
http://us01.proxy.teleduino.org/api/1.0/328.php?k={YOURKEY}
&r=setDigitalOutput&pin=<X>&output=<S>
Again, you’ll need to change three parameters in the URL. First, replace {
YOURKEY}
with the long alphanumeric key you received from the Teleduino site. Next, replace <
X>
with the digital pin number you want to control. Third, change the <
S>
to 0
for low or 1
for high to alter the digital output. For example, to turn digital pin 7 to high, you would enter:
http://us01.proxy.teleduino.org/api/1.0/328.php?k={YOURKEY}&r=setDigitalOutput&pin=7&output=1
After the command succeeds, you should see something like the following in your web browser:
{"status":200,"message":"OK","response"
{"result":0,"time":0.22814512252808,"values":[]}}
If the command fails, you should see an error message like this:
{"status":403,"message":"Key is offline or invalid.","response":[]}
You can send commands to change the digital pins to high or low by modifying the URL.
If a digital pin is capable of pulse-width modulation (PWM), as described in Chapter 3, you can also control the PWM output from a pin using:
http://us01.proxy.teleduino.org/api/1.0/328.php?k={YOURKEY}&r=setPwmOutput&pin=<X>&output=<Y>
where <
X>
is the digital output pin and <
Y>
is the PWM level, between 0 and 255.
After you have created the URLs for your project, bookmark them in your browser or create a local web page with the required links as buttons. For example, you might have a URL bookmarked to set digital pin 7 to high and another bookmarked to set it back to low.
In some situations, the status of your Arduino outputs could be critical. As a fail-safe in case your Arduino resets itself due to a power outage or other interruption, set the default state for the digital pins. With your project connected to the Teleduino service, visit https://www.teleduino.org/tools/manage-presets/. After entering your unique key, you should see a screen of options that allows you to select the mode and value for the digital pins, as shown in Figure 21-8.
Along with easily monitoring your Arduino over the internet and having it send tweets on Twitter, you can control your Arduino projects over the internet without creating any complex sketches, having much networking knowledge, or incurring monthly expenses. This enables you to control the Arduino from almost anywhere and extend the reach of its ability to send data. The three projects in this chapter provide a framework that you can build upon to design your own remote control projects.
The next chapter, which is the last one in the book, shows you how to make your Arduino send and receive commands over a cellular network connection.
44.213.80.203