Non-blocking code: replacing delay()
لم يُترجم بعد؛ يُعرض باللغة الإنجليزية
عن هذا الدرس
delay() parks the CPU on one line, so every other job in loop() stops with it. Follow an Arduino Uno with two jobs: blink the LED on pin 13 every 500 ms, and light the LED on pin 12 while a button on pin 2 is held. With delay(), a press from 1,200 to 1,450 ms is never seen. Then rewrite loop() so it never waits: each pass reads millis(), does only what is due, and reads the button every time. The lesson “Hardware timers, prescalers and millis()” explains where millis() comes from; here you use it to structure your firmware.
Two jobs, one loop()
Our Arduino Uno has two jobs. Blink the LED on pin 13 every 500 ms. And light the LED on pin 12 while you hold the button on pin 2. Both jobs must keep going at the same time.
board Arduino Uno R3, ATmega328P at 16 MHz
job 1 pin 13: flip every 500 ms
job 2 pin 12 = button held?
button pin 2 to GND, INPUT_PULLUP
held -> LOW, open -> HIGHاقرأ الدرس خطوة بخطوة
Two jobs, one loop()
Our Arduino Uno has two jobs. Blink the LED on pin 13 every 500 ms. And light the LED on pin 12 while you hold the button on pin 2. Both jobs must keep going at the same time.
board Arduino Uno R3, ATmega328P at 16 MHz job 1 pin 13: flip every 500 ms job 2 pin 12 = button held? button pin 2 to GND, INPUT_PULLUP held -> LOW, open -> HIGHdelay() makes the CPU wait
The easy way uses delay(). delay(500) pauses the program for 500 ms. The CPU sits on that line and does nothing else: no reading pins, no maths, no writing pins. Only interrupts still run.
line 1 pin 13 HIGH, LED on t = 0 ms line 2 delay(500) t = 0 .. 500 ms the CPU stays on this line interrupts still run (millis keeps counting) no other line of loop() runsA press nobody sees
At 1,200 ms you press the button, and you let go at 1,450 ms. The CPU is inside a delay(500) the whole time, so it never looks. The press comes and goes, and LED 12 stays dark.
pass 2 line 1 at 1,000 ms, line 2 waits until 1,500 ms press 1,200 .. 1,450 ms (250 ms) reads line 5 runs at 1,000, 2,000, 3,000 ms seen neverOne look per second
This loop reads the button only once per pass, on line 5, and a pass takes 1,000 ms. Short presses vanish, and long ones wait up to a second. Every delay you add makes it worse.
one pass 500 + 500 = 1,000 ms of waiting line 5 reads pin 2 once per pass at 2,000 ms: HIGH (released), LED 12 off worst wait almost 1,000 ms missed any press shorter than one pass can vanishCheck the clock, never wait
The fix: never wait. Each pass starts with now = millis(), the milliseconds since the board started. A pass with no waiting is very short, so loop() comes round again almost at once, thousands of times a second.
line 1 now = millis(); read the clock, no waiting 16 MHz most instructions take 1 cycle = 62.5 ns even 1,000 instructions = 62.5 µs per pass = about 16,000 passes a second (the figure is slowed down a great deal)Not time yet? Move on
Line 2 asks: have 500 ms passed since last? At now = 1,130, now - last is 130, so no. The CPU skips the LED code, reads the button on line 7, sets LED 12 on line 8, and starts the next pass.
now = 1,130 last = 1,000 (set at the flip at 1,000 ms) line 2 1,130 - 1,000 = 130 >= 500? false skip lines 3 .. 5 line 7 read the button, line 8 set LED 12The press is seen at once
You press at 1,200 ms. The very next pass reaches line 7 and reads LOW, which means held. Line 8 turns LED 12 on, microseconds after your press. Nothing is missed, because nothing waits.
press 1,200 ms, pin 2 goes LOW line 7 b = LOW (0) line 8 digitalWrite(12, !b) -> HIGH, LED on release 1,450 ms: the next pass turns it off delay version: this press was never seenTime is up: flip the LED
At now = 1,500, now - last is 500, so line 2 is true. last becomes 1,500, the LED state flips, and line 5 turns LED 13 on. Then the pass carries on and reads the button as usual.
line 2 1,500 - 1,000 = 500 >= 500 true line 3 last = 1,000 + 500 = 1,500 line 4 led = true line 5 pin 13 HIGH, LED on next true again at 2,000 msKeep every pass short
Give every timed job its own last and interval, and check it on each pass. Never wait inside a pass: no delay(), no while loop waiting for a pin. The lesson “Event-driven firmware as a state machine” builds on this.
per job unsigned long last; const interval; if (now - last >= interval) { ... } never delay(...) inside loop() while (digitalRead(2) == HIGH) {} // Arduino Uno R3: blink pin 13 every 500 ms and // light pin 12 while the button on pin 2 is held unsigned long last = 0; bool led = false; void setup() { pinMode(13, OUTPUT); pinMode(12, OUTPUT); pinMode(2, INPUT_PULLUP); // pressed reads LOW } void loop() { unsigned long now = millis(); if (now - last >= 500) { last += 500; led = !led; digitalWrite(13, led); } int b = digitalRead(2); digitalWrite(12, !b); }
أسئلة سريعة: 5
اختر إجابة واحدة لكل سؤال. يمكنك تغيير اختياراتك قبل التحقق منها.
01While delay(500) is running on an Arduino Uno, which of these still happens?
The Arduino reference says delay() does not disable interrupts, so Timer0 keeps millis() counting and serial bytes are still received. But no other code in loop() runs until the delay ends.
02A loop() turns an LED on, waits 500 ms, turns it off, waits 500 ms, then reads a button. How often is the button read?
One pass holds two delays of 500 ms, so it takes about 1,000 ms, and the button line runs once per pass.
03In the non-blocking loop, now = 1,130 and last = 1,000. What does the pass do?
now - last = 130, which is less than 500, so the if is false. The pass skips the LED code, reads the button and ends at once.
04Which of these blocks the loop just like delay() does?
The while loop spins on one line until the button is pressed, so nothing else in loop() runs. That is still waiting, only written differently.
05You add a second job: beep every 300 ms. What is the non-blocking way?
Each timed job keeps its own last time and interval, and checks them on every pass. Sharing last would tie the two jobs together, and any loop that waits blocks everything.
المسرد
- Blocking code
- Code that makes the CPU wait on one spot (delay(), or a loop that spins until something happens), so nothing else in the program runs.
- Non-blocking code
- Code that never waits: it checks whether something is due, does it if so, and moves on at once.
- Pass
- One run through loop(), from its first line to its last. The Arduino core then calls loop() again.
- millis()
- An Arduino function that returns the milliseconds since the program started, as an unsigned long. It wraps after about 49.7 days.
- Interrupt
- A signal that makes the CPU pause your code for a moment, run a tiny handler (such as the one that counts milliseconds), then return.
- SRAM
- The chip's small working memory where variables such as now and last live while the program runs. The ATmega328P has 2 KB.
- INPUT_PULLUP
- A pinMode() setting that turns on the pin's internal pull-up resistor, so an open button reads HIGH and a pressed button (to ground) reads LOW.
- Superloop
- Firmware built as one endless loop that runs every job in turn, like Arduino's loop(), with no operating system.
الملاحظات والمصادر
- The cards shorten the code: the full sketch declares unsigned long now and last, bool led, and sets pin 2 to INPUT_PULLUP in setup(). digitalRead returns LOW (0) while the button is held, so !b is true and LED 12 lights.
- How fast is a pass? Most ATmega328P instructions take one clock cycle, 62.5 ns at 16 MHz. Even a pass of 1,000 such instructions takes 62.5 µs, about 16,000 passes a second. The figure slows this down enormously: it runs one pass per millisecond, about 1,000 a second, so you can follow it.
- last += 500 keeps the beat steady even when a pass is a little late; the Arduino example BlinkWithoutDelay uses previousMillis = currentMillis, which is also fine for blinking. Unsigned subtraction keeps now - last correct when millis() wraps after about 49.7 days.
- delay() does not turn interrupts off: Timer0 keeps millis() counting, serial bytes arriving on RX are still stored and PWM outputs keep running. What stops is your own code.
- With an RTOS such as FreeRTOS, vTaskDelay() blocks only the task that calls it; the scheduler runs other tasks meanwhile. On a bare superloop there is only one task, so a delay blocks everything.
- A real button also bounces: its contacts open and close a few times as they meet. The lesson “Debouncing a button” shows how to clean that up with the same millis() pattern.
- Arduino language reference: delay() (source)
- Arduino language reference: millis() (source)
- Arduino example: BlinkWithoutDelay
- Arduino language reference: pinMode() and INPUT_PULLUP (source)
- Microchip ATmega328P datasheet (7810D): single-cycle instructions, 16 MIPS at 16 MHz
- FreeRTOS kernel, task.h: vTaskDelay() and xTaskDelayUntil()
- J. W. Valvano, Embedded Systems: Shape the World, ch. 10 (finite state machines and time delays)
اختبار يتاح بعد الخطوة الأخيرة.