#! /usr/bin/python3 # Importa les llibreries requerides import RPi.GPIO as GPIO # Inicialitza una variable global amb el pin on connectarem el LED, segons els noms # de la Raspberry Pi GPIO Extension Board. En este cas, GPIO17 ledPin = 17 # Variable global per al botó, en GPIO18 buttonPin = 18 # Configura els pins def setup(): # Utilitza els noms de la extension board GPIO.setmode(GPIO.BCM) # Posa el ledPin en mode OUTPUT GPIO.setup(ledPin, GPIO.OUT) # Escriu un nivell LOW per el ledPin per apagar el LED GPIO.output(ledPin, GPIO.LOW) print('LED en pin %d'%ledPin) # Posa el buttonPin en mode INPUT PULL UP GPIO.setup(buttonPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) print('Botó en pin %d'%buttonPin) # Funció amb el codi principal def run(): while True: # Si el botó està premut if GPIO.input(buttonPin) == GPIO.LOW: print('Botó premut') # Engega el LED GPIO.output(ledPin, GPIO.HIGH) # Si el botó no està premut else: print('Botó no premut') # Apaga el LED GPIO.output(ledPin, GPIO.LOW) # Allibera els recursos utilitzats def destroy(): # Allibera els pins GPIO GPIO.cleanup() # Si s'executa este script... if __name__ == '__main__': print('Executant el script... \n') # Ho prepara tot per funcionar setup() try: # Executa la funció principal run() # Captura el CTRL+C del teclat per a no abortar directament except KeyboardInterrupt: # Acaba ordenadament destroy()