Introduction
Interfacing and controlling a limit switch with an ESP32-WROOM microcontroller involves connecting the limit switch to one of the GPIO pins on the ESP32-WROOM and monitoring the switch for any changes in its state. in today’s tutorial, we are going to understand how to interface a simple limit switch with an ESP32-WROOM microcontroller.
What is a Limit Switch?
A limit switch is an electromechanical device that utilizes a mechanical actuator, such as a plunger, lever, or roller, to mechanically actuate electrical contacts. Limit switches operate based on mechanical displacement and find applications in position sensing, safety systems, and automation control.
Hardware Components
To interface a Limit Switch with ESP32, you’ll need the following hardware components to get started:
Steps-by-Step Guide
(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
ESP32 | Limit Switch |
---|---|
GND | GND |
GIOP17 | Pin 2 |
(5) Uploading Code
Now copy the following code and upload it to Arduino IDE Software.
Much like a button or switch, a Limit Switch also demands debouncing. This can introduce complexity into the code structure. Nonetheless, the ezButton library simplifies this by providing debouncing capabilities and leveraging internal pull-up registers, thus facilitating programming tasks.
#include <ezButton.h>
ezButton limitSwitch(17); // create ezButton object that attach to ESP32 pin GIOP17
void setup() {
Serial.begin(9600);
limitSwitch.setDebounceTime(50); // set debounce time to 50 milliseconds
}
void loop() {
limitSwitch.loop(); // MUST call the loop() function first
if(limitSwitch.isPressed())
Serial.println("The limit switch: UNTOUCHED -> TOUCHED");
if(limitSwitch.isReleased())
Serial.println("The limit switch: TOUCHED -> UNTOUCHED");
int state = limitSwitch.getState();
if(state == HIGH)
Serial.println("The limit switch: UNTOUCHED");
else
Serial.println("The limit switch: TOUCHED");
}