Subsection 2.7.4 Part 4: Implementing a State Machine in C
Now we’ll turn one of the diagrams you just drew into working code, using the
typedef enum and
switch pattern from earlier today.
Activity 2.7.3. Implementing Your FSM.
Start from your
toggleLED.c or
blinkyCNT.c project. Replace any blocking logic or bare flag variables with a proper FSM.
(a)
Implement the pause/resume counter FSM. The counter should blink the LEDs in binary (as in
blinkyCNT.c) and a button press should pause or resume counting. Test it: does a single physical press always produce exactly one state change?
(b)
If you finish early, implement the 3-state LED cycling FSM from your diagram. Or: add a second button that resets the counter to zero from either state. How does the state diagram change?
(c)
Verify on the oscilloscope that the LED transitions are clean (no multiple toggles per press) both with and without the debounce capacitor.
The link below opens the simulator loaded with the button toggle written as a state machine, with
typedef enum and
switch, as it is printed in
Subsection 2.7.2, so you can work on the pause/resume counter away from your Nucleo. Attach the button first: click
+ Button in the component bay, then click the Arduino header pin D5 (PB4). Each press toggles the on-board LED. For the counter, attach three LEDs the way you wired them in Lab 1: click
+ LED and then the Arduino header pin D13 (PA5), and do the same for D12 (PA6) and D11 (PA7). The on-board LED is also on PA5, so it lights together with the first. When you test your counter here, try a quick tap as well as a press held down.
One warning: the debouncing capacitor across the switch (
Figure 2.4.5) is not modeled, so nothing here bounces, and a single press that gives exactly one state change in the simulator is not evidence that your machine is right on the real switch. There is no oscilloscope here either, so checking that the LED transitions are clean with and without the capacitor needs your Nucleo and the AD2.
The simulator does not save your code, so use the download button (the downward arrow) to keep a copy of your work.
Open in the board simulator (new tab)