Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Arduino: Toggle LED with breadboard push button
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Button toggles LED off and on
Using an Arduino MEGA 2560 (from here on referred to as the MEGA)
and associated electronic components, create a hardware and software solution that
will turn on an LED when a momentary button is pressed and then turn off the light
when the button is pressed again.
The circuit:
- LED attached from pin 12 with inline 1k Ω to ground
- pushbutton attached to pin 9 from +5V to ground
created 2020-01-19
Steven Combs (
// Integer variables
int ledPin = 12; // LED to PIN 12 (+5V) to ground on MEGA
int buttonPin = 9; // Button on PIN 9 (+5V) to ground on MEGA
int toggleState = false; // Button toggle is off
void setup() // Configure devices
pinMode(ledPin, OUTPUT); // ledPin as output device
pinMode(buttonPin, INPUT_PULLUP); // buttonPin as input with a pullup resistor
void loop() // Main loop
if (digitalRead(buttonPin) == false) {
toggleState = !toggleState; // Reverse current state of variable (false <-> true)
digitalWrite(ledPin, toggleState); // LED to toggleState
while (digitalRead(buttonPin) == false);
delay(50); // Add a necessary time delay of 50ms
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment