Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Internet of Things with Arduino Blueprints
Internet of Things with Arduino Blueprints

Internet of Things with Arduino Blueprints: Develop interactive Arduino-based Internet projects with Ethernet and WiFi

Arrow left icon
Profile Icon Seneviratne
Arrow right icon
zł59.99 zł141.99
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3 (3 Ratings)
eBook Oct 2015 210 pages 1st Edition
eBook
zł59.99 zł141.99
Paperback
zł177.99
Subscription
Free Trial
Arrow left icon
Profile Icon Seneviratne
Arrow right icon
zł59.99 zł141.99
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3 (3 Ratings)
eBook Oct 2015 210 pages 1st Edition
eBook
zł59.99 zł141.99
Paperback
zł177.99
Subscription
Free Trial
eBook
zł59.99 zł141.99
Paperback
zł177.99
Subscription
Free Trial

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Table of content icon View table of contents Preview book icon Preview Book

Internet of Things with Arduino Blueprints

Chapter 1. Internet-Controlled PowerSwitch

For many years, people physically interacted with electrical appliances using hardware switches. Now that things have changed, thanks to the advances in technology and hardware, controlling a switch over the Internet without any form of physical interaction has become possible.

In this chapter, we will incrementally build a web server-enabled smart power switch that can be controlled through the Internet with a wired Internet connection. Let's move to Arduino's IoT (Internet of Things).

In this chapter, you will do the following:

  • Learn about Arduino UNO and Arduino Ethernet Shield basics
  • Learn how to connect a PowerSwitch Tail with Arduino UNO
  • Build a simple web server to handle client requests and control the PowerSwitch accordingly
  • Build a simple mains electricity (general purpose alternating current) sensor with 5V DC wall power supply
  • Develop a user friendly UI (User Interface) with HTML (Hyper Text Markup Language) and Metro UI CSS (Cascade Style Sheet)

Getting started

This project consists of a DC (Direct Current) activated relay switch with an embedded web server that can be controlled and monitored through the Internet and the integrated mains electricity sensor that can be used to get the status of the availability of mains electricity. The possible applications are:

  • Controlling electrical devices such as lamp posts, water pumps, gates, doors, and so on, in remote locations
  • Sensing the availability of mains electricity in houses, offices, and factories remotely
  • Detecting whether a door, window, or gate is open or shut

Hardware and software requirements

All the hardware and software requirements are mentioned within each experiment. Most of the hardware used in this project are open source, which allows you to freely learn and hack them to make more creative projects based on the blueprints of this chapter.

Arduino Ethernet Shield

