Raspberry Pi: Push Button LED

This is another simple beginner project where a LED tuns on as long as the push button is pressed.

Check out other Raspberry Pi Projects here: (LINK)

Demo:

Things Required:

  1. Raspberry Pi (I’ve used Raspberry Pi 3)
  2. Keyboard
  3. Mouse
  4. HDMI Screen
  5. Push button
  6. Jumper Wires
  7. LED
  8. 1 k ohm resistor

Reference Material:

  1. Link to the article that I followed: (LINK)

Code:

Note that the following code is in python!

View on/Download from Github: (LINK)

#!/usr/bin/python3

import RPi.GPIO as GPIO
import time

button = 16
led = 18

def setup():
    GPIO.setmode(GPIO.BOARD)
    GPIO.setup(button, GPIO.IN, pull_up_down=GPIO.PUD_UP)
    GPIO.setup(led, GPIO.OUT)

def loop():
    while True:
        Button_state= GPIO.input(button)
        if Button_state == False:
            GPIO.output(led, True)
            print("Button Pressed")
            while GPIO.input(button)==False:
                time.sleep(0.2)

        else:
            GPIO.output(led, False)

def endprogram():
    GPIO.output(led, False)
    GPIO.cleanup()


if __name__ == '__main__':
    setup()
    try:
        loop()
    except KeyboardInterrupt:
        print("Keyboard Interrupt Detetcted")
        endprogram()

Stay Tuned for upcoming posts on Raspberry Pi Projects! Want to be the first to know when a new and amazing post comes up?? Then feel free to subscribe!

Happy Learning!!

This image has an empty alt attribute; its file name is stay-tuned.gif

Leave a Reply

PHP JS HTML CSS BASH PYTHON CODE

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: