基于Python的上升沿计数:TY-010光电传感器树莓派实现
Hey Stephan, welcome to the Raspberry Pi world—sounds like a fun first project! Let's fix up your code to count those sensor interrupts over a set time (like 2 seconds) as you want.
First, let's spot a quick typo in your existing code: you defined outputFunction but tried to use ausgabeFunktion in the event detect setup. That'll throw an error right away, so we'll fix that first.
Step-by-Step Implementation
Here's a revised version of your code that adds the counting logic, with clear explanations:
import RPi.GPIO as GPIO import time GPIO_PIN = 24 count = 0 # Global variable to track interrupts def outputFunction(null): global count count += 1 print(f"Signal detected! Total so far: {count}") # Updated print for better clarity # Setup GPIO (explicit mode is good practice) GPIO.setmode(GPIO.BCM) GPIO.setup(GPIO_PIN, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) print("Sensor-Test [Press CTRL+C to exit]") # Attach interrupt callback (fixed the function name mismatch) GPIO.add_event_detect(GPIO_PIN, GPIO.RISING, callback=outputFunction, bouncetime=100) try: while True: # Reset count and start a 2-second timer window count = 0 start_time = time.time() # Wait until the 2-second window ends while time.time() - start_time < 2: time.sleep(0.01) # Small sleep to reduce unnecessary CPU load # Print the final count for this window print(f"--- 2-second window complete: {count} interrupt(s) detected ---") # Optional: Add a pause between windows if needed # time.sleep(1) except KeyboardInterrupt: print("\nCleaning up GPIO...") GPIO.cleanup()
Key Details & Technical Tips
- Global Count Variable: We use a global variable to track interrupts because the callback function can't easily pass values back to the main loop. If you expand this project later, consider using a class to manage state instead of globals—it's cleaner for larger codebases.
- Bouncetime: Your
bouncetime=100is perfect for filtering out sensor noise. Adjust this value (in milliseconds) if you notice false triggers (increase it) or miss real signals (decrease it, but be careful not to let noise slip through). - CPU Efficiency: The small
time.sleep(0.01)in the inner loop prevents your script from hogging the CPU while waiting for the timer to finish. - GPIO Mode: Explicitly setting
GPIO.setmode(GPIO.BCM)ensures consistency—RPi.GPIO supports two numbering schemes, so being clear avoids confusion down the line. - Cleanup: Always ensure
GPIO.cleanup()runs on exit (via theKeyboardInterrupthandler) to reset GPIO pins to their default state, preventing issues with future projects.
Alternative Non-Blocking Approach (Using threading.Timer)
If you want to keep your main loop free for other tasks while still counting interrupts at 2-second intervals, try a timer thread:
# Add threading import at the top import threading def print_and_reset_count(): global count print(f"--- 2-second window complete: {count} interrupt(s) detected ---") count = 0 # Schedule the next count check threading.Timer(2.0, print_and_reset_count).start() # In the try block: try: print_and_reset_count() # Start the first timer while True: time.sleep(1) # Keep the main loop alive except KeyboardInterrupt: print("\nCleaning up GPIO...") GPIO.cleanup()
This approach lets you run other code in the main loop while still tracking interrupt counts automatically every 2 seconds.
内容的提问来源于stack exchange,提问作者Stephan Prn