Arduino Ethernet Shield is used to connect your Arduino UNO board to the Internet. It is an open source piece of hardware and is exactly the same size as the Arduino UNO board. The latest version of the Arduino Ethernet Shield is R3 (Revision 3). The official Arduino Ethernet Shield is currently manufactured in Italy and can be ordered through the official Arduino website (https://store.arduino.cc). Also, there are many Arduino Ethernet Shield clones manufactured around the world that may be cheaper than the official Arduino Ethernet Shield. This project is fully tested with a clone of Arduino Ethernet Shield manufactured in China.

Arduino Ethernet Shield

Arduino UNO R3 (Front View)

Arduino Ethernet Shield

Arduino Ethernet Shield R3 (Front View)

Plug your Arduino Ethernet Shield into your Arduino UNO board using wire wrap headers so that it's exactly intact with the pin layout of the Arduino UNO board. The following image shows a stacked Arduino UNO and Arduino Ethernet Shield together:

Arduino Ethernet Shield

Arduino Ethernet Shield R3 (top) is stacked with Arduino UNO R3 (bottom) (Front View)

Arduino Ethernet Shield consists of an Ethernet controller chip—WIZnet W5100—the only proprietary hardware used with the shield. The WIZnet W5100 includes a fully hardwired TCP/IP stack, integrated Ethernet MAC (Media Access Control), and PHY (Physical Layer).

The hardwired TCP/IP stack supports the following protocols:

  • TCP (Transport Control Protocol)
  • UDP (User Datagram Protocol)
  • IPv4 (Internet Protocol Version 4)
  • ICMP (Internet Control Message Protocol)
  • ARP (Address Resolution Protocol)
  • IGMP (Internet Group Management Protocol)
  • PPPoE (Point-to-Point Protocol over Ethernet)

The WIZnet W5100 Ethernet controller chip also simplifies the Internet connectivity without using an operating system.

Arduino Ethernet Shield

The WIZnet W5100 Ethernet controller (Top View)

Throughout this chapter, we will only work with TCP and IPv4 protocols.

The Arduino UNO board communicates with the Arduino Ethernet Shield using digital pins 10, 11, 12, and 13. Therefore, we will not use these pins in our projects to make any external connections. Also, digital pin 4 is used to select the SD card that is installed on the Arduino Ethernet Shield, and digital pin 10 is used to select the Ethernet controller chip. This is called SS (Slave Select) because the Arduino Ethernet Shield is acting as the slave and the Arduino UNO board is acting as the master.

However, if you want to disable the SD card and use digital pin 4, or disable the Ethernet controller chip and use digital pin 10 with your projects, use the following code snippets inside the setup() function:

  1. To disable the SD card:
    pinMode(4,OUTPUT);
    digitalWrite(4, HIGH);
  2. To disable the Ethernet Controller chip:
    pinMode(10,OUTPUT);
    digitalWrite(10, HIGH);

The Arduino Ethernet board

The Arduino Ethernet board is a new version of the Arduino development board with the WIZnet Ethernet controller built into the same board. The USB to serial driver is removed from the board to keep the board size the same as Arduino UNO and so that it can be stacked with any Arduino UNO compatible shields on it.

You need an FTDI cable compatible with 5V to connect and program your Arduino Ethernet board with a computer.

The Arduino Ethernet board

The Arduino Ethernet board (Front View)

You can visit the following links to get more information about the Arduino Ethernet board and FTDI cable:

You can build all the projects that are explained within this chapter and other chapters throughout the book with the Arduino Ethernet board using the same pin layout.

Connecting Arduino Ethernet Shield to the Internet

To connect your Ethernet shield to the Internet, you require the following hardware:

Use the following steps to make connections between each hardware component:

  1. Plug your Ethernet shield into your Arduino board using soldered wire wrap headers:
    Connecting Arduino Ethernet Shield to the Internet

    Fritzing representation of Arduino and Ethernet shield stack

  2. Get the Ethernet cable and connect one end to the Ethernet jack of the Arduino Ethernet Shield.
    Connecting Arduino Ethernet Shield to the Internet

    One end of the Ethernet cable is connected to the Arduino Ethernet board

  3. Connect the other end of the Ethernet cable to the Ethernet jack of the network router or switch.
    Connecting Arduino Ethernet Shield to the Internet

    The other end of the Ethernet cable is connected to the router/switch

  4. Connect the 9VDC wall adapter power supply to the DC barrel connector of the Arduino board.
  5. Use the USB A-to-B cable to connect your Arduino board to the computer. Connect the type A plug end to the computer and the type B plug end to the Arduino board.
    Connecting Arduino Ethernet Shield to the Internet

    One end of the Ethernet cable is connected to the Ethernet shield (top) and the power connector and USB cable are connected to the Arduino board (bottom) Image courtesy of SparkFun Electronics (https://www.sparkfun.com)

Testing your Arduino Ethernet Shield

To test you Arduino Ethernet Shield, follow these steps:

  1. Open your Arduino IDE and navigate to File | Examples | Ethernet | WebServer:
    Testing your Arduino Ethernet Shield
  2. The sample sketch WebServer will open in a new Arduino IDE:
    Testing your Arduino Ethernet Shield
  3. You can also paste the code from the sketch named B04844_01_01.ino from the code folder of this chapter. The following header files should be included for serial communication and Ethernet communication in the beginning of the sketch:
    #include <SPI.h> //initiates Serial Peripheral Interface
    #include <Ethernet.h> //initiates Arduino Ethernet library
  4. Replace the MAC address with your Ethernet shield's MAC address if you know it. You can find the printed sticker of the MAC address affixed to the back of your Ethernet shield. (Some clones of Arduino Ethernet Shield don't ship with a MAC address affixed on them). If you don't know the MAC address of your Arduino Ethernet Shield, use the one mentioned in the sample code or replace it with a random one. But don't use network devices with the same MAC address on your network; it will cause conflicts and your Ethernet shield will not function correctly. (Read Finding the MAC address and obtaining a valid IP address for more information on MAC addresses).
    byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
  5. Replace the IP address with a static IP in your local network IP range. (Read the Finding the MAC address and obtaining a valid IP address section for selecting a valid IP address).
    IPAddress ip(192, 168, 1, 177);
  6. Then, create an instance of the Arduino Ethernet Server library and assign port number 80 to listen to incoming HTTP requests.
    EthernetServer server(80);
  7. Inside the setup() function, open the serial communications and wait for the port to open. The computer will communicate with Arduino at a speed of 9600 bps.
    Serial.begin(9600);
  8. The following code block will start the Ethernet connection by using the MAC address and IP address (we have assigned a static IP address) of the Arduino Ethernet Shield and start the server. Then it will print the IP address of the server on Arduino Serial Monitor using Ethernet.localIP():
    Ethernet.begin(mac, ip);
    server.begin();
    Serial.print("server is at ");
    Serial.println(Ethernet.localIP());
  9. Inside the loop() function, the server will listen for incoming clients.
    EthernetClient client = server.available();
  10. If a client is available, the server will connect with the client and read the incoming HTTP request. Then, reply to the client by the standard HTTP response header. The output can be added to the response header using the EthernetClient class's println() method:
      if (client) {
        Serial.println("new client");
        // an http request ends with a blank line
        boolean currentLineIsBlank = true;
        while (client.connected()) {
          if (client.available()) {
            char c = client.read();
            Serial.write(c);
            // if you've gotten to the end of the line (received a newline
            // character) and the line is blank, the http request has ended,
            // so you can send a reply
            if (c == '\n' && currentLineIsBlank) {
              // send a standard http response header
              client.println("HTTP/1.1 200 OK");
              client.println("Content-Type: text/html");
              client.println("Connection: close");  // the connection will be closed after completion of the response
              client.println("Refresh: 5");  // refresh the page automatically every 5 sec
              client.println();
              client.println("<!DOCTYPE HTML>");
              client.println("<html>");
              // output the value of each analog input pin
              for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
                int sensorReading = analogRead(analogChannel);
                client.print("analog input ");
                client.print(analogChannel);
                client.print(" is ");
                client.print(sensorReading);
                client.println("<br />");
              }
              client.println("</html>");
              break;
            }
            if (c == '\n') {
              // you're starting a new line
              currentLineIsBlank = true;
            }
            else if (c != '\r') {
              // you've gotten a character on the current line
              currentLineIsBlank = false;
            }
          }
        }
        // give the web browser time to receive the data
        delay(1);
  11. Finally, close the connection from the client using the EthernetClient class's stop() method:
    client.stop();
    Serial.println("client disconnected");
  12. Verify the sketch by clicking on the Verify button located in the toolbar.
  13. On the menu bar, select the board by navigating to Tools | Board | Arduino UNO. If you are using an Arduino Ethernet board, select Tools | Board | Arduino Ethernet.
  14. On the menu bar, select the COM port by navigating to Tools | Port and then selecting the port number.
  15. Upload the sketch into your Arduino UNO board by clicking on the Upload button located in the toolbar.
  16. Open your Internet browser (such as Google Chrome, Mozilla Firefox, or Microsoft Internet Explorer) and type the IP address (http://192.168.1.177/) assigned to your Arduino Ethernet Shield in the sketch (in Step 4), and hit the Enter key.
  17. The web browser will display analog input values (impedance) of all the six analog input pins (A0-A5). The browser will refresh every 5 seconds with the new values. Use following code to change the automatic refresh time in seconds:
    client.println("Refresh: 5");
    Testing your Arduino Ethernet Shield

    Output for Arduino Ethernet board: Analog input values are displaying on the Google Chrome browser, refreshing every 5 seconds

    Testing your Arduino Ethernet Shield

    Output for Arduino UNO + Arduino Ethernet Shield: Analog input values are displaying on the Google Chrome browser, refreshing every 5 seconds

    Testing your Arduino Ethernet Shield

    Arduino Serial Monitor prints the static IP address of Arduino Ethernet Shield

  18. To make your sketch more stable and to ensure that it does not hang, you can do one of the following:
    • Remove the SD card from the slot.
    • Add the following two lines inside your setup() function:
      pinMode(4,OUTPUT);
      digitalWrite(4, HIGH);

Now you can be assured that your Arduino Ethernet Shield is working properly and can be accessed through the Internet.

Selecting a PowerSwitch Tail

PowerSwitch Tail has a built-in AC relay that is activated between 3-12 VDC. This is designed to easily integrate with many microcontroller platforms, such as Arduino, Raspberry Pi, BeagleBone, and so on. Usually, Arduino digital output provides 5VDC that allows it to activate the AC (Alternative Current) relay inside the PowerSwitch Tail. Using a PowerSwitch Tail with your microcontroller projects provides safety since it distinguishes between AC and DC circuitry by using an optocoupler which is an optically activated switch.

PowerSwitch Tail ships in several variants. At the time of writing this book, the product website lists various PowerSwitch Tails, assembled and in kit form, that can be used with this project.

To build this project, we will use a 240V AC PowerSwitch Tail that can be purchased as a kit and assembled.

PN PSSRKT-240

Refer to http://www.powerswitchtail.com/Pages/PowerSwitchTail240vackit.aspx.

PN PSSRKT-240

PN PSSRKT-240 Normally Open (NO) version—240V AC Image courtesy of PowerSwitchTail.com, LLC (http://www.powerswitchtail.com)

Here, we will not cover the assembly instructions about the PN PSSRKT-240 kit. However, you can find the assembly instructions at http://www.powerswitchtail.com/Documents/PSSRTK%20Instructions.pdf.

The following image shows an assembled PN PSSRKT-240 kit:

PN PSSRKT-240

PN PSSRKT-240 Normally Open (NO) version—240V Image courtesy of PowerSwitchTail.com, LLC (http://www.powerswitchtail.com)

PN PSSRKT-240

PN PSSRKT-240 Normally Open (NO) version—240V Image courtesy of PowerSwitchTail.com, LLC (http://www.powerswitchtail.com)

If you are in a country that has a 120V AC connection, you can purchase an assembled version of the PowerSwitch Tail.

PN80135

Refer to http://www.powerswitchtail.com/Pages/default.aspx.

PN80135

PN80135 Normally Open (NO) version—120V AC (left-hand side plug for LOAD and right-hand side plug for LINE) Image courtesy of SparkFun Electronics (https://www.sparkfun.com)

Wiring PowerSwitch Tail with Arduino Ethernet Shield

Wiring the PowerSwitch Tail with Arduino is very easy. Use any size of wire range between gauge #14-30 AWG to make the connection between Arduino and PowerSwitch Tail.

PowerSwitch Tail has a terminal block with three terminals. Use a small flat screwdriver and turn the screws CCW (Counter Clock Wise) to open the terminal contacts.

With the Arduino Ethernet Shield mounted on the Arduino UNO board, do the following:

  1. Use the red hookup wire to connect the positive terminal of the PowerSwitch Tail to digital pin 5 on your Arduino.
  2. Use the black hookup wire to connect the negative terminal of the PowerSwitch Tail to the GND pin on your Arduino.
  3. Connect the wall adapter power supply (9V DC 650mA) to the DC power jack on your Arduino board. The ground terminal is connected internally to the AC-side electrical safety ground (the green conductor) and can be used if needed.
    Wiring PowerSwitch Tail with Arduino Ethernet Shield

    Two wires from Arduino connected to the PowerSwitch Tail Image courtesy of PowerSwitchTail.com, LLC (http://www.powerswitchtail.com)

    Wiring PowerSwitch Tail with Arduino Ethernet Shield

    PowerSwitch Tail connected to the Ethernet Shield—Fritzing representation

    Wiring PowerSwitch Tail with Arduino Ethernet Shield

    PowerSwitch Tail connected to the Ethernet Shield—Schematic

Turning PowerSwitch Tail into a simple web server

In this topic, we will look into how to convert our Arduino connected PowerSwitch Tail into a simple web server to handle client requests, such as the following:

  • Turn ON the PowerSwitch Tail
  • Turn OFF the PowerSwitch Tail

And other useful information such as:

  • Display the current status of the PowerSwitch Tail
  • Display the presence or absence of the main electrical power

What is a web server?

A web server is a piece of software which serves to connected clients. An Arduino web server uses HTTP on top of TCP and UDP. But remember, the Arduino web server can't be used as a replacement for any web server software running on a computer because of the lack of processing power and limited number of multiple client connectivity.

A step-by-step process for building a web-based control panel

In this section ,you will learn how to build a web-based control panel for controlling the PowerSwitch Tail through the Internet.

We will use the Arduino programming language and HTML that's running on the Arduino web server. Later, we will add HTML radio button controls to control the power switch.

Handling client requests by HTTP GET

Using the HTTP GET method, you can send a query string to the server along with the URL.

The query string consists of a name/value pair. The query string is appended to the end of the URL and the syntax is http://example.com?name1=value1.

Also, you can add more name/value pairs to the URL by separating them with the & character, as shown in the following example:

http://example.com?name1=value1&name2=value2.

So, our Arduino web server can actuate the PowerSwitch Tail using the following URLs:

  • To turn ON the PowerSwitch Tail: http://192.168.1.177/?switch=1
  • To turn OFF the PowerSwitch Tail: http://192.168.1.177/?switch=0

The following sketch can be used by the web server to read the incoming client requests, process them, and actuate the relay inside the PowerSwitch Tail:

  1. Open your Arduino IDE and type or paste the code from the B04844_01_02.ino sketch.
  2. In the sketch, replace the MAC address with your Arduino Ethernet Shield's MAC address:
    byte mac[] = { 0x90, 0xA2, 0xDA, 0x0B, 0x00 and 0xDD };
  3. Replace the IP address with an IP valid static IP address in the range of your local network:
    IPAddress ip(192,168,1,177);
  4. If you want the IP address dynamically assigned by the DHCP to the Arduino Ethernet Shield, do the following:
    1. Comment the following line in the code:
      //IPAddress ip(192,168,1,177);
    2. Comment the following line in the code:
      //Ethernet.begin(mac, ip);
    3. Uncomment the following line in the code:
      Ethernet.begin(mac);
  5. The following two lines will read the incoming HTTP request from the client using the EthernetClient class's read() method and store it in a string variable http_Request:
    char c = client.read();
    http_Request += c;
  6. The following code snippet will check whether the HTTP request string contains the query string that is sent to the URL. If found, it will turn on or off the PowerSwitch Tail according to the name/value pair logically checked inside the sketch.

    The indexOf() function can be used to search for the string within another string. If it finds the string switch=1 inside the HTTP request string, the Arduino board will turn digital pin 5 to the HIGH state and turn on the PowerSwitch Tail. If it finds the text switch=0, the Arduino board will turn the digital pin 5 to the LOW state and turn off the PowerSwitch Tail.

    if (httpRequest.indexOf("GET /?switch=0 HTTP/1.1") > -1) {
                relayStatus = 0;
                digitalWrite(5, LOW);
                Serial.println("Switch is Off");
              } else if (httpRequest.indexOf("GET /?switch=1 HTTP/1.1") > -1) {
                relayStatus = 1;
                digitalWrite(5, HIGH);
                Serial.println("Switch is On");
              }
  7. Select the correct Arduino board and COM port from the menu bar.
  8. Verify and upload the sketch into your Arduino UNO board (or the Arduino Ethernet board).
  9. If you have to choose DHCP to assign an IP address to your Arduino Ethernet Shield, it will be displayed on the Arduino Serial Monitor. On the menu bar, go to Tools | Serial Monitor. The Arduino Serial Monitor window will be displayed with the IP address assigned by the DHCP.
    Handling client requests by HTTP GET

    The IP address assigned by the DHCP

  10. Plug the PowerSwitch Tail LINE side into the wall power socket and connect the lamp into the LOAD side of the PowerSwitch Tail. Make sure that the lamp switch is in the ON position and all the switches of the wall power socket are in the ON position.
  11. Open your Internet browser and type the IP address of your Arduino Ethernet Shield with HTTP protocol. For our example it is http://192.168.1.177. Then hit the Enter key on your keyboard.
  12. The web browser sends an HTTP request to the Arduino web server and the web server returns the processed web content to the web browser. The following screen capture displays the output in the web browser.
  13. Type http://192.168.1.177/?switch=1 and hit the Enter key. The lamp will turn on.
  14. Type http://192.168.1.177/?switch=0 and hit the Enter key. The lamp will turn off.
  15. If you have connected your Arduino Ethernet Shield to your home wireless network, you can test your PowerSwitch Tail using your Wi-Fi connected smartphone as well. If you have the idea to add port forwarding to your router, you can then control your switch from anywhere in the world. Explaining about port forwarding is out of scope of this book.
    Handling client requests by HTTP GET

    Electric lamp controlled by PowerSwitch Tail

    Handling client requests by HTTP GET

    PowerSwitch Tail control panel accessed by Google Chrome browser

Sensing the availability of mains electricity

You can sense the availability of mains electricity in your home and read the status before actuating the PowerSwitch Tail.

You will need the following hardware to build the sensor:

Follow the next steps to attach the sensor to the Arduino Ethernet Shield:

  1. Connect the positive wire of the 5V DC wall adapter power supply to the Ethernet shield digital pin 2.
  2. Connect the negative wire of the wall adapter power supply to the Ethernet shield GND pin.
  3. Connect the 10 kilo ohm resistor between the Ethernet shield digital pin 2 and the GND pin.
  4. Plug the wall adapter power supply into the wall.
    Sensing the availability of mains electricity

    A wiring diagram

    Sensing the availability of mains electricity

    Schematic

Testing the mains electricity sensor

The previous sketch is modified to check the availability of the mains electricity and operate PowerSwitch Tail accordingly. The 5V DC wall adapter power supply plugged into the wall keeps the Arduino digital pin 2 in the HIGH state if mains electricity is available. If mains electricity is not available, the digital pin 2 switches to the LOW state.

  1. Open your Arduino IDE and paste the code from the sketch named B04844_01_03.ino from the code folder of this chapter.
  2. Power up your Arduino Ethernet Shield with 9V battery pack so that it will work even without mains electricity.
  3. The Arduino digital pin 2 is in its HIGH state if mains electricity is available. The hasElectricity boolean variable holds the state of availability of the electricity.
  4. If only the mains electricity is available, the PowerSwitch Tail can be turned ON. If not, the PowerSwitch Tail is already in its OFF state.

Building a user-friendly web user interface

The following Arduino sketch adds two radio buttons to the web page so the user can easily control the switch without typing the URL with the query string into the address bar of the web browser. The radio buttons will dynamically build the URL with the query string depending on the user selection and send it to the Arduino web server with the HTTP request.

  1. Open your Arduino IDE and paste the code from the sketch named B04844_01_04.ino from the code folder of this chapter.
  2. Replace the IP address with a new IP address in your local area network's IP address range.
    IPAddress ip(192,168,1,177);
  3. Verify and upload the sketch on your Arduino UNO board.
  4. Open your web browser and type your Arduino Ethernet Shield's IP address into the address bar and hit the Enter key.
  5. The following code snippet will submit your radio button selection to the Arduino web sever as an HTTP request using the HTTP GET method. The radio button group is rendered inside the <form method="get"></form> tags.
              client.println("<form method=\"get\">");
              if (httpRequest.indexOf("GET /?switch=0 HTTP/1.1") > -1) {
                relayStatus = 0;
                digitalWrite(9, LOW);
                Serial.println("Off Clicked");
              } else if (httpRequest.indexOf("GET /?switch=1 HTTP/1.1") > -1) {
                relayStatus = 1;
                digitalWrite(9, HIGH);
                Serial.println("On Clicked");
              }
    
              if (relayStatus) {
                client.println("<input type=\"radio\" name=\"switch\" value=\"1\" checked>ON");
                client.println("<input type=\"radio\" name=\"switch\" value=\"0\" onclick=\"submit();\" >OFF");
              }
              else {
                client.println("<input type=\"radio\" name=\"switch\" value=\"1\" onclick=\"submit();\" >ON");
                client.println("<input type=\"radio\" name=\"switch\" value=\"0\" checked>OFF");
              }
              client.println("</form>");

Also, depending on the radio button selection, the browser will re-render the radio buttons using the server response to reflect the current status of the PowerSwitch Tail.

Adding a Cascade Style Sheet to the web user interface

Cascade Style Sheet (CSS) defines how HTML elements are to be displayed. Metro UI CSS (https://metroui.org.ua/) is a cascade style sheet that can be used to apply Windows 8-like style to your HTML elements.

The following Arduino sketch applies Windows 8-like style to the radio button group:

  1. Open your Arduino IDE and paste the code from the sketch named B04844_01_05.ino from the code folder of this chapter.
  2. Between the <head></head> tags we have first included the JQuery library which consists of a rich set of JavaScript functions:
    client.println("<script src=\"https://metroui.org.ua/js/jquery-2.1.3.min.js\"></script>");
  3. Then, we have included metro.js and metro.css from the https://metroui.org.ua website:
    client.println("<script src=\"https://metroui.org.ua/js/metro.js\"></script>");
    client.println("<link rel=\"stylesheet\" href=\"https://metroui.org.ua/css/metro.css\">");

Upload the sketch on your Arduino board and play with the new look and feel. You can modify the other HTML elements and even use the radio buttons by referring to the MetroUI CSS website documentation at https://metroui.org.ua/.

Adding a Cascade Style Sheet to the web user interface

MetroUI CSS style applied to radio buttons

Finding the MAC address and obtaining a valid IP address

To work with this project, you must know your Arduino Ethernet Shield's MAC address and IP address to communicate properly over the Internet.

Finding the MAC address

Current Arduino Ethernet Shields come with a dedicated and uniquely assigned 48-bit MAC (Media Access Control) address which is printed on the sticker. Write down your Ethernet shield's MAC address so you can refer to it later. The following image shows an Ethernet shield with the MAC address of 90-A2-DA-0D-E2-CD:

Finding the MAC address

You can rewrite your Arduino Ethernet Shield's MAC address using hexadecimal notations, as in 0x90, 0xA2, 0xDA, 0x0D, 0xE2 and 0xCD, with the leading 0x notation recognized by C compilers (remember that the Arduino programming language is based on C) and assembly languages.

If not present, you can use one that does not conflict with your network. For example:

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

Obtaining an IP address

You can assign an IP address to your Arduino Ethernet Shield by one of the following methods:

  • Using the network router or switch to assign a static IP address to your Ethernet shield.
  • Using DHCP (Dynamic Host Configuration Protocol) to dynamically assign an IP address to your Ethernet shield. In this chapter, we will only discuss how to assign an IP address using DHCP.

The network devices we will use for this experiment are the following:

  • Huawei E517s-920 4G Wi-Fi Router
  • DELL computer with Windows 8.1 installed and Wi-Fi connected
  • Nokia Lumia phone with Windows 8.1 installed and Wi-Fi connected
  • Arduino Ethernet Shield connected to the Wi-Fi router's LAN port using an Ethernet cable

Assigning a static IP address

The following steps will explain how to determine your network IP address range with a Windows 8.1 installed computer, and select a valid static IP address.

  1. Open Network and Sharing Center in Control Panel:
    Assigning a static IP address
  2. Click on Connections. The Connection Status dialog box will appear, as shown here:
    Assigning a static IP address
  3. Click on the Details… button. The Network Connection Details dialog box will appear, as shown in the following screenshot:
    Assigning a static IP address
  4. The IPv4 address assigned to the Windows 8.1 computer by the Wireless router is 192.168.1.2. The IPv4 subnet mask is 255.255.255.0. So, the IP address range should be 192.168.1.0 to 192.168.1.255.
  5. The Wi-Fi network used in this example currently has two devices connected, that is, a Windows 8.1 computer, and a Windows phone. After logging in to the wireless router product information page, under the device list, all the IP addresses currently assigned by the router to the connected devices can be seen, as shown here:
    Assigning a static IP address
  6. Now, we can choose any address except 192.168.1.1, 192.168.1.2, and 192.168.1.3.
  7. Let's assign 192.168.1.177 to the Arduino Ethernet Shield as a static IP address using the following sketch. Upload the following sketch into your Arduino board and open the Serial Monitor to verify the static IP address assigned.
  8. Open your Arduino IDE and type or paste the following code from the sketch named B04844_01_06.ino from the code folder of this chapter.
    #include <SPI.h>
    #include <Ethernet.h>
    
    byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
    byte ip[] = { 192, 168, 1, 177 };
    
    EthernetServer server(80);
    
    void setup()
    {
      Serial.begin(9600);
        
      Ethernet.begin(mac, ip);
      server.begin();
      Serial.print("IP Address: ");
      Serial.println(Ethernet.localIP());
    
    }
    
    void loop () {}
    Assigning a static IP address

    A static IP address

Obtaining an IP address using DHCP

The DHCP can be used to automatically assign a valid IP address to the Arduino Ethernet Shield. The only address you need is the MAC address of the Ethernet shield. Pass the MAC address as a parameter to the Ethernet.begin() method.

Upload the following Arduino sketch to your Arduino board, and open the Arduino Serial Monitor to see the auto-assigned IP address by the DHCP. Use this IP address to access your Ethernet shield through the Internet. Remember, this IP address may be changed at the next start up or reset.

Open your Arduino IDE and type or paste the following code from the sketch named B04844_01_07.ino from the code folder of this chapter:

#include <SPI.h>
#include <Ethernet.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };  

EthernetServer server(80);

void setup()
{
  Serial.begin(9600);
    
  Ethernet.begin(mac);
  server.begin();
  Serial.print("IP Address: ");
  Serial.println(Ethernet.localIP());

}

void loop () {}
Obtaining an IP address using DHCP

DHCP assigned IP address

Summary

In this chapter, you have gained a lot, and built your first Arduino Internet of Things (IoT) project, an internet controlled power switch, which is very smart. Using your creative knowledge, you can take this project to a more advanced level by adding many more functionalities, such as an LCD screen to the switch to display the current status and received user requests, or a feedback LED to show different statuses, and so on.

In the next chapter, you will learn how to build a Wi-Fi signal strength notification system using Arduino wearable and Internet of Things. Use the basic knowledge about Arduino IoT gained from this chapter to build the next project more successfully. Always be creative!

Left arrow icon Right arrow icon

Description

Arduino is a small single-chip computer board that can be used for a wide variety of creative hardware projects. The hardware consists of a simple microcontroller, board, and chipset. It comes with a Java-based IDE to allow creators to program the board. Arduino is the ideal open hardware platform for experimenting with the world of the Internet of Things. This credit card sized Arduino board can be used via the Internet to make more useful and interactive Internet of things projects. Internet of Things with Arduino Blueprints is a project-based book that begins with projects based on IoT and cloud computing concepts. This book covers up to eight projects that will allow devices to communicate with each other, access information over the Internet, store and retrieve data, and interact with users—creating smart, pervasive, and always-connected environments. It explains how wired and wireless Internet connections can be used with projects and the use of various sensors and actuators. The main aim of this book is to teach you how Arduino can be used for Internet-related projects so that users are able to control actuators, gather data from various kinds of sensors, and send and receive data wirelessly across HTTP and TCP protocols. Finally, you can use these projects as blueprints for many other IoT projects and put them to good use. By the end of the book, you will be an expert in the use of IoT with Arduino to develop a set of projects that can relate very well to IoT applications in the real world.

What you will learn

  • Make a powerful Internet controlled relay with an embedded web server to monitor and control your home electrical appliances
  • Build a portable WiFi signal strength sensor to give haptic feedback about signal strength to the user
  • Measure water flow speed and volume with liquid flow sensors and record realtime readings
  • Secure your home with motionactivated Arduino security cameras and upload images to the cloud
  • Implement realtime data logging of a solar panel voltage with Arduino cloud connectors
  • Track locations with GPS and upload location data to the cloud
  • Control a garage door light with your Twitter feed
  • Control infrared enabled devices with IR remote and Arduino

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Oct 27, 2015
Length: 210 pages
Edition : 1st
Language : English
ISBN-13 : 9781785281914
Vendor :
Arduino
Category :
Concepts :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want

Product Details

Publication date : Oct 27, 2015
Length: 210 pages
Edition : 1st
Language : English
ISBN-13 : 9781785281914
Vendor :
Arduino
Category :
Concepts :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just zł20 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just zł20 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 557.97
Internet of Things with Arduino Blueprints
zł177.99
Building Wireless Sensor Networks Using Arduino
zł181.99
Arduino By Example
zł197.99
Total 557.97 Stars icon

Table of Contents

9 Chapters
1. Internet-Controlled PowerSwitch Chevron down icon Chevron up icon
2. Wi-Fi Signal Strength Reader and Haptic Feedback Chevron down icon Chevron up icon
3. Internet-Connected Smart Water Meter Chevron down icon Chevron up icon
4. Arduino Security Camera with Motion Detection Chevron down icon Chevron up icon
5. Solar Panel Voltage Logging with NearBus Cloud Connector and Xively Chevron down icon Chevron up icon
6. GPS Location Tracker with Temboo, Twilio, and Google Maps Chevron down icon Chevron up icon
7. Tweet-a-Light – Twitter-Enabled Electric Light Chevron down icon Chevron up icon
8. Controlling Infrared Devices Using IR Remote Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
(3 Ratings)
5 star 0%
4 star 66.7%
3 star 0%
2 star 0%
1 star 33.3%
GreenBeanieGuy Dec 05, 2015
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
This book is an excellent project book for intermediate to advanced Arduino users. The projects are clear, well-documented, and include all relevant code (downloadable separately). My principle reason for not giving this five stars is due to the fairly extensive BOM that you will need to build these projects.There are numerous somewhat specialized components required (Power SwitchTail, Arduino WiFi and Ethernet Shields, Adafruit Haptic Controller, liquid flow sensor, Hitachi HD44780 Compatible LCD, etc.), that while relatively easy to source, do represent quite a bit of investment in time and money. The required components are listed as prerequisites, with links to the product URL. It would have been nice to have everything presented as a BOM, with then-current cost and substitutes.Overall it's an excellent book of useful IoT projects for the Arduino.
Amazon Verified review Amazon
Francis B. Dec 09, 2015
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
I purchased this item directly from the publisher (which gives access to a nicely formatted PDF book). In terms of content, the book offers an impressive collection of hands-on projects, which are very useful for understanding how the Arduino can be used in networking applications. Note that the book is not a beginner's guide, in fact assuming a fair bit of experience in electronics and network programming (however, there are other books, also from Packt, that fulfill this purpose). I am docking one star for the following two reasons. First, the book currently requires specific items to be used, which may not always be available. Perhaps providing guidelines on selecting alternative parts should be more appropriate. Second, Windows is assumed to be the operating system used, which means OSX or Linux users will at times have to cope with surprises and adjustments in the instructions. Perhaps an Appendix detailing modifications needed for other operating systems will be helpful.
Amazon Verified review Amazon
Bob Jan 16, 2020
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
Expensive. Didn't like the writing style at all. Lots of handy refrences and very little explanation. Look elsewhere if you want to understand the subject.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.