Lesson 28: Reaction duel
Who is faster?
- A reaction duel is a game for two: wait for the GO light, then press your button as fast as you can.
- The GO light comes on after a random wait, so nobody can guess the moment.
- The Arduino checks the buttons thousands of times a second, so it always knows who was first.
Words for this lesson
| Word | Meaning |
|---|---|
| duel | a fight or game between two people |
| false start | starting before the signal |
| random(a, b) | a number from a up to b − 1, different each time |
| break | leave a loop at once |
Waiting, two ways
delay(1500); |
while (millis() - t0 < 1500) { ... } |
|---|---|
| the board does nothing else | the board checks the buttons all the time |
| a press is not seen | a press can end the wait with break |
AND and OR in a loop
| Code | The loop runs while… |
|---|---|
A == HIGH && B == HIGH |
both buttons are up |
A == LOW || B == LOW |
at least one button is down |
&&means AND: both must be true.||means OR: one is enough.- The first loop waits for a press; the second waits until both players let go.
רמת קושי 4/5 · 280 מטבעות + בונוס קטן בהשלמה הראשונה היום
Two players, two buttons. After a random wait the GO light (pin 13) comes on, and the first player to press wins. The sketch already waits for the first press. Finish it: if button 1 (pin 2) is pressed, light player 1's LED (pin 8) and print Player 1 wins; else light pin 9 and print Player 2 wins.
לחץ על הרץ כדי לראות את התוצא כאן.
רמת קושי 5/5 · 400 מטבעות + בונוס קטן בהשלמה הראשונה היום
Some players press before GO, just in case. That is a false start, and the other player wins. Change the random wait: wait with a while loop and millis(), and check both buttons inside it. If player 1 presses too soon, player 2 wins: light pin 9 and print False start! Player 2 wins (and the other way round). Only when nobody pressed too soon, switch GO on as before.
לחץ על הרץ כדי לראות את התוצא כאן.