|     Inicio    |   |         |  |   FOROS      |  |      |      
   Elastix - VoIP B4A (Basic4Android) App inventor 2 PHP - MySQL
  Estación meteorológica B4J (Basic4Java) ADB Shell - Android Arduino
  Raspberry Pi Visual Basic Script (VBS) FireBase (BD autoactualizable) NodeMCU como Arduino
  AutoIt (Programación) Visual Basic Cosas de Windows Webs interesantes
Translate:
Búsqueda en este sitio:


.

Raspberry Pi

Tutorial de Rapberry Pi en español.
- Juan Antonio Villalpando -

Volver al índice del tutorial

____________________________

39.- Interrupciones.

GPIO2 es SDA
GPIO3 es SCL

- Para comprobar si un Pulsador está pulsado utilizamos la instrucción if dentro de un bucle. Esto se llama "polling".

- El bucle está continuamente ejecutándose y el programa está "atrapado" en ese bucle.

- En vez de utilizar un bucle y un if para comprobar si un Pulsador está pulsado, se utilizan Interrupcions

http://tipsraspberry.blogspot.com/2014/02/gpio-entradas-y-salidas-en-python.html

https://hondou.homedns.org/pukiwiki/index.php?Raspberry%20Pi%20GPIO%20%28Python%CA%D4%29

______________________________
1.- Pulsador. Bucle. Polling. Sondeo.

- Conecta un Pulsador al terminal 12 (es el GPIO18) y su otro terminal a 3,3 V.

- GPIO.setup(12, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

- Observa que el programa se mete en un bucle infinito. while True:

- Mediante el if está comprobando si está pulsado o no el Pulsador.

pulsador_bucle.py

import RPi.GPIO as GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(12, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

while True:
    if GPIO.input(12) == GPIO.HIGH:
        print("Botón PULSADO.")
    else:
        print("No pulsado.")

- Fíjate que si pusiera una instrucción fuera de ese bucle, nunca se ejecutaría.

- Todo debe estar dentro de ese bucle, a menos que se rompa el bucle mediante un break

pulsador_bucle_no.py

import RPi.GPIO as GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(12, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

while True:
    if GPIO.input(12) == GPIO.HIGH:
        print("Botón PULSADO.")
    else:
        print("No pulsado.")

print("Esto no se imprime.")			

______________________________
2.- Pulsador. Interrupción.

pulsador_interrupcion.py

#!/usr/bin/env python
import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BOARD)
switch = 12

# Define a threaded callback function to run in another thread when events are detected  
def my_callback(channel):
    print GPIO.input(switch)
    if GPIO.input(switch):     # if port 18 == 1  
        print ("De bajo a alto.")
    else:                  # if port 18 != 1  
        print ("De alto a bajo.")

GPIO.setup(switch, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.add_event_detect(switch,GPIO.BOTH,callback=my_callback,bouncetime=300)
try:
    print ("Cuando pulses, saldrá de bajo a alto.")
    print ("Cuando no pulses, saldrá de bajo a alto.")
    time.sleep(30)         #  30 segundos  
    print ("Tiempo finalizado")

finally:
    GPIO.cleanup()

 

pulsador_interrupcion_2.py

from time import sleep
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)

# Set up input pin
GPIO.setup(12, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

try:
    while True:
        if(GPIO.input(12) == 1):    
            print("Pulsado")
        else:
            print("NO Pulsado")
        sleep(0.2)

finally:
    GPIO.cleanup()

 

 

pulsador_interrupcion_3.py

#!/usr/bin/env python2.7   
import RPi.GPIO as GPIO  
GPIO.setmode(GPIO.BOARD)  
  
GPIO.setup(12, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)    
  
print ("Esperando que pulses el boton 12" )  
 
try:  
    GPIO.wait_for_edge(12, GPIO.RISING)  
    print ("\nSubida de nivel" )  
except KeyboardInterrupt:  
    GPIO.cleanup()

 

pulsador_interrupcion_4.py

#!/usr/bin/env python
import time
import RPi.GPIO as GPIO

def buttonEventHandler (pin):
    print ("handling button event")

def main():

    GPIO.setmode(GPIO.BOARD)

    GPIO.setup(12,GPIO.IN)

    GPIO.add_event_detect(12,GPIO.FALLING)
    GPIO.add_event_callback(12,buttonEventHandler)

    while True:
        print("Uno")
        time.sleep(1)
        print("Dos")
        time.sleep(1)

    GPIO.cleanup()

if __name__=="__main__":
    main()				 
					 

 

pulsador_interrupcion_5.py

#!/bin/python
import RPi.GPIO as GPIO
from time import sleep
import os
 
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
 
def apagar(pin):
  os.system("sudo shutdown -r now")
  sleep(1)
 
def loop():
  try:
    raw_input()
  except KeyboardInterrupt:  
    GPIO.cleanup() 
 
GPIO.setup(12, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.add_event_detect(12, GPIO.RISING, callback=apagar, bouncetime=200)
 
loop()   

 

GPIO.FALLING event, but it's also possible to detect GPIO.RISING and GPIO.BOTH
GPIO.wait_for_edge() which will make your program sleep until an event wakes it up.
GPIO.remove_event_detect().

 

			   
buttons = (17, 27)
GPIO.setup(buttons, GPIO.IN, pull_up_down=GPIO.PUD_UP)

GPIO.add_event_detect(17, GPIO.RISING)  # add rising edge detection on a channel
GPIO.add_event_detect(27, GPIO.RISING)  #for both buttons

start = time.time()
while True:
    if GPIO.event_detected(17):
        print('Button 1 pressed')
    if GPIO.event_detected(27):
        print('Button 2 pressed')
    if time.time() - start > 5:
        print('Timeout')
    time.sleep(0.0001)   
			 



  
def callback_1():
   global GPIO1_triggered
   set GPIO1_triggered

def callback_2():
   global GPIO2_triggered
   set GPIO2_triggered

GPIO1_triggered = False
GPIO2_triggered = False

add_event_detect(GPIO1, callback1)
add_event_detect(GPIO2, callback2)

stop = time.time() + 5

while not GPIO1_triggered and not GPIO_2 triggered and time.time() < stop:
   time.sleep(0.01)

cancel_event_detect(GPIO1)
cancel_event_detect(GPIO2)

if GPIO1_triggered:
   code
elif GPIO2_triggered:
   code
else:
   code
			   
			   

___________________________________________________

 

- Mi correo:
juana1991@yahoo.com
- KIO4.COM - Política de cookies. Textos e imágenes propiedad del autor:
© Juan A. Villalpando
No se permite la copia de información ni imágenes.
Usamos cookies propias y de terceros que entre otras cosas recogen datos sobre sus hábitos de navegación y realizan análisis de uso de nuestro sitio.
Si continúa navegando consideramos que acepta su uso. Acepto    Más información