Lesson 12: Reaction game
How fast are you?
- In this project you build a small game: an LED says GO, and you press the button as fast as you can.
- The Arduino measures the time between GO and your press, and prints it in the Serial Monitor.
- You wire the circuit yourself: an LED on pin 13 and a button on pin 2.
Words for this lesson
| Word | Meaning |
|---|---|
| reaction time | how long you need to answer a signal |
| millis() | the number of milliseconds since the board started |
| unsigned long | a whole number that can be very big and is never negative |
| cheat | win by breaking the rules |
A clock inside the board
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.print("The board has run for ");
Serial.print(millis());
Serial.println(" ms");
delay(1000);
}
millis()counts up all the time, 1000 every second, while your sketch does other things.- Save the time at one moment, and later take it away from
millis():
| Moment | millis() |
|---|---|
| the LED says GO | 1000 |
| you press the button | 1312 |
| your reaction time | 1312 − 1000 = 312 ms |
Wait for the button
while (digitalRead(2) == HIGH) { }is a loop with nothing inside. The sketch stays in it until the button is pressed.- After the press, wait again until you let go. Otherwise one long press would count again and again.
- Most people need 200 to 300 ms. Can you beat 200?
ความยาก 3/5 · 200 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Build the game: an LED with a 220 Ω resistor on pin 13, and a button from pin 2 to GND. Then finish the sketch. After 1 second the LED comes on. Wait until the button is pressed, then switch the LED off and print the time, like Time: 312 ms. Press Run and try it: how fast are you?
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 4/5 · 280 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Stop the cheats! Some players press before the LED comes on. Change the 1-second wait: in a loop, check the button again and again until 2 seconds have passed. If someone presses too soon, print Too soon!, wait until they let go, and start the 2 seconds again.
คลิก Run เพื่อดูผลลัพธ์ที่นี่