ESP32 Tutorial – Switch

1,541 views

Introduction

Interfacing a toggle switch with an ESP32-WROOM module involves connecting the switch to one of the GPIO pins of the ESP32-WROOM so that you can detect the state of the switch (on or off). In today’s tutorial, we are going to understand how to interface a simple toggle switch with an ESP32-WROOm microcontroller.

What is Switch?

A toggle switch is an electrical control device with two distinct positions, ON and OFF, which mechanically latches into one of these states until manually toggled. Toggle switches are available in various configurations, including single-pole, single-throw (SPST), single-pole, double-throw (SPDT), double-pole, single-throw (DPST), etc.

Hardware Components

To interface a switch with ESP32, you’ll need the following hardware components to get started:

ComponentsValue / ModelQty
ESP321
Switch 1
Breadboard1
Jumper Wires1
DC Power for ESP321

(1) Setting up Arduino IDE

Download Arduino IDE Software from its official site. Here is a step-by-step guide on “How to install Arduino IDE“.

(2) ESP32 in Arduino IDE

There’s an add-on that allows you to program the ESP32 using the Arduino IDE. Here is a step-by-step guide on “How to Install ESP32 on Arduino IDE“.

(3) Include Libraries

Before you start uploading a code, download and unzip the ezButton.h library at /Program Files(x86)/Arduino/Libraries (default). Here is a step-by-step guide on “How to Add Libraries in Arduino IDE“.

(4) Schematic

Make connections according to the circuit diagram given below.

Wiring / Connections

ESP32Switch
GNDGND
GIOP17Pin 2

(5) Uploading Code

Now copy the following code and upload it to Arduino IDE Software.

Just like a button, an ON/OFF switch needs debouncing as well. This process can add complexity to the code. However, the ezButton library simplifies this by providing built-in debouncing functionality and utilizing internal pull-up registers, thus streamlining programming tasks.

#include <ezButton.h>

ezButton mySwitch(17);  // create ezButton object that attach to ESP32 pin GIOP17

void setup() {
  Serial.begin(9600);
  mySwitch.setDebounceTime(50); // set debounce time to 50 milliseconds
}

void loop() {
  mySwitch.loop(); // MUST call the loop() function first

  if (mySwitch.isPressed())
    Serial.println("The switch: OFF -> ON");

  if (mySwitch.isReleased())
    Serial.println("The switch: ON -> OFF");

  int state = mySwitch.getState();
  if (state == HIGH)
    Serial.println("The switch: OFF");
  else
    Serial.println("The switch: ON");
}