Arduino Mega - Rocker Switch Module

An Arduino Mega often runs the long jobs: a weather station that writes a reading every few seconds, or a test bench that records data all night. Sooner or later, you want to stop the log for a moment - to move a sensor, change a battery, or just read the screen in peace - without pulling out the USB cable. A rocker switch on the front of the box is the classic answer. The DIYables ON/OFF Rocker Switch Module gives you one that comes ready-made on a little PCB, with printed pin names. This tutorial instructs you how to use the Arduino Mega to read the rocker switch module and let it start and stop a simple logger. In detail, we will learn:

Arduino Mega rocker switch module - pause and resume a serial uptime logger

We suggest:

Hardware Preparation

1×Arduino MEGA
1×Alternatively, DIYables MEGA Development Board
1×USB 2.0 cable type A/B (for USB-A PC)
1×USB 2.0 cable type C/B (for USB-C PC)
1×ON/OFF Rocker Switch Module
1×Jumper Wires
1×Recommended: Screw Terminal Block Shield for Arduino Uno/Mega
1×Recommended: Sensors/Servo Expansion Shield for Arduino Mega
1×Recommended: Breadboard Shield for Arduino Mega
1×Recommended: Enclosure for Arduino Mega

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 and Its Pinout

Rocker switch module pinout - three header pins named SIG, VCC and GND on the DIYables board
image source: diyables.io

If you have ever turned on a power strip, you have already used a rocker switch. In this DIYables module, that kind of switch - a black KCD1 rocker - is mounted on a square blue PCB, roughly 24mm on each side. Four corner holes let you bolt the module behind a panel. Along one edge, a 3-pin header with right-angle pins points sideways for the jumper wires.

Two symbols are printed on the rocker itself: "I" (ON) and "O" (OFF). The text "ON (H)" and "OFF (L)" next to it on the PCB adds the electrical meaning - in other words, the Mega sees HIGH when the switch is ON and LOW when it is OFF.

The most important thing about this switch is that it remembers. Whichever side you push down, that side holds - for a minute or for a year - until somebody pushes the other side. People call this a maintained (or latching) switch. Compare it with a push button, which gives ON just as long as your finger stays on it. For that reason, the rocker code never waits for a click. It looks at the present position, and it only acts when that position differs from the last one.

Electrically, it is an SPST switch (single pole, single throw): one contact, closed or open. Closed, it links SIG straight to VCC. Open, it leaves SIG to a 10 kOhm pull-down resistor on the module (the tiny part marked "103"), which drags the line to 0V. Pin 7 of the Mega therefore never floats, and no extra resistor goes into your wiring.

ON/OFF Rocker Switch Module
Rocker KCD1 type, black, marked I and O
Contact Type SPST (single pole, single throw)
Action maintained (latching) - holds "I" or "O"
Power (VCC) 3.3V to 5V
Output on SIG VCC level when ON, 0V when OFF
Pull-down 10 kOhm on SIG, printed "103"
Pins 3-pin male header, right-angle, 2.54mm pitch
Board about 24 x 24mm with 4 mounting holes
Size with Header about 24 x 29 x 22mm
Package 5 modules

Do not let the "6A 250VAC / 10A 125VAC" stamp fool you. It belongs to the switch as a separate part. On this module, the job is much smaller: sending a logic level to an input pin. Keep mains wiring and motor current away from its header.

Flip the module over and you find the three pin names, printed beside the header:

  • SIG pin: must be connected to one of the digital pins of the Arduino Mega - this tutorial uses pin 7. With "I" down, SIG is at the VCC voltage (HIGH). With "O" down, SIG is at 0V (LOW).
  • VCC pin: must be connected to 3.3V or 5V on the Mega. Whichever you choose also becomes the HIGH voltage on SIG.
  • GND pin: must be connected to one of the GND pins (0V).

※ NOTE THAT:

The pin order is not the same on every rocker module on the market. Before you plug in the jumper wires, turn the board over and match each wire to its printed name.

Wiring Diagram

Only three wires run between the module and the Mega: one for power, one for ground and one for the signal. The diagram feeds VCC from the 3.3V pin and sends SIG to digital pin 7.

The wiring diagram between Arduino Mega rocker switch module

This image is created using Fritzing. Click to enlarge image

Rocker Switch Module Arduino Mega
GND GND
VCC 3.3V (or 5V)
SIG Pin 7

※ NOTE THAT:

  • The Arduino Mega works with 5V logic, so you may also move the VCC wire to the 5V pin. SIG then gives 5V instead of 3.3V when the switch is ON. The Mega reads both as HIGH.
  • Pin 7 is only an example. The long double header of the Mega (pins 22 to 53) has plenty of free inputs. If you move the SIG wire, update ROCKER_SIG_PIN in the sketch as well.

How To Program For Rocker Switch Module

Only built-in calls are used, so no library has to be installed.

  • First, give pin 7 a name that says what is wired to it. Should the SIG wire move to another pin later, this is the only line to edit:
#define ROCKER_SIG_PIN 7
  • Inside setup(), set that pin up with pinMode(). Choose INPUT, not INPUT_PULLUP. While the rocker rests on "O", the 10 kOhm resistor keeps SIG at a clean 0V by itself:
pinMode(ROCKER_SIG_PIN, INPUT);
  • Call digitalRead() to get the present position. It returns HIGH for "I" and LOW for "O":
if (digitalRead(ROCKER_SIG_PIN) == HIGH) { // ON: put the job for the "I" position here }
  • The logger must also catch the moment of a flip. A moving rocker does not give one clean edge: for a few milliseconds the contacts bounce, and one flip may look like three or four. The cure is a short waiting rule. Each time the raw level moves, note the time. Only when the level has not moved for 50 milliseconds does it count as the new state. millis() keeps the time, and nothing in the loop has to pause:
if (reading != lastReading) { // the raw level moved: note the time lastChangeTime = millis(); lastReading = reading; } if (millis() - lastChangeTime >= 50 && reading != loggingState) { loggingState = reading; // quiet for 50 ms: a real flip }

Arduino Mega Code for Rocker Switch Module - Wiring Test with the Raw Pin Value

Before you build the logger, check the wiring with a short test. Every 300 milliseconds, this sketch reads pin 7 and writes one line: the position in words (ON or OFF) next to the number from digitalRead() (1 or 0). At this slow pace, no debounce is needed, because any contact bounce has died away long before the next reading.

/* * This Arduino Mega code was developed by newbiely.com * * This Arduino Mega code is made available for public use without any restriction * * For comprehensive instructions and wiring diagrams, please visit: * https://newbiely.com/tutorials/arduino-mega/arduino-mega-rocker-switch-module */ #define ROCKER_SIG_PIN 7 // The Arduino Mega pin wired to the SIG pin of the rocker switch module void setup() { Serial.begin(9600); pinMode(ROCKER_SIG_PIN, INPUT); // plain INPUT: the 10k pull-down on the module keeps SIG LOW while the switch is OFF } void loop() { int sigLevel = digitalRead(ROCKER_SIG_PIN); // 1 = rocker on "I" (ON), 0 = rocker on "O" (OFF) Serial.print("Rocker switch: "); if (sigLevel == HIGH) Serial.print("ON "); else Serial.print("OFF"); Serial.print(" | pin 7 = "); Serial.println(sigLevel); delay(300); // about three readings per second - plenty for a switch that stays where you put it }

Detailed Instructions

  • New to the Arduino Mega? Install the Arduino IDE on your computer first. Support for the Mega is built in, so you do not need an extra board package.
  • Plug the three jumper wires in as shown in the wiring diagram.
  • Use the USB cable to connect the Arduino Mega to your computer.
  • Start the Arduino IDE.
  • In the Tools menu, choose Arduino Mega or Mega 2560 as the board, then choose the COM port of the Mega.
  • Paste the code above into an empty sketch window.
  • Click the Upload button and wait for the upload to finish.
  • Open the Serial Monitor and choose 9600 baud in its baud list.
  • Start with "O" pressed down. After about a second, rock the switch to "I", hold on for two seconds, then go back to "O".
∞
Newbiely | Arduino IDE 2.3.8
──
☐
✕
File
Edit
Sketch
Tools
Help
Arduino Mega Or...
Newbiely.ino
···
8 Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'Arduino Mega Or...' on 'COM15')
New Line
9600 baud
Rocker switch: OFF | pin 7 = 0 Rocker switch: OFF | pin 7 = 0 Rocker switch: OFF | pin 7 = 0 Rocker switch: OFF | pin 7 = 0 Rocker switch: ON | pin 7 = 1 Rocker switch: ON | pin 7 = 1 Rocker switch: ON | pin 7 = 1 Rocker switch: ON | pin 7 = 1 Rocker switch: ON | pin 7 = 1 Rocker switch: ON | pin 7 = 1 Rocker switch: ON | pin 7 = 1 Rocker switch: OFF | pin 7 = 0 Rocker switch: OFF | pin 7 = 0
Ln 11, Col 1
Arduino Mega Or... on COM15
2

Nothing changes until you rock the switch to the other side. Until then, the same line keeps coming back - the rocker simply stays put.

Does the line say OFF no matter which side is down? Then the VCC wire is usually missing or on the wrong pin. If ON and OFF swap by themselves while nobody touches the switch, pin 7 is floating: push the SIG wire firmly into pin 7 and onto the SIG pin of the module.

Arduino Mega Code for Rocker Switch Module - Logging Switch with Uptime Stamps

Here the rocker earns its place on the front panel. In this sketch, it is the logging switch of a small logger:

  • Rocker on "I": the Mega prints a log line every 2 seconds. Each line starts with its uptime, for example [00:01:24]. The uptime is the time since the board started. The sketch works it out from millis() and shows it as hours, minutes and seconds. The "L" LED on the board (LED_BUILTIN, pin 13) stays lit, like the REC lamp of a recorder.
  • Flip to "O": the Mega prints "Logging paused" one time, turns the LED off and stays quiet.
  • Flip back to "I": it prints "Logging resumed" and goes on with the next entry number.

In this demo, each log line only carries an entry number. In a real project, you would put a sensor value there. The flip is checked with the 50 ms millis() rule from above, so one flip never prints two messages. And because the loop never calls delay(), a flip is noticed within a few milliseconds - the Mega does not have to finish a 2-second wait first. The Arduino Mega - LED - Blink Without Delay tutorial explains this millis() style of timing in more detail.

/* * This Arduino Mega code was developed by newbiely.com * * This Arduino Mega code is made available for public use without any restriction * * For comprehensive instructions and wiring diagrams, please visit: * https://newbiely.com/tutorials/arduino-mega/arduino-mega-rocker-switch-module */ #define ROCKER_SIG_PIN 7 // The Arduino Mega pin wired to the SIG pin of the rocker switch module #define REC_LED_PIN LED_BUILTIN // the "L" LED on the Mega board (pin 13): lit while logging is ON #define DEBOUNCE_MS 50 // a new switch level must stay the same this long before it counts #define LOG_INTERVAL_MS 2000 // one log line every 2 seconds while logging is ON int loggingState; // the accepted (debounced) switch state: HIGH = log, LOW = pause int lastReading; // the raw level seen in the previous loop unsigned long lastChangeTime = 0; // when the raw level last moved unsigned long lastLogTime = 0; // when the last log line was printed unsigned long entryCount = 0; // how many log lines have been printed so far // Print one log line that starts with the uptime of the Mega as [hh:mm:ss] void printLogLine(unsigned long now) { unsigned long totalSeconds = now / 1000; unsigned long hours = totalSeconds / 3600; unsigned long minutes = (totalSeconds / 60) % 60; unsigned long seconds = totalSeconds % 60; entryCount++; char line[48]; sprintf(line, "[%02lu:%02lu:%02lu] logging - entry %lu", hours, minutes, seconds, entryCount); Serial.println(line); } void setup() { Serial.begin(9600); pinMode(ROCKER_SIG_PIN, INPUT); // plain INPUT: the module has its own pull-down resistor pinMode(REC_LED_PIN, OUTPUT); Serial.println("Mega logger ready - rocker on I = log, O = pause"); loggingState = digitalRead(ROCKER_SIG_PIN); // the rocker may already be ON at power-up lastReading = loggingState; digitalWrite(REC_LED_PIN, loggingState); // LED on = logging if (loggingState == HIGH) Serial.println("Logging started"); else Serial.println("Logging paused - flip the rocker to I to start"); lastLogTime = millis(); } void loop() { unsigned long now = millis(); int reading = digitalRead(ROCKER_SIG_PIN); // 1) Debounce: start timing again every time the raw level moves if (reading != lastReading) { lastChangeTime = now; lastReading = reading; } // 2) Steady for 50 ms and not the same as the accepted state: the rocker was really flipped if (now - lastChangeTime >= DEBOUNCE_MS && reading != loggingState) { loggingState = reading; digitalWrite(REC_LED_PIN, loggingState); if (loggingState == HIGH) { if (entryCount == 0) Serial.println("Logging started"); else Serial.println("Logging resumed"); lastLogTime = now; // the next line comes 2 seconds after the flip } else { Serial.println("Logging paused"); } } // 3) While logging is ON, print one line every 2 seconds if (loggingState == HIGH && now - lastLogTime >= LOG_INTERVAL_MS) { lastLogTime = now; printLogLine(now); } }

Detailed Instructions

  • No new wires are needed: the "L" LED is part of the Mega board.
  • Paste this sketch over the old one in the Arduino IDE, then click Upload.
  • Set the rocker to "I", then bring up the Serial Monitor at 9600 baud. Missing the first lines? Tap RESET on the Mega once.
  • Let it log for about ten seconds. Flip the rocker to "O" for a while, then flip it back to "I".
∞
Newbiely | Arduino IDE 2.3.8
──
☐
✕
File
Edit
Sketch
Tools
Help
Arduino Mega Or...
Newbiely.ino
···
8 Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'Arduino Mega Or...' on 'COM15')
New Line
9600 baud
Mega logger ready - rocker on I = log, O = pause Logging started [00:00:02] logging - entry 1 [00:00:04] logging - entry 2 [00:00:06] logging - entry 3 [00:00:08] logging - entry 4 [00:00:10] logging - entry 5 [00:00:12] logging - entry 6 Logging paused Logging resumed [00:00:33] logging - entry 7 [00:00:35] logging - entry 8 [00:00:37] logging - entry 9
Ln 11, Col 1
Arduino Mega Or... on COM15
2

