PI-16Trung bình

Trò chơi kéo co LED với Raspberry Pi Pico (dải NeoPixel + 2 nút nhấn + Buzzer)

Cuộc đấu nút nhấn cho hai người chơi! Raspberry Pi Pico biến dải NeoPixel WS2812B 30 LED thành sợi dây kéo co: người chơi đỏ bên trái, người chơi xanh bên phải. Mỗi lần nhấn đẩy màu của bạn tiến thêm một LED; phủ kín cả dải để thắng hiệp, thắng 3 hiệp để thắng trận. Nhấn quá sớm khi đang đếm ngược sẽ bị mất đất, buzzer thụ động cho mỗi người chơi một tiếng click khác nhau, và trận đấu kết thúc bằng cầu vồng. neopixel, chống dội và âm thanh không chặn trong MicroPython.

0.0(0)
2 đã hoàn thành
Trò chơi kéo co LED với Raspberry Pi Pico (dải NeoPixel + 2 nút nhấn + Buzzer)
Một trò kéo co phát sáng, nơi bạn và một người bạn thi xem ngón tay ai nhanh hơn. Một nửa dải đèn 30 LED màu đỏ, nửa kia màu xanh; ai bấm nút nhanh hơn sẽ kéo nút thắt ở giữa về phía mình, và người đầu tiên phủ kín cả dải bằng màu của mình thắng hiệp đó. Nhấn trước hiệu lệnh sẽ bị phạt, ai thắng ba hiệp trước sẽ thắng trận, tiếp theo là màn trình diễn cầu vồng cùng giai điệu chiến thắng.

Video

Sơ đồ mạch

Trò chơi kéo co LED với Raspberry Pi Pico (dải NeoPixel + 2 nút nhấn + Buzzer) - Sơ đồ mạch

Mã nguồn

