How to toggle an LED using a switch in Arduino? Simplest code without de-bouncing - Yash Vidyasagar
Aviation Industry Default Image

How to toggle an LED using a switch in Arduino? Simplest code without de-bouncing

This code is the simplest code to toggle an LED using a switch using Arduino UNO or Arduino Nano. Be careful about the connections of resistor, switch and LED together.

Just use the following code, burn it in your Arduino and run the project.

Its that simple…!

/*
 * Simple code to toggle an LED using a button
 * Program written by: Yash Vidyasagar
 * Tested on Arduino UNO and Arduino Nano with following connections:
 * LED attached from pin 13 to ground
 * pushbutton attached to pin 2 from +5V
 * 10K resistor attached to pin 2 from ground
 * Note: on most Arduinos there is already an LED on the board 
 * to pin-13
 * You can connect 5V relay to this pin w.r.t. ground to toggle 
 * high voltage devices like 230V fan or tubelight, etc.
 * 
 * IMPORTANT NOTE:
 * WE ARE IGNORING THE DEBOUNCING OF THE BUTTON IN THIS PROJECT.
 */

const int Button=2; // the number of the pushbutton pin
const int Output_pin=13; // the number of the LED pin

void setup() 
{
  pinMode(Output_pin,OUTPUT);
  pinMode(Button,INPUT);
}

void loop() 
{
  digitalWrite(Output_pin,!digitalRead(Button));
}

The following code line is the actual outcome of this code.

digitalWrite(Output_pin,!digitalRead(Button));

Enjoy….!

Leave a Reply