Buttons and LEDs with Raspberry pi
Hey, hello everyone hopes you guys are doing well. Today in this lesson we will learn how we can take input from a push button in our Raspberry Pi. We will make a modular code which helps us to automate or control LEDs and other peripherals. So without any further due let’s start.
So first of all you need some components to follow me along with this lesson. Those components are :
- 1 push switch
- 1 LED
- 5 jumper wires
- 1 breadboard
I assumed that you guys setup your Raspberry Pi with the raspbian OS properly if not then go through my previous post about How to setup your Raspberry pi . Now after the setup process is done simply fire up any of your python editor and make a new file namely button_control_led.py and copy this block of code inside that file.
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BOARD) GPIO.setup(8, GPIO.OUT) GPIO.setup(7, GPIO.IN, pull_up_down=GPIO.PUD_UP) while True: if GPIO.input(7)== 0: print("Led pussed") GPIO.output(8, True) print("Led On") time.sleep(.5) else: GPIO.output(8, False) print("Led Off") time.sleep(.5)
Now simply save this file and prepare the connections as per the diagram given below. In this diagram, it may confuse you as we connect one side of the switch to the GPIO pin and another side to the GND instead of +5v or VCC. The reason why we do so is that we use the digital input pull-up concept. Note: while making the connections power off your Pi and always double-check the connections before power it up.
Now when you are done with all the connections and programming let’s run it and see what will we get from this setup. And to run the program simply click the Run button on your editor or run this command on the terminal.
~$ python3 button_control_led.py
And after that you can see when only you press the button then only the light glows otherwise the led remains off.
Now let’s understand how everything works?
So I hope everything works properly on your side but if you have any problem or question, simply put that in the comments section below. Also hope you learn something new today, if so don’t forget to share this in your community and leave a message below. Stay Home Stay Safe!