同时运行两项任务
同时让指示灯闪烁并读取按钮
同时运行两项任务 是 CoddyKit 上的免费 Arduino & IoT Academy 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Arduino & IoT Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Arduino & IoT Academy 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
The Multitasking Dream
Real devices do many things at once: blink a light while watching a button. With non-blocking timing your board can finally juggle both.
Each Task Gets Its Timer
The trick is one timer per task. Give the blink its own previousMillis and interval, separate from anything else you want to run.
Track Time Separately
Keep a dedicated previousMillis for the LED so its schedule never tangles with other timed jobs in the same loop.
unsigned long ledPrevious = 0;
const long ledInterval = 500;Blink Block
First, the blink block checks its own timer. When 500 milliseconds pass it toggles the LED and resets, then control moves on.
if (millis() - ledPrevious >= ledInterval) {
ledPrevious = millis();
}Read the Button Every Loop
Right after the blink block, you read the button on every single pass. Because nothing froze, no press is ever missed.
int state = digitalRead(buttonPin);Two Jobs, One Loop
Now the same loop handles both: it times the blink and checks the button thousands of times a second. They feel simultaneous.
Add a Third Task
Want more? Just add another timer and block, like reading a sensor every two seconds. The pattern scales to many tasks cleanly.
Keep the Loop Fast
The rule that makes it work: never block. Keep every part of the loop quick so it can return often and serve all tasks fairly.
Not True Parallelism
The board still does one thing at a time, just very fast. This is cooperative multitasking, where each task does a little and yields.
Banish the Big delay
One long delay anywhere breaks the whole illusion, since it freezes every task. Replace pauses with millis checks to keep things smooth.
The Heart of Responsive IoT
This state machine style, many small timed checks in one loop, is how responsive sensors, displays, and connected devices are really built.
Quick Check
How does one loop blink an LED and read a button at the same time?
Recap
You combined timers in one loop to multitask: blink and read a button together, with no blocking delay. That is the core skill behind real IoT devices. 🚀
常见问题解答
「同时运行两项任务」课时是免费的吗?
是的 — 「同时运行两项任务」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Arduino & IoT Academy 课程的其余内容,请升级到 CoddyKit PRO。 Arduino & IoT Academy 课程共包含 4 节课。
「同时运行两项任务」这节课中我会学到什么?
同时让指示灯闪烁并读取按钮 你通过在浏览器中直接运行的动手代码来练习 Arduino & IoT Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Arduino & IoT Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Arduino & IoT Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「同时运行两项任务」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Arduino & IoT Academy 课中编写并运行代码吗?
能。每节 Arduino & IoT Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。