code
نسخ
اقتباس
عرض
تنزيل
import RPi.GPIO as GPIO
import time
# Define GPIO pin for the button
BUTTON_pin = 16
# Set the GPIO mode
GPIO.setmode(GPIO.BCM)
# Setup button with pull-up resistor
GPIO.setup(BUTTON_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
try:
system_active = False
while True:
button_state = GPIO.input(BUTTON_pin)
if button_state == GPIO.LOW:
system_active = not system_active
if system_active:
print("System activated")
else:
print("System deactivated")
time.sleep(0.250) # Debounce delay
except KeyboardInterrupt:
GPIO.cleanup()
code
نسخ
اقتباس
عرض
تنزيل
import RPi.GPIO as GPIO
# Set the GPIO mode to BCM
GPIO.setmode(GPIO.BCM)
# Define the GPIO pin for your button
BUTTON_PIN = 16
# Define debounce time in milliseconds
DEBOUNCE_TIME_MS = 200 # 200 milliseconds
# Set the initial state and pull-up resistor for the button
GPIO.setup(BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)
# Initialize the button state and previous state
button_state = GPIO.input(BUTTON_PIN)
prev_button_state = button_state
# Define a function to handle button presses
def button_callback(channel):
global button_state
button_state = GPIO.input(BUTTON_PIN)
# Add an event listener for the button press
GPIO.add_event_detect(BUTTON_PIN, GPIO.BOTH, callback=button_callback, bouncetime=DEBOUNCE_TIME_MS)
try:
# Main loop
while True:
# Check if the button state has changed
if button_state != prev_button_state:
if button_state == GPIO.HIGH:
print("Button released")
else:
print("Button pressed")
prev_button_state = button_state
except KeyboardInterrupt:
# Clean up GPIO on exit
GPIO.cleanup()