Print Friendly, PDF & Email

Difficulty level: Beginner

Approx reading time:

Components Required:

1. Raspberry Pi 3 model B

2. MicroSD card 8 or 16 GB (Class 4 and above) with Raspbian

3. Windows PC / Linux PC (Tested on Windows 10, Ubuntu 14.04 LTS)

4. Ethernet cable (Category 5 – also called Cat 5)

5. Micro USB cable

6. Breadboard

7. 5 mm LED (your favourite colour)

8. 220 Ohms Resistor (colour code: Red, Red, Brown)

9. Push Button

9. 4 Male to Female (Red – power/GPIO pin, Black – ground) Jumper Wires

Way to go ->

1. Login to your Pi using PuTTy or your Ubuntu terminal.

2. Login to your Pi GUI using VNC server (Linux / Windows).

3. From the menu on the top left open Python 3 (IDLE).

3_OpenIdle3

4. In IDLE, create a new file by clicking on File -> New File in the menu bar.

4_NewFile

5. Save the file by clicking on File -> Save As… in the menu bar. The file could be saved on the Desktop. The name could be: LEDbutton.py.

5_SaveAsFile_1

6. In the file LEDbutton.py, write the following code with comments (line starting with “#”) for clear understanding and save (press Cntrl + S on your PC keyboard) the file.

import RPi.GPIO as GPIO
from time import sleep


GPIO.setmode(GPIO.BOARD)

buttonCount = 3  # number of times the LED can be switched ON
count = 0
LEDPin = 8
buttonPin = 40

# Setup the pin the LED is connected to
GPIO.setup(LEDPin, GPIO.OUT)
# Setup the button
GPIO.setup(buttonPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)

buttonPress = True  # Button is OFF
ledState = False

try:
    while count < buttonCount:
        print("Come on man, press the button!")
        buttonPress = GPIO.input(buttonPin)
        if ((not buttonPress) and (not ledState)):
            GPIO.output(LEDPin, True)  # LED ON
            print("LED ON")
            ledState = True
            sleep(3)
        elif ((not buttonPress) and (ledState)):
            GPIO.output(LEDPin, False)  # LED OFF
            print("LED OFF")
            ledState = False
            count += 1
            sleep(.5)
        sleep(.1)
finally:
    # Reset the GPIO Pins to a safe state
	GPIO.output(LEDPin, False)    
	GPIO.cleanup()

 7. Run the code by clicking on Run -> Run Module in the menu bar.

7_RunModule

Hardware Connections ->

1. Raspberry Pi 3 GPIO Header.

pi3_gpio

2. LED connected to Pin 8 – BOARD notation (GPIO14 – BCM notation). Push Button connected to Pin 40 – BOARD notation (GPIO21 – BCM notation).

GPIOButton_schem

GPIOButton_bb

Read full tutorial at

Rating widget: