Push button with LED - Arduino Nano Tutorial

In this Arduino Nano tutorial, we will illustrate how to use Push Button to control a LED. When the push button is pressed the LED will turn on otherwise the LED will remain off. 

To turn on/off a led when push button is pressed, we must read the state of the push button. To read the state of the push button we can use digitalRead() function. And to turn on/off the led we can use the digitalWrite() function. The digitalWrite() function was explained previously in the LED blink Arduino Nano Tutorial.

Hardware Components/Materials Required

Push button with LED - Arduino Nano Tutorial

The following are the materials required for this tutorial:

- Arduino Nano
- LED
- 220Ohm resistor
- Push Button
- Connecting Wires
- Breadboard
- USB cable
- Arduino IDE

Interfacing Arduino Nano with Push Button and LED

The push button is connected to digital pin 9 of the Arduino Nano. The LED is connected to the pin 2 via a 220Ohm current limiting resistor to the ground. 
The Schematic diagram of Arduino Nano Push Button and LED interfacing is shown below.

Schematic diagram of Arduino Nano Push Button and LED interfacing

On the breadboard it looks like the following.

Push button LED Arduino Nano Breadboard

Programming Push Button and LED with Arduino Nano


Below is program code that reads the state of the push button connected to pin 9 using digitalRead() function and outputs either on(HIGH) or off(LOW) using digitalWrite() function to the LED connected to pin 2. For this purpose we have used the while() statement that checks whether the push button input is high or low. If the push button input is LOW then output signal to the LED is made HIGH and hence turns on the LED. Otherwise the LED stays off. Notice that we have set up the internal pull-up resistor so the initial state of the push button will be HIGH.

const int ledpin = 2;
const int pushbtn = 9;

void setup() {
  // put your setup code here, to run once:
  pinMode(ledpin, OUTPUT);
  pinMode(pushbtn, INPUT_PULLUP);
}

void loop() {
  // put your main code here, to run repeatedly:
  while(!digitalRead(pushbtn)){
    digitalWrite(ledpin,HIGH);
    }
   digitalWrite(ledpin, LOW);
}

Post a Comment

Previous Post Next Post