Today’s pattern (configure a timer, let its interrupt do the timekeeping, keep the main loop for real work) is great preparation for Lab 5, where a timer interrupt paces the ADC in a temperature controller.
The homework can be done in the simulator as well as on your board. The link below opens the simulator with the ADCPot.c starter. Paste your own finished ADCPot.c in its place, then click + Pot in the component bay to the right of the board and click the Arduino header pin labeled A0.
Modify your ADCPot.c from Day 7 so that, in addition to performing the ADC readings, the on-board LED blinks at a steady rate of one-third of a second on, one-third of a second off, using a timer interrupt. Hint: you may wish to toggle the LED directly in the ISR: consider what the main loop is busy doing, and for how long at a stretch.
Choose your prescaler and auto-reload values so the period is exact, and show the arithmetic in a comment. One-third of a second does not divide as conveniently as 500 ms did: more than one pair works, but not every pair you might like.
Figure8.2.20.The homework’s structure, from the class deck: the main loop cycles through start-conversion, read, print, and its delay, while the timer interrupt arrives on its own schedule; each arrival runs the ISR (clear the flag, toggle the LED) and returns exactly where main was suspended. The main loop and the ISR run independently.
And a challenge, for fun, nothing to submit: make the blink asymmetric, 200 ms on and 800 ms off. One timer, two different intervals: the code must reprogram ARR on the fly and remember which phase it is in. A state machine with two states does it in a dozen lines.
Main cycles read-print-delay; the ISR toggles the LED on the timer’s schedule.
Blinky with T_on ≠T_off: 200 ms on, 800 ms off. One timer, two intervals: reprogram ARR on the fly and remember which phase you are in. A two-state machine does it in a dozen lines.