WiFi Client mode of ESP32 controller

A simple client program is used to access a webpage and displays it on the serial monitor. Retrieving a web page contents sent by a server, to demonstrate basic client’s functionality. Once you are able to retrieve information from a server, you should be able to phrase it and extract specific data you need.
by using the library

#include "WiFi.h"

We should start by connecting the module to an access point to obtain an access to the internet.

while (WiFi.status() != WL_CONNECTED)
 {
 Serial.println("IP address: ");
    Serial.println(WiFi.localIP());
}

Once connected to the network we should connect to the specific server. Web address of this server is declared in host character string. You need to get privateKey at https://thingspeak.com/channels/392874/api_keys

const char* host = "api.thingspeak.com";
const char* privateKey = "....................";

Now we should declare a client that will be contacting the host (server)

  WiFiClient client;

Then connect to the host and check the connection result. Note that 80 that is the standard port number used for web access.

const int httpPort = 80;
    if (!client.connect(host, httpPort)) {
        Serial.println("connection failed");
        return;
    }

If the connection is successful, Then we create a request for URL.

String url = "/update";
  url += "?key=";
  url += privateKey;
  url += "&field1="; // Thingspeak field1
  url += value; // value that need  put to field1
  url += "&status=";
  url += count; // Number of count that transmitted to the thingspeak Server

  Serial.print("Requesting URL: ");
  Serial.println(url);

and we should send a request to the host to provide specific information we need. This is done using the HTTP GET request as in the following lines:

client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");

we can read all the lines of the reply from the server and print them to Serial and print out server’s response:

while(client.available()) {
        String line = client.readStringUntil('\r');
        Serial.print(line);
    }

ThingSpeak requires a user account and a channel to get the private key. Each channel has up to eight data fields, location fields, and a status field. A free account holder can send data every 15 seconds to ThingSpeak.

  1. Sign up for a new account.
  2. Create a channel by selecting Channels > My Channels > New Channel.
  3. Enable Field 1
  4. Enter the value as the Field 1 name.
  5. Name the channel. For example, WiFi Client
  6. Save your channel.
  7. Note the Write API Key on the API Keys tab.

WiFi_client