Raspberry Pi GPIO with python

440 views Asked by At

I am stuck on this work related project. What I am trying to accomplish is, after a specific amount of button presses, I want my program to end. I am thinking along the lines of a loop.

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)

GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP)

while True:

    input_state = GPIO.input(18)
    if input_state == False:
            print('Button Pressed')
            time.sleep(0.2)

Max_Presses = 100
button_pressed  = 0

def button_pressed():
    return input_state()

 while button_pressed < Max_Presses:

    print 'still going'
    if button_pressed():
            button_pressed += 1
1

There are 1 answers

0
mhawke On

Yes, a while loop sounds like a necessary thing to use for that. You will need a counter that keeps track of the number of button presses. Check the counter as your loop condition, e.g.

MAX_PRESSES = 10
button_presses = 0

def button_pressed():
     return poll_GPIO_pin_or_whatever()   # something that detects button presses

while button_presses < MAX_PRESSES:
    print 'still going'
    if button_pressed():
        button_presses += 1

The check function might work by polling a GPIO pin, or there might be some sort of callback mechanism for that that works in your environment.