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
uorUincrements the counter. -
Pressing
dorDdecrements it. -
Pressing
rorRresets 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.