MicroPython
1# ─────────────────────────────────────────
2#   BlueGrays · bluegrays.com
3#   Raspberry Pi Pico LED Tug of War Game (NeoPixel Strip + 2 Buttons + Buzzer)
4# ─────────────────────────────────────────
5# Two-player button duel. Every press pushes your color one step along the
6# strip; the first to reach the far end wins the round, first to 3 rounds
7# wins the match. Pressing early during the countdown costs you 2 steps.
8#
9# Pins:
10#   GP2  -> strip DIN
11#   GP14 -> Player 1 button (RED), diger ucu GND
12#   GP16 -> Player 2 button (BLUE), diger ucu GND
13#   GP15 -> Buzzer (+)
14
15from machine import Pin, PWM
16from neopixel import NeoPixel
17import time
18import math
19
20# ============ SETTINGS ============
21NUM_LEDS = 30          # LEDs on the strip
22BRIGHTNESS = 0.6       # ~0.4 A with colours, fine for USB
23WIN_ROUNDS = 3         # Rounds to win the match
24FALSE_START_STEPS = 2  # False start penalty
25SOUND_ON = True        # Sound effects
26
27RED = (255, 0, 0)      # Player 1
28BLUE = (0, 60, 255)    # Player 2
29
30# Knot = number of red LEDs (the border between colors). Both players need the same number of steps.
31START = NUM_LEDS // 2                   # Starting border
32GOAL = min(START, NUM_LEDS - START)     # Steps needed to win
33
34# ============ HARDWARE ============
35strip = NeoPixel(Pin(2), NUM_LEDS)
36btn1 = Pin(14, Pin.IN, Pin.PULL_UP)   # Player 1
37btn2 = Pin(16, Pin.IN, Pin.PULL_UP)   # Player 2
38buzzer = PWM(Pin(15))
39buzzer.duty_u16(0)
40
41
42# ============ SOUND ============
43class Sound:
44    """
45    Non-blocking note player: the game keeps reading buttons while sound plays
46    """
47
48    def __init__(self, pwm):
49        self.pwm = pwm
50        self.queue = []
51        self.until = 0
52
53    def play(self, notes):
54        # notes = [(frequency, ms), ...], frequency 0 = rest
55        if SOUND_ON:
56            self.queue = list(notes)
57            self.until = 0
58
59    def update(self):
60        now = time.ticks_ms()
61        if self.until and time.ticks_diff(now, self.until) < 0:
62            return
63        if not self.queue:
64            if self.until:
65                self.pwm.duty_u16(0)
66                self.until = 0
67            return
68        freq, ms = self.queue.pop(0)
69        if freq:
70            self.pwm.freq(freq)
71            self.pwm.duty_u16(20000)
72        else:
73            self.pwm.duty_u16(0)
74        self.until = time.ticks_add(now, ms)
75
76
77sound = Sound(buzzer)
78
79
80# ============ BUTTON ============
81class Button:
82    """
83    Catches new presses with a 15 ms debounce
84    """
85
86    def __init__(self, pin):
87        self.pin = pin
88        self.state = 1
89        self.raw = 1
90        self.changed = time.ticks_ms()
91
92    def pressed(self):
93        now = time.ticks_ms()
94        raw = self.pin.value()
95        if raw != self.raw:
96            self.raw = raw
97            self.changed = now
98        if time.ticks_diff(now, self.changed) > 15 and raw != self.state:
99            self.state = raw
100            return raw == 0
101        return False
102
103    def sync(self):
104        # Forget stale presses (a button held between rounds is not penalized)
105        self.state = self.raw = self.pin.value()
106        self.changed = time.ticks_ms()
107
108
109b1 = Button(btn1)
110b2 = Button(btn2)
111
112
113# ============ DRAWING HELPERS ============
114def dim(color, k=1.0):
115    # Scale a color by global brightness and k
116    s = BRIGHTNESS * k
117    return (int(color[0] * s), int(color[1] * s), int(color[2] * s))
118
119
120def fill(color, k=1.0):
121    c = dim(color, k)
122    for i in range(NUM_LEDS):
123        strip[i] = c
124    strip.write()
125
126
127def draw_rope(knot):
128    # `knot` LEDs are red (left), the rest blue (right); 2 LEDs on each side of the border form the
129    # bright "knot"
130    for i in range(NUM_LEDS):
131        if i < knot:
132            k = 1.0 if knot - i <= 2 else 0.45   # LEDs near the knot are brighter
133            strip[i] = dim(RED, k)
134        else:
135            k = 1.0 if i - knot < 2 else 0.45
136            strip[i] = dim(BLUE, k)
137    strip.write()
138
139
140def wheel(pos):
141    # Convert 0-255 to a rainbow color
142    pos %= 256
143    if pos < 85:
144        return (255 - pos * 3, pos * 3, 0)
145    if pos < 170:
146        pos -= 85
147        return (0, 255 - pos * 3, pos * 3)
148    pos -= 170
149    return (pos * 3, 0, 255 - pos * 3)
150
151
152def wait_ms(ms):
153    # Wait while keeping the sound running
154    end = time.ticks_add(time.ticks_ms(), ms)
155    while time.ticks_diff(end, time.ticks_ms()) > 0:
156        sound.update()
157        time.sleep_ms(5)
158
159
160# ============ GAME PHASES ============
161def attract():
162    # Waiting: both colors breathe, any button starts the game
163    print("Press a button to start")
164    b1.sync()
165    b2.sync()
166    t0 = time.ticks_ms()
167    while True:
168        sound.update()
169        t = time.ticks_diff(time.ticks_ms(), t0)
170        k = 0.25 + 0.75 * (math.sin(t / 400) + 1) / 2
171        for i in range(NUM_LEDS):
172            if i < START:
173                strip[i] = dim(RED, k)
174            else:
175                strip[i] = dim(BLUE, 1.25 - k)   # Breathes in opposite phase
176        strip.write()
177        if b1.pressed() or b2.pressed():
178            return
179        time.sleep_ms(15)
180
181
182def countdown():
183    # 3-2-1 countdown; early presses are penalized. Returns the starting knot
184    knot = START
185    b1.sync()
186    b2.sync()
187    colors = [(255, 0, 0), (255, 150, 0), (0, 255, 0)]   # Red, yellow, green
188    for step in range(3):
189        fill(colors[step], 0.6)
190        if step == 2:
191            sound.play([(1200, 200)])   # GO!
192            break
193        sound.play([(600, 150)])
194        end = time.ticks_add(time.ticks_ms(), 800)
195        while time.ticks_diff(end, time.ticks_ms()) > 0:
196            sound.update()
197            if b1.pressed():
198                knot -= FALSE_START_STEPS
199                print("Player 1 false start!")
200                sound.play([(150, 200)])
201            if b2.pressed():
202                knot += FALSE_START_STEPS
203                print("Player 2 false start!")
204                sound.play([(150, 200)])
205            time.sleep_ms(5)
206    # Penalties must not push the knot to an end
207    return max(START - GOAL + 2, min(START + GOAL - 2, knot))
208
209
210def play_round(knot):
211    # Button duel; returns the winner (1 or 2) when the knot reaches an end
212    draw_rope(knot)
213    while True:
214        sound.update()
215        moved = False
216        if b1.pressed():
217            knot += 1
218            sound.play([(440, 25)])
219            moved = True
220        if b2.pressed():
221            knot -= 1
222            sound.play([(660, 25)])
223            moved = True
224        if moved:
225            if knot >= START + GOAL:   # Strip fully red
226                return 1
227            if knot <= START - GOAL:   # Strip fully blue
228                return 2
229            draw_rope(knot)
230        time.sleep_ms(1)
231
232
233def celebrate_round(winner, scores):
234    # Winner color flashes 3 times, then the score dots are shown
235    color = RED if winner == 1 else BLUE
236    print("Round winner: Player", winner, "| Score:", scores[0], "-", scores[1])
237    sound.play([(523, 120), (659, 120), (784, 120), (1047, 300)])
238    for _ in range(3):
239        fill(color)
240        wait_ms(180)
241        fill((0, 0, 0))
242        wait_ms(120)
243    # Score: red dots from the left, blue dots from the right
244    for i in range(NUM_LEDS):
245        strip[i] = (0, 0, 0)
246    for s in range(scores[0]):
247        strip[s * 2] = dim(RED)
248    for s in range(scores[1]):
249        strip[NUM_LEDS - 1 - s * 2] = dim(BLUE)
250    strip.write()
251    wait_ms(1800)
252
253
254def celebrate_match(winner):
255    # End of match: rainbow wave and victory tune
256    print("MATCH WINNER: Player", winner)
257    sound.play([(784, 150), (784, 150), (784, 150), (1047, 450), (0, 80), (988, 150), (1047, 500)])
258    t0 = time.ticks_ms()
259    while time.ticks_diff(time.ticks_ms(), t0) < 3500:
260        sound.update()
261        offset = time.ticks_diff(time.ticks_ms(), t0) // 8
262        for i in range(NUM_LEDS):
263            strip[i] = dim(wheel(i * 256 // NUM_LEDS + offset))
264        strip.write()
265        time.sleep_ms(15)
266    fill(RED if winner == 1 else BLUE)
267    wait_ms(1000)
268
269
270# ============ MAIN LOOP ============
271print("== BlueGrays · bluegrays.com ==")
272print("Pico LED Tug of War")
273
274scores = [0, 0]
275while True:
276    attract()
277    while max(scores) < WIN_ROUNDS:
278        start_knot = countdown()
279        winner = play_round(start_knot)
280        scores[winner - 1] += 1
281        celebrate_round(winner, scores)
282    celebrate_match(1 if scores[0] > scores[1] else 2)
283    scores = [0, 0]
284

FAQ

Dải LED của mình không phải 30 LED. Mình có dùng độ dài khác được không?

Có. Đặt `NUM_LEDS` ở đầu code bằng số LED trên dải của bạn; điểm xuất phát (`START`) và số bước cần để thắng (`GOAL`) được tính tự động. Với dải 60 LED, mỗi người chơi cần 30 lần nhấn, nên mỗi hiệp kéo dài hơn.

Mình có thật sự cần điện trở 330 Ω và tụ 470 µF không?

Trong Wokwi thì không, nhưng với mạch thật thì nên có. Mắc điện trở 330 Ω nối tiếp giữa GP2 và chân DIN của dải LED, và tụ 470 µF giữa 5V và GND của dải (chân dài vào 5V). Chúng bảo vệ LED đầu tiên và tránh nhấp nháy cũng như màu ngẫu nhiên.

USB của Pico có đủ cấp nguồn cho dải LED không?

Với 30 LED và `BRIGHTNESS = 0.6`, dải LED kéo tối đa khoảng 0,4 A, USB đáp ứng được. VBUS chỉ cấp 5V khi đang cắm USB. Với dải dài hơn hoặc độ sáng cao hơn, hãy dùng adapter 5V/2A riêng và nối chung GND.

Mình đổi số hiệp và hình phạt nhấn sớm thế nào?

`WIN_ROUNDS` là số hiệp cần thắng để thắng trận (mặc định 3). `FALSE_START_STEPS` đặt số bước người nhấn sớm bị đẩy lùi (mặc định 2; đặt thành 0 để tắt hình phạt). Muốn chơi không âm thanh, hãy đặt `SOUND_ON = False`.