ESP32 - Rocker Switch Module

Hours at a desk go by fast, and your back pays for it. In this tutorial, an ESP32 and one rocker switch turn into a simple break reminder: flip the switch ON when you sit down to work, and the ESP32 tells you from time to time to stand up and stretch. Flip it OFF, and the reminders stop. The part is the DIYables ON/OFF Rocker Switch Module: a KCD1 rocker with an I and an O on its face, already soldered to a little PCB that gives you SIG, VCC and GND pins. We start with the basics, reading ON or OFF on GPIO21 and printing it to the Serial Monitor. After that, the ezButton library takes care of the contact bounce and tells the code the moment the rocker is flipped.

ESP32 rocker switch module - read the ON/OFF position on GPIO21 and use it as a break reminder switch

This tutorial shows how to program the ESP32 using the Arduino language (C/C++) via the Arduino IDE. If you’d like to learn how to program the ESP32 with MicroPython, visit this ESP32 MicroPython - Rocker Switch Module tutorial.

Introduction to the Rocker Switch Module

The rocker switch module pinout - SIG, VCC and GND pins of the DIYables board
image source: diyables.io

Turn the module in your hand and you find two parts. The top is a black KCD1 rocker, the type you press on a kettle or an extension lead. It is soldered to a blue PCB of roughly 24 mm per side. A screw fits through each of its four corner holes, which is handy for fixing the switch inside a project box. The wires go to a 3-pin header that is bent at 90 degrees, so the cable leaves the board sideways.

The face of the rocker carries an "I" for ON and an "O" for OFF. The PCB adds "ON (H)" and "OFF (L)" beside the switch. Read the letters in brackets as the level that the ESP32 will see: H for HIGH, L for LOW.

A push button jumps back up when you let go. This rocker does not: it is a maintained (latching) switch, and the side you pressed stays down. So the ESP32 never waits for a click here. Instead, it checks which side is down, and in the second code, whether that side has just changed.

Rocker Switch Module
The switch KCD1 rocker, SPST, maintained (latching)
The marks on the rocker I = ON, O = OFF
The supply voltage (VCC) 3.3V to 5V
The SIG output in the ON position HIGH, the same voltage as VCC
The SIG output in the OFF position LOW (0V)
The pull-down resistor 10K ohm (marked 103), on the board
The connector 3-pin right-angle male header, 2.54mm pitch
The board size about 24 x 24mm, 4 mounting holes
The size with the header about 24 x 29 x 22mm

Rocker Switch Module Pinout

You will not find the pin names on the front. Flip the board over: the labels sit beside the header, and the pin with the square solder pad is GND. Seen from the front, with the header pointing right, the order from the top is SIG, VCC, GND. From the back, the list runs the other way: GND, VCC, SIG.

  • SIG pin: connect this pin to a GPIO of the ESP32. Its level follows the rocker: HIGH with I pressed down, LOW with O pressed down.
  • VCC pin: connect this pin to the 3V3 pin of the ESP32. Never use the 5V or VIN pin.
  • GND pin: connect this pin to GND (0V).

※ NOTE THAT:

In the ON position, the switch joins SIG to VCC, so SIG carries the VCC voltage. The ESP32 GPIO pins take 3.3V at most. With VCC on 5V or VIN, every flip to I would put 5V on GPIO21, and that can damage the pin. Keep VCC on 3V3: the module works fine at 3.3V.

When the switch is open, a 10K resistor on the PCB ties SIG to GND. The pin therefore has a clear LOW level in the OFF position, and the ESP32 needs no extra resistor and no INPUT_PULLUP. The logic is not inverted either: ON reads HIGH, OFF reads LOW.

The switch body says "6A 250VAC / 10A 125VAC", and that can mislead you. Those numbers belong to the switch part by itself, not to this module. Here the rocker only sends a tiny 3.3V signal to one GPIO. Keep mains power, lamps and motors away from the header pins.

Like every mechanical switch, the rocker bounces. For a few milliseconds after a flip, its contacts touch and let go several times. A slow polling loop, like the first code below, does not care. Code that reacts to the flip itself must ignore this short noise, and in the second code, the ezButton library does that job.

