Control GPIO pins on a raspbery pi with Python

Like it? Share it!

pi_led_overviewI will post instructions on wiring it up but for now it’s just the python code. Has built in error detection and you can chose which pin to control!

 

 

 

 

 

 

##Control GPIO pins with python by Nathan ASH - @ompster - nathanash.id.au
#Use pin 7 if you are unsure (default)

#---------------------------IMPORTS-----------------#
import RPi.GPIO as GPIO #import GPIO library        #
import os #import OS to clear screen                #
import time #import time so we can sleep ZzZzzz     #
#---------------------------------------------------#

#lets setup which pin to control
pin = raw_input('Which GPIO pin would you like to use? ')
try :
    pin = int(pin)
except :
    print 'ERROR not a valid number!'
    exit()

GPIO.setmode(GPIO.BOARD) #setup GPIO for use

try :
    GPIO.setup((pin), GPIO.OUT) #Set PIN(pin) GPIO direction
except :
    print 'ERROR Not a valid GPIO pin! 1 - 24'
    exit()

inMenu = True

def funcBlink(numTimes, blinkSpeed) :
    for i in range(0, numTimes) :
        print 'BLINK ' + str(i+1) #convert int to string for output
        GPIO.output((pin), True)
        time.sleep(blinkSpeed) #wait for x secconds
        GPIO.output((pin), False)
        time.sleep(blinkSpeed)
    print 'Finished blinking!'

while inMenu is True : #menu loop
    os.system('clear')
    print 'What would you like to do:'
    print '1 > Turn on LED'
    print '2 > Turn off LED'
    print '3 > Blink the LED'
    print '0 > Exit'
    userChoice = raw_input('Make a selection 1 - 3 > ')

    if userChoice == '1' :
        GPIO.output((pin), True) #turn on PIN(pin)

    elif userChoice == '2' :
        GPIO.output((pin), False) #turn off PIN(pin)

    elif userChoice == '3' :
        blinkers = raw_input('How many blinks? ')
        speed = raw_input('How fast in secconds? ')
        blinkers = int(blinkers)
        speed = float(speed)
        funcBlink(blinkers, speed) #call the function and supply variables

    elif userChoice == '0' :
        print 'Stopping GPIOs....'
        GPIO.output((pin), False)
        break

    else :
        print 'invalid selection!'
    
GPIO.cleanup() #release the PINS!
print 'Goodbye :)'
exit()

HOT TIP for anyone trying to wire something to the GPIO pins without a breakout board or something. My alligator clips kept touching and grounding 🙁 so I used the old power LED leads from on old PC case!

This article was viewed (542) times!

Like it? Share it!

Comments

comments