You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

带Python计时器的投币器代码问题:计时时无法累加硬币数

Fixing Coin Counting During Timer Countdown in Your Arcade Python Script

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_timer function 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) in process_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 (startBtn and counterPin) with your actual GPIO pin numbers.
  • Adjust the formatTime function if you need a different time display format.
  • The threading.Thread approach ensures both the timer and input handling run simultaneously, just like a real arcade machine.

内容的提问来源于stack exchange,提问作者kdl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:49:31