Do you already have the bare 2-pin ON/OFF switch? The ESP32 - Switch tutorial wires it between a GPIO and GND and uses the pull-up inside the ESP32, so ON reads LOW there. The module turns this around: ON is HIGH, the resistor is already on the board, and every pin has a label. If you need a key that springs back after a press, see ESP32 - Button Module.

Wiring Diagram

Three wires are all it takes. You add nothing else, not even a resistor, and both codes in this tutorial share this wiring.

ESP32 rocker switch module wiring diagram

This image is created using Fritzing. Click to enlarge image

Rocker Switch Module Pin ESP32 Pin
VCC 3V3 (not 5V, not VIN)
SIG GPIO21
GND GND

GPIO21 was picked for a reason: the ESP32 does not care about its level while it boots. This matters for a rocker, because you will often plug in the USB cable while the switch is still ON. Some other pins, such as GPIO2 and GPIO12, must not be HIGH during start-up, or the upload or the boot itself can fail. Keep in mind that GPIO21 is also the default SDA pin for I2C. If your project adds an I2C display or sensor, move SIG to another free GPIO and change the pin number in the code.

If you're unfamiliar with how to supply power to the ESP32 and other components, you can find guidance in the following tutorial: The best way to Power ESP32 and sensors/displays.

How To Program For Rocker Switch Module

Reading the switch needs no library. Two built-in functions do the job.

  • Make GPIO21 an input without an internal resistor. The pull-down is already on the module, and INPUT_PULLUP would only pull against it.
pinMode(ROCKER_SWITCH_PIN, INPUT); // the module's pull-down keeps SIG LOW when OFF
  • Read the position with digitalRead(). The result is HIGH (1) when the rocker is on I, and LOW (0) when it is on O.
bool isOn = (digitalRead(ROCKER_SWITCH_PIN) == HIGH);
  • To do something at the moment of a flip, the code has to remember the last steady position and skip the bounce. You can write this yourself with millis(), or let the ezButton library do it, as in the second code.

ESP32 Code - Read ON or OFF from the Rocker Switch

The first code is a wiring check. About three times per second, the ESP32 reads GPIO21 and prints the position of the rocker, followed by the raw value of the pin.

/* * This ESP32 code is created by esp32io.com * * This ESP32 code is released in the public domain * * For more detail (instruction and wiring diagram), visit https://esp32io.com/tutorials/esp32-rocker-switch-module */ #define ROCKER_SWITCH_PIN 21 // ESP32's GPIO21 connected to the SIG pin of the rocker switch module void setup() { Serial.begin(9600); // plain INPUT: the 10K pull-down resistor on the module already keeps // SIG at LOW while the switch is OFF, so INPUT_PULLUP is not needed pinMode(ROCKER_SWITCH_PIN, INPUT); } void loop() { int sig = digitalRead(ROCKER_SWITCH_PIN); // 1 (HIGH) = rocker on I, 0 (LOW) = rocker on O if (sig == HIGH) Serial.print("ON [rocker on I]"); else Serial.print("OFF [rocker on O]"); Serial.print(" GPIO21 = "); Serial.println(sig); delay(300); // a reading about 3 times per second is enough for a switch you flip by hand }

Quick Instructions

  • If this is the first time you use ESP32, see how to setup environment for ESP32 on Arduino IDE.
  • Make the three connections from the table above. VCC goes to 3V3.
  • Run the USB Type-C cable from the ESP32 to your PC.
  • In Arduino IDE, select the ESP32 board (e.g. ESP32 Dev Module) and the right COM port.
  • Start a new sketch and paste the code above into it.
  • Click to the Upload button and give it a moment: compiling for the ESP32 takes a little longer than for a small Arduino board.
How to upload ESP32 code on Arduino IDE
  • Open the Serial Monitor. Set its speed to 9600 baud.
How to open serial monitor on Arduino IDE
  • Begin with the O side pressed down. Rock the switch over to I, count to two, then rock it back to O.
