Raspberry Pi - Rocker Switch Module

Flip the rocker to "I", and a line with the time shows up in your SSH window. Flip it back to "O", and a second line appears. Between the two flips, your Python script does not check the pin at all. It lets the RPi.GPIO library watch the pin in the background, and a small function of yours runs only when the level really changes. That is the goal of the second script on this page. But first, meet the hardware: the DIYables ON/OFF rocker switch module, the same kind of rocker you know from power strips, mounted on a small board with a pull-down resistor and three labeled pins. This tutorial instructs you how to use Raspberry Pi with this module, using Python scripts that you start over SSH. In detail, we will learn:

Raspberry Pi with a DIYables ON/OFF rocker switch module on GPIO25 - a Python script logs each flip with the time

We suggest:

Hardware Preparation

1×Raspberry Pi 5
1×ON/OFF Rocker Switch Module
1×Jumper Wires
1×Recommended: Screw Terminal Block Shield for Raspberry Pi
1×Recommended: Raspberry Pi Prototyping Base Plate & Breadboard Kit

Or you can buy the following kits:

1×DIYables Sensor Kit (18 sensors/displays)
Disclosure: Some of the links provided in this section are Amazon affiliate links. We may receive a commission for any purchases made through these links at no additional cost to you.
Additionally, some of these links are for products from our own brand, DIYables .

Overview of Rocker Switch Module

Look at a power strip or at the back of a desktop PC, and you will probably find a rocker switch: a small seesaw that you press down on one side or the other. The DIYables ON/OFF rocker switch module carries a black KCD1 rocker of this type on a blue board of about 24 x 24 mm. The board has four mounting holes, so you can screw it behind a cut-out in the lid of a box. On one edge, a 3-pin right-angle male header (2.54 mm pitch) points sideways. The modules come in packs of 5.

The rocker has two marks. Press the "I" side down, and the switch is ON. Press the "O" side down, and it is OFF. The print on the board next to the rocker already tells you the signal: "ON (H)" means the output is HIGH when the switch is ON, and "OFF (L)" means it is LOW when the switch is OFF.

This is a maintained switch, also called a latching switch. After a flip, the rocker stays where it is, with no finger on it, and even while the Raspberry Pi is turned off. Inside, there is one contact that is either closed or open (SPST). So a script for this module does not wait for a "press". It asks "is the switch ON or OFF right now?", or it reacts at the moment the answer changes.

Rocker switch module pinout with the SIG, VCC and GND header pins
image source: diyables.io

The pin names are printed on the back of the board, next to the header. Seen from the top, with the header on the right, the order is SIG, VCC, GND from top to bottom:

  • SIG: This pin must be connected to a GPIO pin of the Raspberry Pi. It gives out the VCC voltage when the rocker is ON, and 0V when it is OFF
  • VCC: This pin must be connected to the 3.3V supply of the Raspberry Pi. The module itself accepts 3.3V to 5V, but on a Pi only 3.3V is safe
  • GND: This pin must be connected to ground (0V) of the Raspberry Pi

A 10 kOhm pull-down resistor (printed "103") sits on the board. While the contact is open, it ties SIG to ground, so the input never floats. For this reason, the scripts on this page switch off the internal pull resistors of the Pi with GPIO.PUD_OFF. You do not add any resistor of your own.

What GPIO25 sees in each position:

Rocker position Voltage on SIG GPIO.input(25) returns
"O" side down (OFF) 0V, held there by the resistor 0 (LOW)
"I" side down (ON) 3.3V, the same as VCC 1 (HIGH)

The logic is not inverted. 1 means ON and 0 means OFF.

DIYables ON/OFF Rocker Switch Module
Switch KCD1 rocker, SPST, maintained (latching)
Marks I = ON, O = OFF
Supply voltage (VCC) 3.3V to 5V (3.3V on a Raspberry Pi)
SIG when ON / OFF HIGH (VCC) / LOW (0V)
Pull-down on SIG 10 kOhm, already on the board
Header 3 pins, 2.54 mm, right-angle male
Size board about 24 x 24 mm, about 24 x 29 x 22 mm with the pins

The switch body also shows "6A 250VAC / 10A 125VAC". Those numbers belong to the bare switch. On this module, the rocker only passes a tiny signal to a GPIO pin. Never connect a lamp, a motor or mains wiring to the header. If the switch should control a bigger load, let the Pi drive a relay, and keep the module on the signal side.

