· 3 min read

Building an Air Quality Monitoring App with Arduino and ESP32 (4) - WiFi

This article was auto-translated from Chinese. Some nuances may be lost in translation.

This article is the fourth in the series:

  1. Sensors Introduction - DHT11 and MH-Z14A
  2. Data Communication - UART (Implemented with UART, so only UART is covered)
  3. Arduino Pitfalls and Lessons Learned
  4. WiFi: To save debugging time, I bought an ESP32 development board, which already comes with built-in WiFi and Bluetooth.
  5. (Coming Soon) MQTT: Used MQTT, a lightweight communication protocol, to send data to other devices.
  6. (Coming Soon) Grafana / Web: Once data is in the database, you obviously want to display it in a flashy way! Here, Grafana + Prometheus and Svelte are used to display the data.

Introduction

Typically, implementing WiFi functionality on an Arduino requires an add-on module, with the ESP8266 being a common chip choice. However, if you only buy an ESP8266 chip, you have to solder all the pins yourself and digest the entire datasheet. While that’s great practice if you want to understand how WiFi works under the hood, our goal here is simply to bring the whole project idea to life. Therefore, I bought an ESP32 development board that already has built-in WiFi and Bluetooth.

The ESP32 development board actually offers far more than just WiFi—it includes GPIO pins, serial interfaces, and UART. It is also compatible with the Arduino IDE for uploading code, making development very convenient. In fact, even without an Arduino, you could implement all the features 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()
{
}

Using the WiFi library makes setting up a WiFi connection quite straightforward. You just need to call WiFi.mode and WiFi.begin directly inside setup. I haven’t implemented a reconnection mechanism here, so if it fails, you might need to restart the board.

Once connected to WiFi, there’s so much you can do! For example, running an HTTP server, making API calls to a backend, sending sensor readings to a database, real-time monitoring, and more.

Here, what we want to do is send the sensor data (temperature, humidity, and CO2 concentration) to a server via MQTT, leaving all the remaining logic for the server to handle. We’ll introduce MQTT in the next article!

Related Posts

Explore Other Topics