带Python计时器的投币器代码问题:计时时无法累加硬币数
Hey there! Let's tackle this problem you're having with your arcade machine script. The core issue here is that your current timer loop uses time.sleep() which blocks the entire program—so while the timer is counting down, your script can't check the GPIO pin for new coin inputs, meaning no coins get added until the timer finishes.
Why Your Current Code Fails
Right now, once you start the timer with this loop:
for i in range(x + 1): time.sleep(1) print(formatTime(x)) x -= 1
The program pauses for 1 second on each iteration. During those pauses, it can't run any other logic (like checking counterPin for new coins). Your coin counting only works when the timer isn't active, which isn't ideal for an arcade machine!
The Solution: Use Threading
We can split the timer logic into a separate thread. This way, the timer runs in the background, and the main thread can keep checking for coin inputs non-stop. Here's how to adjust your code:
Modified Code Example
import RPi.GPIO as GPIO import time import os import threading # Replace these with your actual GPIO pin numbers startBtn = 17 counterPin = 27 # GPIO Setup GPIO.setmode(GPIO.BCM) GPIO.setup(startBtn, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(counterPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) coins = 0 creditss = 0 timer_running = False remaining_time = 0 def formatTime(seconds): # Convert seconds to MM:SS format (adjust if needed) mins = seconds // 60 secs = seconds % 60 return f"{mins:02d}:{secs:02d}" def run_timer(): global remaining_time, timer_running while remaining_time > 0 and timer_running: print(formatTime(remaining_time)) time.sleep(1) remaining_time -= 1 # Timer finished logic timer_running = False if remaining_time == 0: print("Continue? Insert more money to keep playing!") remaining_time = 30 # 30-second continue window while remaining_time > 0: print(formatTime(remaining_time)) time.sleep(1) remaining_time -= 1 print("Time's up! Exiting...") os.system('/home/pi/exit.sh') def process_coins(): global coins, creditss input_state = GPIO.input(counterPin) if input_state == False: coins += 1 print(f"{coins}¢ inserted") time.sleep(0.09) # Debounce delay to prevent duplicate counts # Convert coins to credits when we hit 100¢ if coins >= 100: creditss += coins // 100 coins = coins % 100 print(f"You currently have: {creditss} credits") try: while True: # Always check for new coins first process_coins() start = GPIO.input(startBtn) if start == False and creditss > 0 and not timer_running: # Calculate total play time (5 mins = 300 seconds per credit) remaining_time = creditss * 300 creditss = 0 print(f"You have: {remaining_time//60} minutes to play!") print("Have Fun!") timer_running = True # Start timer in a separate thread timer_thread = threading.Thread(target=run_timer) timer_thread.start() # Add extra time if credits are inserted mid-game if timer_running and creditss > 0: remaining_time += creditss * 300 creditss = 0 print(f"Added time! New remaining time: {formatTime(remaining_time)}") time.sleep(0.01) # Small delay to reduce CPU usage except KeyboardInterrupt: GPIO.cleanup() finally: GPIO.cleanup()
Key Changes Explained
- Threaded Timer: The
run_timerfunction runs in its own thread, so it doesn't block the main thread from checking for coins. - Non-Blocking Input Handling: The main loop continuously calls
process_coins()to check for new coin inputs, even while the timer is running. - Debounce Protection: The
time.sleep(0.09)inprocess_coins()prevents multiple counts from a single coin insertion. - Mid-Game Time Addition: The script now checks for new credits while the timer is running and adds time immediately.
- Cleaner Credit Conversion: Duplicate coin-to-credit code is replaced with a single function, making the script easier to maintain.
Quick Notes
- Replace the placeholder pin numbers (
startBtnandcounterPin) with your actual GPIO pin numbers. - Adjust the
formatTimefunction if you need a different time display format. - The
threading.Threadapproach ensures both the timer and input handling run simultaneously, just like a real arcade machine.
内容的提问来源于stack exchange,提问作者kdl

