Lesson 45: Two things at once
Do not wait, check the clock
delay(500)stops everything for half a second. The board cannot blink another LED or read a button while it waits.millis()tells you how many milliseconds have passed since the board started. It keeps counting while your program runs.- Instead of waiting, ask again and again: "Is it time yet?"
Words for this lesson
| Word | Meaning |
|---|---|
| millis() | milliseconds since the board started |
| unsigned long | a whole number that can be very big and never negative |
| blocking | code that waits, so nothing else can run |
| non-blocking | code that checks and moves on at once |
Is it time yet?
unsigned long last = 0;
void setup() {
Serial.begin(9600);
}
void loop() {
unsigned long now = millis();
if (now - last >= 1000) {
Serial.println(now);
last = now;
}
}
- The Monitor shows 1000, 2000, 3000 … The
ifis true only once a second, butloopruns thousands of times in between.
delay or millis?
| delay | millis |
|---|---|
| easy for one job | needed for two jobs at once |
| the board waits | the board keeps checking |
| a button press can be missed | a button is read all the time |
Сложность 4/5 · 280 монет + небольшой бонус за первое завершение сегодня
Blink the red LED (pin 12) every 500 ms and the green LED (pin 13) every 300 ms, both at the same time. delay cannot do this: while it waits, nothing else happens. Use millis(), the number of milliseconds since the board started: when 500 ms have passed since the red LED last changed, switch it and remember the time. Do the same for green with 300 ms.
Нажмите Запустить, чтобы увидеть результат здесь.
Сложность 4/5 · 280 монет + небольшой бонус за первое завершение сегодня
Now keep the red LED (pin 12) blinking every 500 ms with millis(), and at the same time make the green LED (pin 13) on while the button on pin 2 is held (pressed reads LOW), and off when it is let go. The green LED must react at once, even in the middle of a blink.
Нажмите Запустить, чтобы увидеть результат здесь.