Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
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

eBook
€17.99 €26.99
Paperback
€32.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
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
Estimated delivery fee Deliver to Latvia

Premium delivery 7 - 10 business days

€25.95
(Includes tracking information)

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 : 9781785285486
Vendor :
Arduino
Category :
Concepts :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Latvia

Premium delivery 7 - 10 business days

€25.95
(Includes tracking information)

Product Details

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

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.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
€189.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 €5 each
Feature tick icon Exclusive print discounts
€264.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 €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 103.97
Internet of Things with Arduino Blueprints
€32.99
Building Wireless Sensor Networks Using Arduino
€33.99
Arduino By Example
€36.99
Total 103.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

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela