Skip to main content

Subsection 3.2.4 Part 3: Start the Keyboard Counter

Your counter currently only sends data. Next we’ll add the receive side, so that pressing a key in CoolTerm changes the count. The difficulty is doing that without freezing the 500 ms print loop, and the way around it is to poll the RXNE flag, which stands for receive data register not empty. Use the technique below and test it in CoolTerm.

Activity 3.2.4. Keyboard-Controlled Counter.

Modify counter.c so that:
  • The counter no longer auto-increments. It only changes when one of the control keys below is pressed. Any other key, or no key at all, leaves the count unchanged and the same value prints every 500 ms.
  • Pressing u or U increments the counter.
  • Pressing d or D decrements it.
  • Pressing r or R resets it to zero.
Use the RXNE (receive data register not empty) flag for a non-blocking receive: if a byte is waiting in the receive register, read it and act on it; if not, skip straight to the print and delay. Do not call uart2_read(). That function blocks until a byte arrives and will freeze the counter.
while (1) {
    if (USART2->ISR & USART_ISR_RXNE_RXFNE) {
        char key = /* read the character from the right register */;
        // handle key here ...
    }
    printf("count = %d\r\n", count);
    delay_ms(500);
}
Test it in CoolTerm: type a key and confirm the count changes on the next print line.
Optional challenge: Change the counter so that pressing u or U sets the direction to “up” and pressing d or D sets the direction to “down”, and then the counter keeps incrementing or decrementing automatically every 500 ms, even when no further key is pressed. Pressing r or R resets the count to zero and pauses auto-counting until a new direction key is received.
The link below opens the same exercise in the simulator, for working on it away from your Nucleo. The panel below the editor is a stand-in for CoolTerm: printf output arrives there, and clicking it lets you type back to the board. The RXNE flag and USART2->RDR behave as they do on hardware, and you can watch both in the register panel as you type. The terminal also decodes at whatever baud rate you select in it, so you can reproduce the baud-rate mismatch you saw earlier today without touching a cable. The simulator does not save your code, so use the download button (the downward arrow) to keep a copy of your work.