Skip to content

Instantly share code, notes, and snippets.

@stevencombs
Last active March 3, 2020 00:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stevencombs/b988f757c5ffd8cc99d3177b56b62118 to your computer and use it in GitHub Desktop.
Save stevencombs/b988f757c5ffd8cc99d3177b56b62118 to your computer and use it in GitHub Desktop.
Arduino: Toggle LED with breadboard push button
Display the source blob
Display the rendered blob
Raw
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 (https://www.stevencombs.com)
*/
// 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