ESP32 MicroPython Rocker Switch Module

This tutorial instructs you how to use a DIYables rocker switch module (ON/OFF type) with the ESP32 and MicroPython. Think of the big I/O switch on a power strip, mounted on a little board with three named pins. Our first script polls the switch in a slow loop, 2.5 times every second. After that, we hand the watching job to the hardware: a pin interrupt tells MicroPython the moment the rocker is flipped, and the Shell prints the new state with a time stamp. In detail, we will learn:

ESP32 MicroPython rocker switch module - a GPIO21 pin interrupt reports each ON/OFF flip in Thonny

Overview of Rocker Switch Module

Like a seesaw with two resting places, a rocker tilts to one side or the other. Tip the "I" end down and the switch is ON. Tip the "O" end down and it is OFF. No spring brings it back, so it keeps its position through a power cut or a reset of the ESP32. In parts lists, this is called a latching (or maintained) SPST switch.

On the DIYables module, the black KCD1 rocker sits on a blue PCB that measures about 24 x 24mm. A screw hole in each corner makes it easy to mount on the front panel of an enclosure, and a right-angle 3-pin header takes the wires. Look for the tiny part marked 103 as well: this 10 kΩ resistor pulls SIG down. The PCB also carries two small labels, "ON (H)" and "OFF (L)". They mean that SIG is HIGH in the ON position and LOW in the OFF position. You get five modules in one pack.

For your code, this means there is no "press" to wait for. There is a position that can stay the same for hours, and now and then a change. The first script below reads the position. The second one reacts to the change.

ON/OFF Rocker Switch Module
Rocker type KCD1, SPST, latching (no spring return)
ON / OFF symbols I / O
Supply (VCC) 3.3V to 5V
SIG, rocker on I HIGH (1), same voltage as VCC
SIG, rocker on O LOW (0), 0V
Pull-down 10 kΩ on the board (103)
Pins right-angle header, 3 pins, 2.54mm spacing
PCB about 24 x 24mm, a screw hole in each corner
Size, pins counted about 24 x 29 x 22mm

On the side of the rocker you can see "6A 250VAC / 10A 125VAC". This is the limit of the switch part inside a mains appliance. Here, its contacts only carry a weak logic signal to GPIO21, so never connect mains wires or a motor to the three header pins.

Pinout

Rocker switch module pinout showing which header pin is SIG, VCC or GND
image source: diyables.io

Lay the module down so you look at the rocker, and turn it until the header points right. Now SIG is the top pin, VCC the middle one and GND the bottom one:

  • SIG pin: the output that your code reads. On the I side it gives 1 (3.3 volts), on the O side 0 (0 volts). Connect it to GPIO21.
  • VCC pin: the supply input, 3.3 volts up to 5 volts. On the ESP32, only the 3.3V pin is the right place for it.
  • GND pin: the ground. Wire it to any GND pin (0 volts) of the ESP32.

Flip the board over and you find the names printed next to the pins, now in the order GND, VCC, SIG. The square solder pad marks GND.

※ NOTE THAT:

Inside the switch, the I position joins SIG directly to VCC. So the voltage you feed in on VCC is the voltage that GPIO21 sees. The ESP32 inputs are built for 3.3 volts at most, and 5 volts from the VIN or 5V pin can harm GPIO21. Use the 3.3V pin.

Maybe you know the ESP32 MicroPython Switch tutorial already. That page wires a bare 2-leg rocker to GND and lets the internal pull-up of the ESP32 hold the pin high, so the code must treat 0 as ON. With the module, nothing is upside down: 1 is ON and 0 is OFF. Thanks to the pull-down on the board, Pin(21, Pin.IN) is all the setup you need. Do not add Pin.PULL_UP here: the ESP32's own resistor would pull against the one on the module.

Wiring Diagram

No breadboard this time. The module brings its own header pins, so each of the three jumper wires runs directly from a module pin to an ESP32 pin.

The wiring diagram between ESP32 MicroPython rocker switch module

This image is created using Fritzing. Click to enlarge image

Rocker Switch Module Pin ESP32 Pin
SIG GPIO21
VCC 3.3V (never VIN or 5V)
GND GND

Why GPIO21? It is a normal input pin, it can raise an interrupt (the second script needs that), and the ESP32 does not check it at power-on. If you move SIG to another pin, change ROCKER_SWITCH_PIN in both scripts. Do not pick GPIO12: the ESP32 reads that pin at start-up, and a switch left ON there can stop the board from booting.

ESP32 MicroPython Code - Read the Rocker Switch Module