∞
Newbiely | Arduino IDE 2.3.8
──
☐
✕
File
Edit
Sketch
Tools
Help
ESP32 Dev Module
Newbiely.ino
···
8 Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'ESP32 Dev Module' on 'COM15')
New Line
9600 baud
OFF [rocker on O] GPIO21 = 0 OFF [rocker on O] GPIO21 = 0 OFF [rocker on O] GPIO21 = 0 ON [rocker on I] GPIO21 = 1 ON [rocker on I] GPIO21 = 1 ON [rocker on I] GPIO21 = 1 ON [rocker on I] GPIO21 = 1 ON [rocker on I] GPIO21 = 1 ON [rocker on I] GPIO21 = 1 ON [rocker on I] GPIO21 = 1 OFF [rocker on O] GPIO21 = 0 OFF [rocker on O] GPIO21 = 0
Ln 11, Col 1
ESP32 Dev Module on COM15
2

The words follow the marks on the rocker: I gives 1, O gives 0. If you see 0 in both positions, check that VCC is on 3V3 and SIG is on GPIO21. Without a voltage on VCC, the switch has nothing to pass to SIG. If 0 and 1 change by themselves while you do not touch the rocker, a wire is loose.

This code repeats the same line about three times per second, and it has no idea when the rocker was flipped. That is fine for a test, but a real project usually wants to act once per flip. The next code does that.

ESP32 Code - Break Reminder Switch with the ezButton Library

Time to give the rocker something useful to do: it becomes the ON/OFF switch of a break reminder. While the rocker is on I, the ESP32 prints "stand up and stretch!" every 15 seconds. This short time is only for testing. For real use, change BREAK_INTERVAL to 30 minutes. When you flip the rocker to O, the reminders stop, and the ESP32 tells you how many it sent.

The ezButton library was written for buttons, but it works just as well for a switch. It checks the time with millis() instead of waiting with delay(), so the loop never stops and the reminder timer keeps running. Because the module has its own pull-down resistor, the object is created in the EXTERNAL_PULLDOWN mode, where HIGH counts as "pressed". For a rocker, "pressed" simply means "switched ON". This mode needs ezButton version 1.0.6 or newer.

  • ezButton toggleSwitch(21, EXTERNAL_PULLDOWN); creates the switch object on GPIO21.
  • toggleSwitch.setDebounceTime(50); accepts a new position only after it stays steady for 50 milliseconds.
  • toggleSwitch.loop(); must be the first line in loop(). It reads the pin and removes the bounce.
  • toggleSwitch.isPressed() is true once, right after the rocker is switched ON.
  • toggleSwitch.isReleased() is true once, right after the rocker is switched OFF.
  • toggleSwitch.getState() gives the current steady position at any time: HIGH (ON) or LOW (OFF).
/* * This ESP32 code is created by esp32io.com * * This ESP32 code is released in the public domain * * For more detail (instruction and wiring diagram), visit https://esp32io.com/tutorials/esp32-rocker-switch-module */ #include <ezButton.h> #define ROCKER_SWITCH_PIN 21 // ESP32's GPIO21 connected to the SIG pin of the rocker switch module #define BREAK_INTERVAL 15000UL // 15 seconds for testing. For real use, try 1800000UL (30 minutes) // EXTERNAL_PULLDOWN: the module has its own pull-down resistor, // so HIGH means the rocker is ON (ezButton calls this "pressed") ezButton toggleSwitch(ROCKER_SWITCH_PIN, EXTERNAL_PULLDOWN); unsigned long lastReminderTime = 0; // the moment of the last reminder (or of the flip to ON) int reminderCount = 0; // reminders sent since the rocker went ON void printTime() { Serial.print("["); Serial.print(millis() / 1000); // seconds since the ESP32 started Serial.print(" s] "); } void setup() { Serial.begin(9600); toggleSwitch.setDebounceTime(50); // a new position counts only after it stays steady for 50 ms // getState() gives the current position, also when the rocker is already ON at power-up Serial.print("Break reminder ready - rocker is "); Serial.println(toggleSwitch.getState() == HIGH ? "ON" : "OFF"); lastReminderTime = millis(); } void loop() { toggleSwitch.loop(); // MUST be called first. It reads GPIO21 and filters out the bounce if (toggleSwitch.isPressed()) { // true once, right after the rocker is switched to I (ON) printTime(); Serial.print("Rocker on I: reminders ON, one every "); Serial.print(BREAK_INTERVAL / 1000); Serial.println(" s"); reminderCount = 0; lastReminderTime = millis(); // start counting the interval from this moment } if (toggleSwitch.isReleased()) { // true once, right after the rocker is switched to O (OFF) printTime(); Serial.print("Rocker on O: reminders OFF, "); Serial.print(reminderCount); Serial.println(" sent"); } // while the rocker stays ON, send a reminder each time the interval has passed if (toggleSwitch.getState() == HIGH && millis() - lastReminderTime >= BREAK_INTERVAL) { lastReminderTime = millis(); reminderCount++; printTime(); Serial.print("Reminder "); Serial.print(reminderCount); Serial.println(": stand up and stretch!"); } // nothing here blocks, so other tasks (WiFi, a display, sensors) can run in the loop too }

