GPIO and Python (5/9) - User Input

GPIO and Python (5/9) - User Input

In this project you will controller either the red or blue led depending on what your chose.

Things you will need:

Raspberry Pi + SD Card
Keyboard + Mouse
Monitor + HDMI Cable
Power Supply
Breadboard
1x Red LED
1x Blue LED
2x 330? Resistor
1x M/M Jumper Wire
4x M/F Jumper Wire
1x Button

Prerequisites:

Latest version of Rasbian installed on your SD Card
Raspberry Pi setup with a keyboard, mouse and monitor

1. Change the current directory to our gpio_python_code directory:

cd gpio_python_code

2. Start by creating a file for our user input script

touch 5_user_input_blink.py

3. Edit the 5_user_input_blink.py script using nano 5_user_input_blink.py add the following code:

#!/usr/bin/python



import os

from time import sleep

import RPi.GPIO as GPIO



GPIO.setmode(GPIO.BCM)



GPIO.setup(17,GPIO.OUT)

GPIO.setup(27,GPIO.OUT)



#Setup variables for user input

led_choice = 0

count = 0



os.system('clear')



print "Which LED would you like to blink"

print "1: Red?"

print "2: Blue?"



led_choice = input("Choose your option: ") # ask for an input



if led_choice == 1:

    os.system('clear')

    print "You picked the Red LED"

    count = input("How many times would you like it to blink?: ")

    while count > 0: # while the value of count is greater than 0

        GPIO.output(27,GPIO.HIGH)

        sleep(1)

        GPIO.output(27,GPIO.LOW)

        sleep(1)

        count = count - 1 # reduce the value of count by 1



if led_choice == 2:

    os.system('clear')

    print "You picked the Red LED"

    count = input("How many times would you like it to blink?: ")

    while count > 0: # while the value of count is greater than 0

        GPIO.output(17,GPIO.HIGH)

        sleep(1)

        GPIO.output(17,GPIO.LOW)

        sleep(1)

        count = count - 1 # reduce the value of count by 1

4. Execute your 5_user_input_blink.py script

sudo python 5_user_input_blink.py

You’ll be asked to enter the number “1” or “2” depending on which led you would like to make blink.

You will then be asked to enter a number, the amount of times you want the led to blink.

Your chosen LED should now be blinking!

Leave a comment

All comments are moderated before being published.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.