With 54 digital pins, the Arduino Mega is a natural choice for projects that take a lot of input: an arcade cabinet, a quiz buzzer system for several players, or a machine panel with START, STOP and MODE keys. Each of those keys can be a button module. It is a ready-made board with a push button, a colored cap and its own resistor, so it plugs straight into the Mega with three wires. This tutorial instructs you how to use the Arduino Mega to read a button module, step by step. In detail, we will learn:
Which parts sit on the button module and what its VCC, OUT and GND pins do
How to wire the button module to the Arduino Mega, with no extra resistor
How to program the Arduino Mega to print the raw HIGH/LOW level of the button
How to program the Arduino Mega to detect each press and each release, using a short delay to filter out bouncing
How to use the ezButton library to debounce the button without stopping the rest of the program
We suggest:
Reading the Arduino Mega - Button tutorial if you want to use a bare 4-leg push button with your own resistor.
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 Button Module and Its Pinout
image source: diyables.io
In short, the button module is "a push button with its resistor already on board". A momentary tactile switch is soldered on a small PCB and topped with a colored cap. While nobody touches it, a pull-down resistor on the board keeps the OUT pin at LOW. When you push the cap, the switch connects OUT to VCC, so the pin goes HIGH. When you let go, it falls back to LOW. Like every mechanical switch, the metal contacts bounce for a few milliseconds when they close or open. During that short time, one press can look like several presses to the Arduino Mega - the second and third code examples below deal with this.
Button Module
Operating Voltage
3.3V to 5V DC
Switch Type
Momentary tactile push button
Header
3-pin, 2.54mm pitch
Onboard Resistor
Pull-down on the OUT line
Output Logic
Active HIGH (pressed = HIGH, released = LOW)
Pack
5 modules, cap colors red, yellow, green, blue and white
The three pins are printed on the board in this order:
VCC pin: must be connected to the 3.3V pin or the 5V pin of the Arduino Mega. This is also the voltage that OUT gives when the button is pressed, and the 5V logic of the Mega reads both levels as HIGH.
OUT pin: must be connected to a digital input pin of the Arduino Mega. It reads HIGH while the button is held down and LOW while it is free.
GND pin: must be connected to GND (0V)
※ NOTE THAT:
The arrangement of pins on a module may differ from one manufacturer to another. Read the labels printed beside the header before you connect anything, and wire by label, not by position.
Wiring Diagram
The button module needs just three jumper wires. Its VCC goes to the 3.3V pin (or the 5V pin), OUT goes to digital pin 7, and GND goes to one of the GND pins of the Arduino Mega.
This image is created using Fritzing. Click to enlarge image
Button Module
Arduino Mega
VCC
3.3V (or 5V)
OUT
Pin 7
GND
GND
How To Program For Button Module
The first step is to give a name to the Arduino Mega pin that is connected to the OUT pin of the module:
#define BUTTON_MODULE_PIN 7
Set that pin as a plain input in setup(). Do not use INPUT_PULLUP here - the module already has a pull-down, and an internal pull-up would work against it:
pinMode(BUTTON_MODULE_PIN, INPUT);
Read the pin. The value is HIGH while the button is pressed and LOW while it is released:
int state = digitalRead(BUTTON_MODULE_PIN);
Arduino Mega Code for Button Module - Read the Raw State
This first sketch reads pin 7 five times per second and writes the level it finds to the Serial Monitor. Nothing is filtered yet, so you see exactly what the module puts on its OUT pin.
/* * 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-button-module */#define BUTTON_MODULE_PIN 7 // The Arduino Mega pin wired to the OUT pin of the button modulevoidsetup() {Serial.begin(9600);pinMode(BUTTON_MODULE_PIN, INPUT); // plain INPUT: the module already has its own pull-down resistor}voidloop() {int state = digitalRead(BUTTON_MODULE_PIN); // HIGH = pressed, LOW = releasedif (state == HIGH)Serial.println("OUT pin: HIGH -> button held down");elseSerial.println("OUT pin: LOW -> button not touched");delay(200); // slow the printing down so the Serial Monitor is easy to read}
Wire the button module to the Arduino Mega as shown in the diagram.
Connect the Arduino Mega board to your computer using a USB cable.
Open Arduino IDE on your computer.
Select the Arduino Mega or Mega 2560 board and the right COM port.
Paste the code above into a new sketch.
Click the Upload button and wait until the upload is done.
Open the Serial Monitor, then hold the button down for about one second and let it go.
Newbiely | Arduino IDE 2.3.8
──
☐
✕
File
Edit
Sketch
Tools
Help
Arduino Mega Or...
Newbiely.ino
···
8Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'Arduino Mega Or...' on 'COM15')
New Line
9600 baud
OUT pin: LOW -> button not touched
OUT pin: LOW -> button not touched
OUT pin: HIGH -> button held down
OUT pin: HIGH -> button held down
OUT pin: HIGH -> button held down
OUT pin: HIGH -> button held down
OUT pin: HIGH -> button held down
OUT pin: LOW -> button not touched
OUT pin: LOW -> button not touched
Ln 11, Col 1
Arduino Mega Or... on COM15
2
The line stays LOW at rest and turns HIGH only while your finger is on the cap. This proves the onboard pull-down is doing its job - there is no random flickering between the two values.
Arduino Mega Code for Button Module - Press and Release Events with Delay Debounce
Most projects do not care about the level itself. They want to know the moment the button goes down (for example, to start a motor) or comes up (for example, to stop a timer). This sketch remembers the last confirmed state. When the reading changes, it waits 50 milliseconds, reads the pin again, and only accepts the change if it is still there. That second read is what filters out the bouncing. Keep in mind that delay() blocks the loop: during those 50 milliseconds, the Arduino Mega does nothing else.
/* * 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-button-module */#define BUTTON_MODULE_PIN 7 // The Arduino Mega pin wired to the OUT pin of the button module#define DEBOUNCE_DELAY 50 // milliseconds to wait for the contacts to settleint lastState = LOW; // the module idles LOW because of its onboard pull-downvoidsetup() {Serial.begin(9600);pinMode(BUTTON_MODULE_PIN, INPUT);}voidloop() {int reading = digitalRead(BUTTON_MODULE_PIN);if (reading != lastState) { // something changed - maybe a real press, maybe a bouncedelay(DEBOUNCE_DELAY); // wait until the bouncing is over (the loop stops here) reading = digitalRead(BUTTON_MODULE_PIN); // read the pin a second timeif (reading != lastState) { // the change is still there, so it is realif (reading == HIGH)Serial.println("The button is pressed");elseSerial.println("The button is released"); lastState = reading; // remember the confirmed state } }}
Detailed Instructions
Keep the wiring from the previous example.
Replace the old sketch in the Arduino IDE with the code above and click Upload.
Open the Serial Monitor and give the button three separate presses.
Newbiely | Arduino IDE 2.3.8
──
☐
✕
File
Edit
Sketch
Tools
Help
Arduino Mega Or...
Newbiely.ino
···
8Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'Arduino Mega Or...' on 'COM15')
New Line
9600 baud
The button is pressed
The button is released
The button is pressed
The button is released
The button is pressed
The button is released
Ln 11, Col 1
Arduino Mega Or... on COM15
2
Three presses give exactly three pairs of messages. Without the second read, a single press could print "pressed" two or three times in a row.
Arduino Mega Code for Button Module - Non-blocking Debounce with ezButton
A 50ms pause is fine for one button. But on a Mega that also drives a display, a stepper motor or ten more buttons, those pauses add up and the program feels slow. The ezButton library solves this. It checks the time with millis() on every call, so button.loop() returns at once and never stops the program. Because the module uses a pull-down, the button object is created with EXTERNAL_PULLDOWN, which tells ezButton that HIGH means pressed. This option needs ezButton version 1.0.6 or newer.
The key functions are:
Button.setDebounceTime(50) - sets the filter time in setup()
Button.loop() - must be the first line in loop()
Button.isPressed() / button.isReleased() - true once for each press or release
Button.getState() - the steady, debounced level (HIGH or LOW)
/* * 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-button-module */#include <ezButton.h>#define BUTTON_MODULE_PIN 7 // The Arduino Mega pin wired to the OUT pin of the button module// EXTERNAL_PULLDOWN tells ezButton that the module has its own pull-down,// so HIGH means pressed and LOW means releasedezButtonbutton(BUTTON_MODULE_PIN, EXTERNAL_PULLDOWN);int lastSteadyState = -1; // used to print the steady state only when it changesvoidsetup() {Serial.begin(9600);button.setDebounceTime(50); // ignore changes shorter than 50 milliseconds}voidloop() {button.loop(); // MUST be called first in every loop - it never blocksif (button.isPressed())Serial.println("The button is pressed");if (button.isReleased())Serial.println("The button is released");int steadyState = button.getState(); // the debounced state: HIGH or LOWif (steadyState != lastSteadyState) {Serial.print("Steady state: ");Serial.println(steadyState == HIGH ? "HIGH (held)" : "LOW (free)"); lastSteadyState = steadyState; }// other tasks can run here without waiting for the button}
Detailed Instructions
Click the Libraries icon on the left bar of the Arduino IDE.
Type ezButton in the search box and find the ezButton library by ArduinoGetStarted.com.
Click Install. If an older version is already installed, update it to 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
Arduino Mega Or...
Library Manager
ezButton
Type:
All
Topic:
All
ezButtonby 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
voidsetup() {
Output
Serial Monitor
Ln 1, Col 1
Arduino Mega Or... on COM15
1
Copy the code above into the Arduino IDE and click Upload.
Open the Serial Monitor. Press the button once, then press and hold it for a moment before you release it.
Newbiely | Arduino IDE 2.3.8
──
☐
✕
File
Edit
Sketch
Tools
Help
Arduino Mega Or...
Newbiely.ino
···
8Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'Arduino Mega Or...' on 'COM15')
New Line
9600 baud
Steady state: LOW (free)
The button is pressed
Steady state: HIGH (held)
The button is released
Steady state: LOW (free)
The button is pressed
Steady state: HIGH (held)
The button is released
Steady state: LOW (free)
Ln 11, Col 1
Arduino Mega Or... on COM15
2
The first line comes right after the upload, before you touch anything. After that, each press and each release prints one event message and one steady-state message - never a duplicate.
Additional Knowledge
Should you use a button module or a bare push button on the Arduino Mega?
Bare 4-leg Push Button
Button Module
Resistor
You must add a pull-down or pull-up, or use INPUT_PULLUP
Pull-down already on the board
Pins
4 legs, joined in pairs - easy to wire wrongly
3 labeled pins (VCC, OUT, GND)
Logic with INPUT_PULLUP
Inverted (pressed = LOW)
Not inverted (pressed = HIGH)
Mounting
Breadboard or soldered on a PCB
Jumper wires to the header
It is evident that the button module is the easier choice for beginners and for quick builds, while a bare push button is cheaper and smaller when you need dozens of keys on one board.
If your project needs several buttons, give each module its own Mega pin and its own ezButton object. Since the module output is active HIGH, every object should use EXTERNAL_PULLDOWN. A five-pack of different cap colors makes it easy to tell the keys apart - for example, green for START, red for STOP and blue for MODE.
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!