Before the interrupt, let's make sure the ESP32 sees the switch at all. The script makes GPIO21 an input with Pin(ROCKER_SWITCH_PIN, Pin.IN) and asks for no pull resistor. Every 400 ms, it calls value() and prints three things: the rocker side that is down, the word ON or OFF, and the number it read. Such a slow check is fine for a rocker. The switch does not move by itself, so nothing gets lost between two reads, and a bounce of a few milliseconds is too short to show up.

""" This ESP32 MicroPython code was developed by newbiely.com This ESP32 MicroPython code is made available for public use without any restriction For comprehensive instructions and wiring diagrams, please visit: https://newbiely.com/tutorials/esp32-micropython/esp32-micropython-rocker-switch-module """ from machine import Pin import time ROCKER_SWITCH_PIN = 21 # The ESP32 pin GPIO21 connected to the SIG pin of the rocker switch module # Pin.IN with no pull argument: the module already holds SIG low # with its own pull-down resistor whenever the switch is OFF. rocker_switch = Pin(ROCKER_SWITCH_PIN, Pin.IN) while True: level = rocker_switch.value() if level == 1: # I side pressed: the switch joins SIG to VCC (3.3V) print("I side pressed -> ON (read 1)") else: # O side pressed: SIG rests at 0V print("O side pressed -> OFF (read 0)") time.sleep_ms(400) # 2.5 lines per second; the rocker does not move by itself

Detailed Instructions

Here's instructions on how to set up and run your MicroPython code on the ESP32 using Thonny IDE:

  • You need Thonny IDE on the computer and MicroPython firmware on the ESP32.
  • If one of them is missing, the ESP32 MicroPython Getting Started guide shows how to install both.
  • Wire SIG, VCC and GND following the table, and check VCC twice: it goes on 3.3V.
  • Plug the ESP32 into the computer with the USB cable and launch Thonny.
  • In the menu, go to Tools Options. On the Interpreter tab, set the interpreter to MicroPython (ESP32).
  • Set the port by hand only if Thonny does not find the board (COM9 on Windows, for example, or /dev/ttyUSB0 on Linux).
  • Open an empty editor tab and put the script from this section into it.
  • Save it to the board:
    • Click the Save button, or press Ctrl+S.
    • Pick MicroPython device in the save window.
    • Use main.py as the file name.
  • With the rocker on O, start the script with F5 (or the green Run button).
  • Count to three and press the I side. Count to three again and press the O side.
  • Read the result in the Shell pane of Thonny:
Shell x
>>> %Run -c $EDITOR_CONTENT
MPY: soft reboot MPY: soft reboot O side pressed -> OFF (read 0) O side pressed -> OFF (read 0) O side pressed -> OFF (read 0) O side pressed -> OFF (read 0) O side pressed -> OFF (read 0) O side pressed -> OFF (read 0) O side pressed -> OFF (read 0) I side pressed -> ON (read 1) I side pressed -> ON (read 1) I side pressed -> ON (read 1) I side pressed -> ON (read 1) I side pressed -> ON (read 1) I side pressed -> ON (read 1) I side pressed -> ON (read 1) O side pressed -> OFF (read 0) O side pressed -> OFF (read 0)
MicroPython (ESP32) • CP2102 USB To UART Bridge Controller @ COM12 ≡

If you name your script main.py and save it to the MicroPython device, it will run automatically every time the ESP32 is powered on.

While the rocker rests, the Shell repeats the same line. Nothing is wrong: a latching switch has no reason to change. But it shows the weak spot of this way of reading: the ESP32 asks the same question 150 times a minute, and the answer is almost always the same. If the words do not follow the rocker, look at the wires first. A SIG wire that is not on GPIO21 gives random values, and a VCC wire that is not on 3.3V gives OFF in both positions.

ESP32 MicroPython Code - Rocker Switch Module with a Pin Interrupt

Now let's turn it around. Instead of the loop asking GPIO21 again and again, the pin itself reports a change. In MicroPython, Pin.irq() links a function, called the handler, to a pin. The script uses rocker_switch.irq(trigger=Pin.IRQ_RISING | Pin.IRQ_FALLING, handler=rocker_isr). It asks for the handler on both kinds of edges: a rising edge (0 to 1) when you press the I side, and a falling edge (1 to 0) when you press the O side.

The handler rocker_isr() only does two things: it sets edge_flag to True and saves time.ticks_ms() in edge_time. An interrupt pauses the main program in the middle of its work, so the handler must finish fast and give control back. Also, the bounce calls it several times for one flip, so a print in the handler would fill the Shell with half-finished changes.

The slow part happens in the while loop, which looks at the note every 5 ms. Each bounce writes a newer time into edge_time, so the loop waits until SETTLE_TIME_MS (30 ms) have passed since the last edge. By then the contacts are still, and one value() read gives the true position. The script prints ON or OFF with the time that the handler saved, in seconds since the start. So the time shows when you flipped the rocker, not when the loop got around to it. Between flips, the loop is free for other jobs, for example blinking an LED or talking to WiFi.