Each time the rocker snaps over, its metal contact bounces for a few milliseconds. The first script below reads the pin only every 0.4 seconds, so it never notices. The second script reacts to every change of level, so it filters the bounce out with a 50 ms window.

※ NOTE THAT:

Always go by the SIG, VCC and GND labels on the back of the board. Rocker modules from other makers may put the pins in a different order.

Wiring Diagram

The wiring diagram between Raspberry Pi and rocker switch module

This image is created using Fritzing. Click to enlarge image

To simplify and organize your wiring setup, we recommend using a Screw Terminal Block Shield for Raspberry Pi. This shield ensures more secure and manageable connections, as shown below:

Raspberry Pi Screw Terminal Block Shield
Rocker Switch Module Pin Raspberry Pi Pin
SIG GPIO25 (pin 22)
VCC 3.3V (pin 17)
GND GND (pin 14)

Wire by wire, on the 40-pin header:

  • Rocker switch module VCC pin to Raspberry Pi 3.3V (pin 17)
  • Rocker switch module SIG pin to Raspberry Pi GPIO25 (pin 22)
  • Rocker switch module GND pin to Raspberry Pi GND (pin 14)

All three header pins lie close together, between pin 14 and pin 22, so the wires stay short and none of them cross. Jumper wires with female ends slide straight onto the module header and onto the Pi header. You do not need a breadboard.

Watch the numbers. The scripts use BCM numbering (GPIO.setmode(GPIO.BCM)), so the code says 25, the GPIO number, and not 22, the place on the header. The Pi also has a GPIO22, but that one is on physical pin 15. If you type 22 in the code, the script watches the wrong pin and never sees a flip.

※ NOTE THAT:

Keep VCC on 3.3V (pin 17). NEVER move it to a 5V pin (pin 2 or pin 4). When the rocker is ON, SIG passes on the full VCC voltage, so 5V on VCC means 5V on GPIO25. The GPIO pins of the Raspberry Pi work at 3.3V and are not 5V tolerant. A single flip could damage the pin, or the whole board.

How To Program for Raspberry Pi to Read the Rocker Switch Position

The first script is a quick check of the wiring. It reads GPIO25 every 0.4 seconds and prints ON or OFF, together with the raw value 1 or 0. The input is prepared with this line:

GPIO.setup(25, GPIO.IN, pull_up_down=GPIO.PUD_OFF)

GPIO.PUD_OFF keeps the pull-up and pull-down resistors inside the Pi switched off. The 10 kOhm resistor on the module already holds SIG at 0V while the rocker is on "O", so a second resistor would add nothing.

Detailed Instructions

  • Make sure you have Raspbian or any other Raspberry Pi compatible operating system installed on your Pi.
  • Make sure your Raspberry Pi is connected to the same local network as your PC.
  • Make sure your Raspberry Pi is connected to the internet if you need to install some libraries.
  • If this is the first time you use Raspberry Pi, See how to set up the Raspberry Pi
  • Connect your PC to the Raspberry Pi via SSH using the built-in SSH client on Linux and macOS or PuTTY on Windows.
  • Make sure you have the RPi.GPIO library installed. If not, install it using the following command:
sudo apt-get update sudo apt-get install python3-rpi.gpio
  • Plug the three wires onto the header as listed above. Before you power on, check once more that VCC sits on pin 17 (3.3V).
  • Create a Python script file rocker_switch_module.py and add the following code:
""" This Raspberry Pi code was developed by newbiely.com This Raspberry Pi code is made available for public use without any restriction For comprehensive instructions and wiring diagrams, please visit: https://newbiely.com/tutorials/raspberry-pi/raspberry-pi-rocker-switch-module """ import RPi.GPIO as GPIO import time # BCM numbering: 25 means GPIO25, which is physical pin 22 of the 40-pin header # (GPIO22 is another pin: it sits on physical pin 15) GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) ROCKER_PIN = 25 # GPIO25 (pin 22) connected to the SIG pin of the rocker switch module READ_INTERVAL = 0.4 # seconds between two readings # The module has its own 10k pull-down resistor on SIG. # So the internal pull-up / pull-down resistors of the Pi are turned off. GPIO.setup(ROCKER_PIN, GPIO.IN, pull_up_down=GPIO.PUD_OFF) print("Reading the rocker switch module on GPIO25 every 0.4 s. Press Ctrl + C to stop.") try: while True: level = GPIO.input(ROCKER_PIN) # 1 = rocker on "I" (ON), 0 = rocker on "O" (OFF) if level == GPIO.HIGH: print("Rocker switch: ON (GPIO25 = {})".format(level)) else: print("Rocker switch: OFF (GPIO25 = {})".format(level)) # A reading every 0.4 s is far slower than the contact bounce (a few ms), # so this script needs no debounce time.sleep(READ_INTERVAL) except KeyboardInterrupt: print("\nScript stopped") finally: GPIO.cleanup() # release GPIO25
  • Save the file and run the Python script by executing the following command in the terminal:
