This version will turn off the LED after max presses:
Code:
import RPi.GPIO as GPIOimport timeBUTTON_PIN = 16button_counts = 0GPIO.setmode(GPIO.BCM)GPIO.setwarnings(False)LED_PIN = 17 # Use GPIO pin 17GPIO.setup(LED_PIN, GPIO.OUT)GPIO.setup(BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)prev_button_state = GPIO.input(BUTTON_PIN)max = 3 # use 15 heretry: while True: GPIO.output(LED_PIN, GPIO.HIGH) button_state = GPIO.input(BUTTON_PIN) if button_state != prev_button_state: if button_state == GPIO.LOW: print("The button is pressed!") button_counts = button_counts + 1 print ("count=",button_counts) else: print("The button is released!") prev_button_state = button_state if button_counts == max: print ("turn off LED as max count reached") GPIO.output(LED_PIN, GPIO.LOW) breakexcept KeyboardInterrupt: print ("\nExiting the program.") GPIO.cleanup() #Clean up the GPIO
Statistics: Posted by neilgl — Fri Aug 16, 2024 6:36 pm