Quick Instructions

  • Keep the wiring from the first code.
  • In Arduino IDE, click to the Libraries icon on the left bar.
  • Type ezButton in the search box, then look for the ezButton library by ArduinoGetStarted.com.
  • Click to the Install button. If ezButton is already installed, make sure its version is 1.0.6 or newer.
  • Search for ezButton created by ArduinoGetStarted.com and click the Install button.
∞
Newbiely | Arduino IDE 2.3.8
──
☐
✕
File
Edit
Sketch
Tools
Help
ESP32 Dev Module
Library Manager
Type:
All
Topic:
All
ezButton by ArduinoGetStarted.com
Button library supports debounce, pressed/released events and the press counting. It is easy to use with multiple buttons. The library can be used for push-button, momentary switches, toggle switch, magnetic contact switch (door sensor)... It is designed for not only beginners but also experienced users. More info
1.0.6
INSTALL
Newbiely.ino
···
1 void setup() {
Output
Serial Monitor
Ln 1, Col 1
ESP32 Dev Module on COM15
1
  • Upload the code above to the ESP32 and open the Serial Monitor at 9600 baud.
  • Press the EN (reset) button on the ESP32 once, so the start line shows up.
  • Flip the rocker to I and wait about 50 seconds. Then flip it to O. Flip it to I and back to O once more, quickly this time.
∞
Newbiely | Arduino IDE 2.3.8
──
☐
✕
File
Edit
Sketch
Tools
Help
ESP32 Dev Module
Newbiely.ino
···
8 Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'ESP32 Dev Module' on 'COM15')
New Line
9600 baud
Break reminder ready - rocker is OFF [6 s] Rocker on I: reminders ON, one every 15 s [21 s] Reminder 1: stand up and stretch! [36 s] Reminder 2: stand up and stretch! [51 s] Reminder 3: stand up and stretch! [58 s] Rocker on O: reminders OFF, 3 sent [73 s] Rocker on I: reminders ON, one every 15 s [74 s] Rocker on O: reminders OFF, 0 sent
Ln 11, Col 1
ESP32 Dev Module on COM15
2

Each flip gives exactly one "Rocker on" line, even though the contacts bounce, and the reminders come only while the rocker stays on I. Every new ON period starts its count from zero. Now press EN with the rocker left on I. The start line says "rocker is ON", and the first reminder comes 15 seconds later without any flip. That is the job of getState(): isPressed() only reports a change, and there is no change at power-up.

You can learn more about the ezButton library here.

Line-by-line Code Explanation

Both ESP32 codes above have a comment on each important line. Please read the comments together with the code!

Video Tutorial

Making video is a time-consuming work. If the video tutorial is necessary for your learning, please let us know by subscribing to our YouTube channel , If the demand for video is high, we will make the video tutorial.

※ OUR MESSAGES