python3 rocker_switch_module.py
  • Start with the rocker on "O". After a moment, press the "I" side down, wait about two seconds, then press the "O" side down again.
  • Check the terminal:
PuTTY - Raspberry Pi
Reading the rocker switch module on GPIO25 every 0.4 s. Press Ctrl + C to stop. Rocker switch: OFF (GPIO25 = 0) Rocker switch: OFF (GPIO25 = 0) Rocker switch: OFF (GPIO25 = 0) Rocker switch: ON (GPIO25 = 1) Rocker switch: ON (GPIO25 = 1) Rocker switch: ON (GPIO25 = 1) Rocker switch: ON (GPIO25 = 1) Rocker switch: ON (GPIO25 = 1) Rocker switch: OFF (GPIO25 = 0) Rocker switch: OFF (GPIO25 = 0)

The same word repeats line after line, because the switch holds its position until you flip it again. About two seconds on "I" gives five ON lines, one every 0.4 seconds. Press Ctrl + C keys in the terminal to stop the script. It then calls GPIO.cleanup() to free GPIO25.

The output does not follow the rocker? Look at these points:

  • Only OFF lines, whatever you do: the SIG wire is not on pin 22, or VCC has no power. With nothing on VCC, an ON switch has no voltage to pass to SIG.
  • ON and OFF jump around with no hand on the rocker: the GND wire is loose. The pull-down resistor then has no ground to pull SIG to.

Code Explanation

Check out the line-by-line explanation contained in the comments of the source code!

How To Program for Raspberry Pi to Log Each Flip with GPIO Event Detection

The first script asks the pin for its level again and again, even when nothing changes for hours. A rocker switch often stays in one position for a long time, so most of those questions are wasted. RPi.GPIO has a better tool for this: event detection. You tell the library which pin to watch and which function to call. A background thread of the library then waits for an edge on the pin and runs your function once per change. Your own code is free for other work, for example reading a sensor or serving a web page. In this example, the main loop simply sleeps.

All the work starts with this line:

GPIO.add_event_detect(25, GPIO.BOTH, callback=on_flip, bouncetime=50)
  • GPIO.BOTH watches both directions: the rising edge (0 to 1, rocker to "I") and the falling edge (1 to 0, rocker to "O"). GPIO.RISING would only report ON, and GPIO.FALLING only OFF.
  • callback=on_flip names the function to run. The library passes it the pin number, so the function reads the pin itself to learn the new position.
  • bouncetime=50 makes the library ignore any further edge for 50 milliseconds after an edge. This swallows the contact bounce of the rocker.

Inside on_flip(), the script waits 10 ms so the contact can settle, reads GPIO25, and prints the time of the Pi clock (time.strftime("%H:%M:%S")) followed by "switched ON" or "switched OFF". It also keeps the last position it printed. A call that brings no real change is skipped, so one flip always gives exactly one line.

Detailed Instructions

  • Keep the wiring of the first test: SIG on GPIO25 (pin 22), VCC on 3.3V (pin 17), GND on pin 14.
  • If the first script still runs, stop it with Ctrl + C.
  • Create a Python script file rocker_switch_module_events.py and add the following code:
