Book Image

ESP8266 Internet of Things Cookbook

By : Marco Schwartz
Book Image

ESP8266 Internet of Things Cookbook

By: Marco Schwartz

Overview of this book

The ESP8266 Wi-Fi Module is a self contained System on Chip (SOC) with an integrated TCP/IP protocol stack and can give any microcontroller access to your Wi-Fi network. It is capable of either hosting an application or offloading all Wi-Fi networking functions from another application processor. This book contains practical recipes that will help you master all ESP8266 functionalities. You will start by configuring and customizing the chip in line with your requirements. Then you will focus on core topics such as on-board processing, sensors, GPIOs, programming, networking, integration with external components, and so on. We will also teach you how to leverage Arduino using the ESP8266 and you'll learn about its libraries, file system, OTA updates, and so on. The book also provide recipes on web servers, testing, connecting with the cloud, and troubleshooting techniques. Programming aspects include MicroPython and how to leverage it to get started with the ESP8266. Towards the end, we will use these concepts and create an interesting project (IOT). By the end of the book, readers will be proficient enough to use the ESP8266 board efficiently.
Table of Contents (15 chapters)
ESP8266 Internet of Things Cookbook
Credits
About the Author
About the Reviewer
www.PacktPub.com
Customer Feedback
Preface
Index

Connecting the ESP8266 to a cloud server


In this recipe, we will connect the ESP8266 to the Internet and send data to a cloud server. The cloud server we will be sending data to is dweet.io. The data we send to dweet.io will be used later in this book, so ensure that you execute this section successfully.

Getting ready

As in the previous recipe, we won't need any extra components here. All we need to do is ensure that the ESP8266 is connected to the computer.

How to do it…

To accomplish this, follow these steps:

  1. We will connect the ESP8266 to a local Wi-Fi network that has an active Internet connection.

  2. Once the connection is successful, we will send a GET request to the cloud server and then display the reply that the server sends back to the ESP8266 board:

    // Libraries
    #include <ESP8266WiFi.h>
  3. Enter the SSID and password:

    // SSID
    const char* ssid     = "your-ssid";
    const char* password = "your-password";
  4. Store the hostname of the cloud server:

    // Host
    const char* host = "dweet.io";
  5. Configure the SSID and password of the Wi-Fi network and connect the ESP8266 to the Wi-Fi network:

    void setup() {
    
      // Serial
      Serial.begin(115200);
      delay(10);
    
      // We start by connecting to a WiFi network
      Serial.println();
      Serial.println();
      Serial.print("Connecting to ");
      Serial.println(ssid);
      
      WiFi.begin(ssid, password);
      
      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }
    
      Serial.println("");
      Serial.println("WiFi connected");  
      Serial.println("IP address: ");
      Serial.println(WiFi.localIP());
    }
  6. Delay for five seconds and then print the name of the host we are connecting to on the serial monitor:

    void loop() {
      
      delay(5000);
    
      Serial.print("connecting to ");
      Serial.println(host);
  7. Connect to the host server:

      // Use WiFiClient class to create TCP connections
      WiFiClient client;
      const int httpPort = 80;
      if (!client.connect(host, httpPort)) {
        Serial.println("connection failed");
        return;
      }
  8. Formulate the URI for the GET request we will send to the host server:

      // We now create a URI for the request
      String url = "/dweet/for/my-thing-name?value=test";
  9. Send the GET request to the server and check whether the request has been received or if it has timed out:

      // Send request
      Serial.print("Requesting URL: ");
      Serial.println(url);
      
      client.print(String("GET ") + url + " HTTP/1.1\r\n" +
                   "Host: " + host + "\r\n" + 
                   "Connection: close\r\n\r\n");
      unsigned long timeout = millis();
      while (client.available() == 0) {
        if (millis() - timeout > 5000) {
          Serial.println(">>> Client Timeout !");
          client.stop();
          return;
        }
      }
  10. Read incoming data from the host server line by line and display the data on the serial monitor.

  11. Close the connection after all the data has been received from the server:

      // Read all the lines from the answer
      while(client.available()){
        String line = client.readStringUntil('\r');
        Serial.print(line);
      }
    
      // Close connecting
      Serial.println();
      Serial.println("closing connection");
    }
  12. Copy the sketch to your Arduino IDE and change the SSID in the code from your-ssid to the name of your Wi-Fi network and the password from your-password to the password of your Wi-Fi network.

  13. Upload the sketch to your ESP8266 board.

  14. Open the serial monitor so that you can view the incoming data.

The serial monitor should display data, as shown in the following screenshot:

As you can see from the serial monitor, when you send the GET request to dweet.io you receive a reply from the server. The reply is enclosed in curly brackets {}.

How it works…

The program connects to the Wi-Fi network using the provided password and SSID. It then proceeds to connect to the provided cloud/host server using the client.connect() function, and sends the provided URI to the host server using the client.print() function.

Once the data has been successfully sent, the sketch waits for a reply from the server. It does this with the client.available() function, which checks whether there is incoming data from the server. If there is data available, the sketch reads it and displays it on the serial monitor. The process is repeated until the ESP8266 is turned off.

There's more…

Since you have understood how to connect the ESP8266 to a cloud server, see if you can change the sketch so that it connects to the www.google.com host server and searches for the word Arduino. The results from the server should be displayed on the serial monitor.

Tip

Hint: You can check out the following link to see the format for Google GET requests:

https://www.google.com/support/enterprise/static/gsa/docs/admin/72/gsa_doc_set/xml_reference/request_format.html.

See also

You can now continue to the next recipe and look at some of the common issues that you may face when using your ESP8266 and how you can solve them.