Отладка и интеграция
ВведеноВ этом уроке
| English | Значение |
|---|---|
| watchdog/ˈwɒtʃdɒɡ/ | Сторожевой таймер |
| debounce/ˈdebaʊns/ | Блокировка контактов |
"It froze twice last night"
- Every firmware bug starts as a vague report. Firmware is tested on the exact hardware it ships on, and the fault rarely appears when someone is watching.
- Without a method you often only move a bug instead of fixing it. This lesson gives that method.
The debug loop
- Reproduce the fault with the smallest input. Isolate it at a boundary with an LED, a breakpoint or one UART print.
- Fix one thing, then re-verify. Two changes at once leave you unsure which one helped.

Расставьте отладочный цикл в правильном порядке.
Сложность 3/5 · 200 монет + небольшой бонус за первое завершение сегодня
Без воспроизведения невозможно определить, помогло ли исправление; устранение нескольких проблем одновременно скрывает, какая именно из них была причиной.
Bisection
- Put a probe in the middle of the suspect code. Whether the probe fires before the fault tells you which half holds the bug.
- Each probe halves the range, so $\log_{2}(n)$ probes find one instruction among $n$: ten for 1024.
Двоичный поиск проверяет 512 подозрительных инструкций. Какое максимальное количество проверок ему потребуется?
Сложность 2/5 · 140 монет + небольшой бонус за первое завершение сегодня
Каждый зонд уменьшает диапазон вдвое: $\log_{2} 512 = 9$.
Подозрительная область содержит 4096 инструкций. Сколько запусков бинарного поиска потребуются для выявления ошибочной?
Сложность 2/5 · 140 монет + небольшой бонус за первое завершение сегодня
$2^{12} = 4096$, следовательно, 12 запусков. Удвоение кода добавляет лишь один дополнительный запуск.
The watchdog
- A watchdog 看门狗 is a counter that resets the chip if it runs out. The firmware must "kick" it (restart the count) regularly.
- A hung system then reboots by design instead of freezing. Kick it only from the main loop, never from an ISR.
Почему неправильно сбрасывать сторожевой таймер внутри обработчика прерывания?
Сложность 1/5 · 100 монет + небольшой бонус за первое завершение сегодня
Если обработчик прерывания сбрасывает сторожевой таймер, основной цикл может зависнуть, пока прерывания продолжают его обновлять, и перезапуск никогда не произойдёт.
Debounce
- A pressed button bounces: its contact opens and closes for a few milliseconds. Debounce 消抖 accepts a new state only after N equal readings in a row.
- It combines a timer tick, a GPIO read and a state decision: the whole course in one routine.
Worked example: a debounce trace
- Samples every 10 ms read 1, 0, 0, 1. Rule: two equal readings in a row.
- At 10 ms there is one 0; at 20 ms a second 0, so a stable 0 is declared. The 1 at 30 ms is a single sample and is ignored.
One contrary reading does not erase the qualified state
$N\text{ equal sampled readings span }(N-1)\Delta t$
Step through the worked 1,0,0,1 trace at 10 ms intervals with two equal readings required. The first qualified 0 appears at 20 ms; the later single 1 does not reverse it. Edit samples, compare a one-sample pulse and an alternating input, and change N to distinguish input chatter from accepted output changes. Startup remains unqualified until a state earns enough consecutive readings.
Образцы 1, 0, 0, 1 поступают каждые 10 мс, начиная с момента 0 мс. При использовании правила «два подряд», когда объявляется стабильное состояние?
Сложность 1/5 · 100 монет + небольшой бонус за первое завершение сегодня
При 10 мс есть одно значение 0, но нет вердикта; при 20 мс второе измерение 0 формирует устойчивое состояние 0. Значение 1 при 30 мс представляет собой единичную выборку.
Правило требует трёх последовательных равных показаний, снимаемых каждые 5 мс начиная с момента 0 мс. Показания имеют значения 0, 1, 0, 1, 1, 1. В какой момент времени (в мс) объявляется устойчивое состояние 1?
Сложность 2/5 · 140 монет + небольшой бонус за первое завершение сегодня
Показания 1 в моменты 15, 20 и 25 мс являются первыми тремя подряд, поэтому вердикт выносится при 25 мс.
Worked example: bisecting the freeze
- The suspect region is 1024 instructions. Make instruction 512 light the LED: dark at the freeze means the first half; lit means the second.
- Each run halves the region: 512, 256, 128 … after ten runs, one instruction is left, because $2^{10} = 1024$.
Three common slips
- Fixing two things at once. One helps, one breaks something else, and now there are three bugs.
- Testing on another board. Debug on the same board revision that failed.
- Turning off the watchdog "for now". The field failure it would have survived is exactly the one that ships.
Во время отладки хорошей практикой является отключение сторожевого таймера и его оставление выключенным после устранения ошибки.
Сложность 1/5 · 100 монет + небольшой бонус за первое завершение сегодня
Продукт, выпущенный без сторожевого таймера, зависает в полевых условиях вместо перезагрузки. Если он должен быть отключён на время сессии, включите его обратно перед релизом.
Recap
- Reproduce, bisect, fix one thing, re-verify.
- $\log_{2}(n)$ probes find the fault among $n$ instructions:
| Instructions $n$ | 1024 | about 1 million |
|---|---|---|
| Probes | 10 | 20 |
- Debounce needs N equal readings in a row; kick the watchdog from the main loop only.
Что пошло не так? Это увидит только команда сайта.