""" This ESP32 MicroPython code was developed by newbiely.com This ESP32 MicroPython code is made available for public use without any restriction For comprehensive instructions and wiring diagrams, please visit: https://newbiely.com/tutorials/esp32-micropython/esp32-micropython-rocker-switch-module """ from machine import Pin import time ROCKER_SWITCH_PIN = 21 # The ESP32 pin GPIO21 connected to the SIG pin of the rocker switch module SETTLE_TIME_MS = 30 # Quiet time after the last edge before the new level is trusted rocker_switch = Pin(ROCKER_SWITCH_PIN, Pin.IN) # The module's pull-down holds SIG at 0 when OFF edge_flag = False # The handler sets this to True on every edge edge_time = 0 # The handler saves time.ticks_ms() of the latest edge here def rocker_isr(pin): # Called on every rising (O -> I) and falling (I -> O) edge of SIG. # Contact bounce can call it several times for one flip. # Keep it short: no print, no sleep, no pin reading here. global edge_flag, edge_time edge_flag = True edge_time = time.ticks_ms() rocker_switch.irq(trigger=Pin.IRQ_RISING | Pin.IRQ_FALLING, handler=rocker_isr) start_time = time.ticks_ms() last_state = rocker_switch.value() # An interrupt only fires on a change, so read the start position once print("Watching GPIO" + str(ROCKER_SWITCH_PIN), "with Pin.irq() - flip the rocker") print("Start position: Switch", "ON" if last_state == 1 else "OFF") while True: # Act only when no new edge has come for SETTLE_TIME_MS: the bounce is over if edge_flag and time.ticks_diff(time.ticks_ms(), edge_time) >= SETTLE_TIME_MS: edge_flag = False # Clear first, so an edge that comes right now is not lost flip_time = edge_time # Time of the last edge, saved by the handler state = rocker_switch.value() if state != last_state: # A very fast flip-and-back gives the same level: print nothing last_state = state seconds = time.ticks_diff(flip_time, start_time) / 1000 if state == 1: print("[{:8.3f} s] Switch ON".format(seconds)) else: print("[{:8.3f} s] Switch OFF".format(seconds)) # The rest of the time the loop is free: other work could go here time.sleep_ms(5)

Detailed Instructions

  • Stop the first script with the red Stop button. Keep the wiring as it is.
  • Paste the interrupt code into a new tab and save it to the MicroPython device as main.py, so it replaces the old file.
  • Leave the rocker on O and press F5.
  • Rock the switch over to I, then back to O. Do that three or four times, once very fast.
  • Each flip adds one line, with the time when it happened:
Shell x
>>> %Run -c $EDITOR_CONTENT
MPY: soft reboot MPY: soft reboot Watching GPIO21 with Pin.irq() - flip the rocker Start position: Switch OFF [ 3.071 s] Switch ON [ 5.846 s] Switch OFF [ 6.902 s] Switch ON [ 7.388 s] Switch OFF [ 12.415 s] Switch ON
MicroPython (ESP32) • CP2102 USB To UART Bridge Controller @ COM12 ≡

Compare this with the first script. The Shell stays quiet while the rocker rests, and a line shows up only when something happens. One flip gives one line, even though the bounce called the handler more than once. If you ever get two lines for a single flip, raise SETTLE_TIME_MS to 50.

Look at the "Start position" line, too. A rocker can already be ON when the ESP32 powers up, and an interrupt only fires on a change. That is why the script reads the pin once before it starts waiting for edges.

Project Ideas

A rocker switch module looks good on the front panel of a project box. The interrupt version fits projects where the ESP32 is busy with other work:

  • A master ON/OFF for a WiFi alarm: the ESP32 keeps its network jobs going, and the interrupt makes sure it never misses the moment you arm or disarm it.
  • An "auto / manual" switch for a plant watering box: on I the soil sensor decides, on O the pump only runs when you ask.
  • A mute switch for the buzzer of an alarm clock.
  • An ON-time log for a machine: keep the time of each flip and add up how long it was ON per day.

Other switch pages for the ESP32 with MicroPython: ESP32 MicroPython Slide Switch covers a tiny three-leg slider. ESP32 MicroPython Button Module uses the same three-wire idea for a push button that pops back up when you let go.

Video Tutorial

※ OUR MESSAGES

  • As freelancers, We are AVAILABLE for HIRE. See how to outsource your project to us
  • Please feel free to share the link of this tutorial. However, Please do not use our content on any other websites. We invested a lot of effort and time to create the content, please respect our work!