Написание безопасного ISR
Делайте обработчики прерываний короткими и используйте volatile.
«Написание безопасного ISR» — бесплатный урок Arduino & IoT Academy на CoddyKit. Это урок 3 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Arduino & IoT Academy, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Arduino & IoT Academy содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
A Special Function
An ISR, or interrupt service routine, is the function that runs when an interrupt fires. It has rules that ordinary functions do not.
Keep It Short
The golden rule: make your ISR as short as possible. The main program is paused while it runs, so finish fast and get out.
Do the Heavy Work Later
Inside the ISR, just set a flag or bump a counter. Let the loop do the slow work like printing or math once it sees the flag.
void myISR() {
pressed = true;
}Shared Variables
An ISR and your loop both touch the same variable. The compiler may not expect it to change behind the loop's back, which causes subtle bugs. 🐞
The volatile Keyword
Mark any variable shared with an ISR as volatile. It tells the compiler the value can change at any moment, so always reread it.
volatile bool pressed = false;No delay Inside
Never call delay in an ISR. The timing that delay needs is itself paused during an interrupt, so it simply will not work.
Serial Is Risky Too
Avoid Serial.print inside an ISR. It relies on interrupts that are blocked while your handler runs, so output can stall or garble.
millis Freezes
Inside an ISR, millis stops advancing because its background counting is paused. Read elapsed time in the loop, not the handler.
Handle the Flag in Loop
Back in the loop, check the flag, act on it, then clear it. This is where the real response safely takes place.
if (pressed) {
pressed = false;
handlePress();
}Reading Multi-Byte Values
When the loop reads a multi-byte volatile value an ISR updates, briefly disable interrupts so you get a clean, unsplit number.
noInterrupts();
long c = count;
interrupts();Why These Rules Matter
Follow these rules and your ISR stays fast and predictable. Break them and you get freezes, lost data, or values that never seem to update.
Quick Check
Why must a variable shared between an ISR and the loop be marked volatile?
Recap
You learned to keep an ISR short, mark shared data volatile, skip delay and Serial, and do the real work back in the loop. 🎉
Часто задаваемые вопросы
Урок «Написание безопасного ISR» бесплатный?
Да — полный текст урока «Написание безопасного ISR» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Arduino & IoT Academy, подпишись на CoddyKit PRO. Курс Arduino & IoT Academy содержит 4 уроков всего.
Чему я научусь в уроке «Написание безопасного ISR»?
Делайте обработчики прерываний короткими и используйте volatile. Ты практикуешь Arduino & IoT Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Arduino & IoT Academy?
Предыдущий опыт не требуется. Arduino & IoT Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 3 из 4.
Сколько времени занимает урок «Написание безопасного ISR»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Arduino & IoT Academy?
Да. Каждый урок Arduino & IoT Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Опрос или прерывания
- attachInterrupt на контакте
- Написание безопасного ISR
- Подсчёт импульсов энкодера