Kalan's Blog

Current Theme light

用 Arduino 與 ESP32 打造空氣品質監測應用(4)- WiFi 篇 | 用 Arduino 打造空氣品質監測

This article is the fourth in a series:

  1. Introduction to Sensors - DHT11 and MH-Z14A
  2. Data Communication - UART (We only discuss UART since it is used for implementation)
  3. Arduino Pitfalls
  4. WiFi: To save debugging time, I purchased an ESP32 development board, which already includes WiFi and Bluetooth functionality.
  5. (Upcoming) MQTT: To send data to other devices, we use MQTT, a lightweight communication protocol.
  6. (Upcoming) Grafana / Web: To display the data in a flashy way, we use Grafana + Prometheus and Svelte.

Introduction

Typically, implementing WiFi functionality on Arduino requires additional expansion modules, with the ESP8266 chip being the most common. However, if you only purchase the ESP8266, you have to solder all the pins yourself and study the Datasheet on your own to understand the underlying WiFi operation. While it's a great exercise to learn about WiFi at a low level, our goal this time is to implement the entire idea. Therefore, I purchased an ESP32 development board that already has built-in WiFi and Bluetooth functionality.

The ESP32 development board not only has WiFi functionality but also features GPIO pins, a Serial interface, and UART, making it convenient for development. It can also be programmed using the Arduino IDE. So even without using Arduino, you can accomplish all the required functionality using just the ESP32.

WiFi Connection

#include "WiFi.h"

WiFiClient client;

void setup()
{
  WiFi.mode(WIFI_STA);
  WiFi.begin(SSID, PASSWORD);

  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.println("Connecting to WiFi..");
  }

  Serial.println("Wifi is connected!");
}

void loop()
{
}

With the WiFi library, establishing a WiFi connection is quite simple. Just call WiFi.mode and WiFi.begin directly in the setup function. I haven't set up a reconnection mechanism here, so if it fails, you may need to restart the Arduino.

Once connected to WiFi, there are many things you can do! Such as running an HTTP server, sending API requests to a server, sending sensor data to a database, real-time monitoring, and more.

In this case, we want to send sensor data (temperature, humidity, and CO2 concentration) to a server using MQTT, and let the server handle the rest of the logic. We will cover MQTT in the next article!

If you found this article helpful, please consider buy me a drink ☕️ It'll make my ordinary day shine✨

Buy me a coffee