A micro chip which is esp32 can connect to internet through wifi. In the weather station, esp32 requests data to a website called open weather map, and then the website will answer with the weather data. The request is done by a protocal called HTTP GET REQUEST. Let`s dive into the code to see how it is done.
#include <WiFiClient.h>
#include <HTTPClient.h> //
#include <Wire.h> // for arduino I2C connection library, optional
const char* ssid = "";//your wifi ssid
const char* password = "";// wifi password
const String endpoint = ""; // your website url
const String key = ""; // your api key for the open weather map.
const String endpointone = "";
int main();{
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi..");
display.setCursor(0, 2);
display.print(".");
cursorPosition++;
display.display();
}
WiFiClient client;
HTTPClient http;
http.begin(client, endpoint + key); //URLを指定 , define url
int httpCode = http.GET(); //GETリクエストを送信 send get request
return 0;
}
Code explained
Libraries
<WiFiClient.h>
:- This library is part of the Arduino core for ESP32 and ESP8266 boards.
- It provides a way to create and manage TCP/IP connections over a WiFi network.
- The
WiFiClient
class allows your ESP32 or ESP8266 board to connect to a web server or any other TCP/IP-based service. - This library is essential when you need to make HTTP requests or communicate with other devices over a WiFi network.
<HTTPClient.h>
:- This library is also part of the Arduino core for ESP32 and ESP8266 boards.
- It provides a simple and easy-to-use interface for making HTTP requests, such as GET, POST, PUT, and DELETE.
- The
HTTPClient
class allows you to send HTTP requests to web servers and retrieve the responses. - This library simplifies the process of sending and receiving HTTP data, making it easier to interact with web-based services and APIs.
These two libraries work together to enable your ESP32 or ESP8266 board to communicate over a WiFi network and make HTTP requests to web servers or other network-connected devices.
The <WiFiClient.h>
library provides the low-level networking functionality, allowing your board to establish a TCP/IP connection. The <HTTPClient.h>
library then builds on top of this, providing a higher-level interface for sending and receiving HTTP data.
By including these libraries in your code, you can easily create applications that interact with web-based services, fetch data from the internet, or communicate with other devices over a WiFi network.
3. <Wire.h>
- The
Wire.h
library in Arduino is used for I2C communication. I2C (Inter-Integrated Circuit) is a serial communication protocol that allows multiple devices to communicate with each other using just two wires: one for data (SDA) and one for a clock signal (SCL).
WiFi Set up
Set up the basic information about connecting to wifi and also provide URL and API key to access to the website.
const char* ssid = "";//your wifi ssid
const char* password = "";// wifi password
const String endpoint = ""; // your website url
const String key = ""; // your api key for the open weather map.
const String endpointone = "";
- ssid: This variable holds the name of your WiFi network (SSID). You need to replace the empty string
""
with the name of your WiFi network. - password: This variable stores the password for your WiFi network. Replace the empty string
""
with your WiFi password. - endpoint: This variable is intended to store the URL of the API endpoint or website you want to interact with. Replace the empty string
""
with the actual URL. - key: This variable should contain your API key for accessing the OpenWeatherMap API. API keys are used to authenticate your requests to the API service.
“const char*” and “const String” can both store data into a designated character (In this case “ssid, password, endpoint and key”)
They do have minor difference but we will discuss that in another article.
Program Execution
int main();
{
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi..");
display.setCursor(0, 2);
display.print(".");
cursorPosition++;
display.display();
}
int main();
The int main()
function serves as the entry point of the program. In embedded systems, especially those involving microcontrollers like ESP32, this function is crucial for initializing and running the main logic of the program.
WiFi.begin(ssid, password);
This line initiates the connection to a WiFi network. The ssid
represents the name of the WiFi network, and password
is the password for the network. This function call starts the process of connecting the device to the specified WiFi network.
while (WiFi.status() !=WL_CONNECTED);
This while
loop continuously checks the connection status. The WiFi.status()
function returns the current status of the WiFi connection. The loop runs as long as the device is not connected to the WiFi (i.e., the status is not WL_CONNECTED
).
delay(1000);
The delay(1000);
function pauses the execution of the program for 1000 milliseconds (or 1 second). This delay prevents the loop from running too frequently, which would otherwise consume unnecessary processing power.
Serial.println("Connecting to WiFi..");
This line prints the message “Connecting to WiFi..” to the serial monitor. This is useful for debugging and provides a visual indication that the program is attempting to connect to the WiFi network.
display.setCursor(0,2);
This line sets the cursor position on a connected display module. The parameters (0, 2)
specify the column and row positions on the display where the next print action will occur.
display.print(".");
This line prints a dot (“.”) on the display at the current cursor position. It’s a visual indication of the connection attempt, often used to show progress.
cursorPosition++;
This line increments the cursorPosition
variable. Although not defined in the snippet, it’s typically used to keep track of where to print the next dot on the display.
display.display();
This line refreshes the display to show the latest changes. It ensures that any updates made to the display buffer are rendered on the screen.
WiFiClient client;
HTTPClient http;
http.begin(client, endpoint + key); //URLを指定 , define url
int httpCode = http.GET(); //GETリクエストを送信 send get request
return 0;
WiFiClient client
The 'WiFiClient'
object, named ‘client'
in this case, is initialized. This object will handle the low-level communication over WiFi, establishing a connection to the server specified by the URL.
HTTPClient http;
An ‘HTTPClient'
object, named ‘http'
, is initialized. This object will manage the details of the HTTP protocol, allowing us to easily send GET or POST requests and handle responses.
http.begin(client, endpoint + key); // URLを指定 , define url
The http.begin()
function sets up the connection to the specified URL. Here, endpoint + key
represents the complete URL, which is the combination of the base endpoint URL and a key (typically an API key or other identifying information).
client
is theWiFiClient
object, which handles the actual network connection.endpoint + key
is the URL to which the GET request will be sent. Ensure that theendpoint
andkey
variables are defined and hold the correct URL strings.
int httpCode = http.GET(); // GETリクエストを送信, send GET request
The http.GET()
function sends an HTTP GET request to the server. The server’s response status code is stored in the httpCode
variable. This code indicates the success or failure of the request (e.g., 200 for success, 404 for not found, etc.).
return 0;
The return 0;
statement indicates the end of the function, returning 0 to indicate successful execution. This line might be part of a larger function or the main program loop.