Look at the time after the pause: it jumps from 00:00:12 to 00:00:33. The clock shows how long the Mega has been running, so it keeps counting while the log is paused. The entry number only grows while logging is ON.

If the rocker is on "O" when the Mega starts, the second line says that the log is paused, and the first flip to "I" prints "Logging started" instead of "Logging resumed".

Additional Knowledge

Which ON/OFF Input Fits Your Mega Project?

The Arduino Mega tutorials cover three inputs that look alike. This table helps you pick the right one:

Bare 2-Leg ON/OFF Switch Rocker Switch Module Button Module
Memory of position yes, latching yes, latching no, momentary
How it connects 2 soldered legs 3-pin labeled header 3-pin labeled header
Input mode in the code INPUT_PULLUP INPUT INPUT
Reading in the ON position LOW (upside down) HIGH HIGH while held
Where the resistor comes from inside the ATmega2560 chip 10 kOhm on the module on the module
Best job a power switch in the wall of a case a mode that lasts, like log or pause a short command, like start or next

It is evident that a rocker module wins whenever a setting must last: no soldering, no resistor to add, and ON simply reads as HIGH. Pick the bare ON/OFF switch when it has to sit in the wall of a case, and the button module when the input is a quick press.

Why Only the Logger Debounces

The first sketch reads the pin once every 300 ms. Contact bounce dies away within a few milliseconds, so a reading almost never lands in the middle of it. And if one does, the next line, 300 ms later, is correct again. The logger is different: it prints a message at each change. Without the 50 ms rule, one flip could print "Logging paused", "Logging resumed" and "Logging paused" in a row.

Ideas for the Logger

  • Save the lines on a memory card instead of the Serial Monitor - see Arduino Mega - Micro SD Card. Flip the rocker to "O" before you take the card out, so no line is being written at that moment.
  • Replace the entry number with a real reading, for example a temperature, and change LOG_INTERVAL_MS to log more or less often.
  • Use more than one rocker module on the same Mega: one for logging, one to mute a buzzer, one to choose between auto and manual mode. Each module only needs its own input pin.

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!