""" This Raspberry Pi code was developed by newbiely.com This Raspberry Pi code is made available for public use without any restriction For comprehensive instructions and wiring diagrams, please visit: https://newbiely.com/tutorials/raspberry-pi/raspberry-pi-rocker-switch-module """ import RPi.GPIO as GPIO import time # BCM numbering: 25 means GPIO25, which is physical pin 22 of the 40-pin header GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) ROCKER_PIN = 25 # GPIO25 (pin 22) connected to the SIG pin of the rocker switch module BOUNCE_MS = 50 # after one edge, ignore new edges for 50 ms (contact bounce) SETTLE_S = 0.01 # in the callback, wait 10 ms before reading the new level # The 10k pull-down resistor on the module holds SIG at 0V while the switch is OFF, # so the internal pull resistors of the Pi stay off. GPIO.setup(ROCKER_PIN, GPIO.IN, pull_up_down=GPIO.PUD_OFF) last_state = GPIO.input(ROCKER_PIN) # the last position that was printed def clock(): return time.strftime("%H:%M:%S") # time from the Raspberry Pi clock def on_flip(channel): # RPi.GPIO calls this function from its own background thread, # once for every edge it sees on the pin. Here, channel is 25. global last_state time.sleep(SETTLE_S) # give the contact a moment to settle level = GPIO.input(channel) # read the new position of the rocker if level == last_state: return # no real change (only bounce): print nothing last_state = level if level == GPIO.HIGH: print("{} switched ON".format(clock())) else: print("{} switched OFF".format(clock())) # Watch both edges: rising (0 -> 1, flip to "I") and falling (1 -> 0, flip to "O") GPIO.add_event_detect(ROCKER_PIN, GPIO.BOTH, callback=on_flip, bouncetime=BOUNCE_MS) print("Watching the rocker switch module on GPIO25. Press Ctrl + C to stop.") print("{} start position: {}".format(clock(), "ON" if last_state == GPIO.HIGH else "OFF")) try: while True: time.sleep(1) # the main code has nothing to do: the callback handles every flip except KeyboardInterrupt: print("\nScript stopped") finally: GPIO.cleanup() # stops the event detection and releases GPIO25
  • Save the file and run it with this command:
python3 rocker_switch_module_events.py
  • Flip the rocker to "I", wait a few seconds, and flip it back to "O". Do this twice, at your own pace.
  • Check the terminal:
PuTTY - Raspberry Pi
Watching the rocker switch module on GPIO25. Press Ctrl + C to stop. 14:02:27 start position: OFF 14:02:31 switched ON 14:02:46 switched OFF 14:03:05 switched ON 14:03:09 switched OFF

The first line with a time shows where the rocker was when the script started. After that, every line belongs to one flip, and the clock tells you when it happened: here the switch was ON for 15 seconds the first time and for 4 seconds the second time. Between flips, the terminal stays quiet and the script uses almost no CPU, because the main loop sleeps for one second at a time. Press Ctrl + C keys to stop the script. The finally part calls GPIO.cleanup(), which also removes the event detection from GPIO25.

※ NOTE THAT:

If the script stops with RuntimeError: Failed to add edge detection (a recent Raspberry Pi OS with a newer Linux kernel), or with Cannot determine SOC peripheral base address (Raspberry Pi 5), the old RPi.GPIO package does not support your system. Replace it with rpi-lgpio. It is a drop-in replacement, so both scripts on this page stay exactly the same.

sudo apt-get remove python3-rpi.gpio sudo apt-get install python3-rpi-lgpio

Code Explanation

Check out the line-by-line explanation contained in the comments of the source code!

Additional Knowledge

Rocker Switch Module vs Bare ON/OFF Switch

The Raspberry Pi - Switch tutorial uses a bare 2-leg ON/OFF switch. Let's compare it with the module:

Rocker Switch Module Bare 2-leg ON/OFF Switch
Wires to the Pi 3 (SIG, VCC, GND) 2 (one leg to a GPIO pin, one leg to GND)
Pull resistor 10 kOhm pull-down on the board the internal pull-up of the Pi
GPIO setup pull_up_down=GPIO.PUD_OFF pull_up_down=GPIO.PUD_UP
Reading when ON 1 (HIGH), no inverted logic 0 (LOW), the logic is inverted
Pin labels SIG, VCC and GND printed on the board none, the two legs are the same
Connection header pins for jumper wires wires soldered to the legs

Evidently, the module is the quicker choice on the desk: three plug-in wires, and 1 means ON. The bare switch needs one wire less and fits into a panel, but you have to solder it, and you must remember that 0 means ON.

Project Ideas with the Rocker Switch Module

  • Arm switch for a motion camera: while the rocker is on "I", the script saves a photo each time motion is seen. On "O", it ignores motion.
  • Master switch for a relay: the Pi turns a fan or a lamp on through a relay only while the rocker is ON. The load current flows through the relay, never through the module.
  • Quiet hours: on "O", the Pi stops sending messages to your phone, for example at night.
  • Usage log: append each "switched ON" and "switched OFF" line of the second script to a CSV file, and later count how many hours a day your project was in use.

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!