Search code examples
microcontrollerkeydownkeyup8051debouncing

Simplest code to handle any key press - 8051


I'm trying to figure out the best approach to my problem. I have an AT89S52 microcontroller with 3 buttons connected to 3 separate GPIO pins so that the microcontroller can perform different functions based on those buttons.

I'm trying to write code that waits for the user to press any of the three keys. By key press, I mean where the system detects any one key is fully pressed down and then fully released.

The code I presented below might work if I added a schmitt trigger in my hardware but I don't want to redo my circuit board (again).

Without adding interrupts, is there a way I can modify the code shown with just a few lines to reliably detect a user key press?

I ask because keys experience a phenomenon called "bouncing" where as soon as someone presses a key, it actually jitters at high speed and the microcontroller will see it as key being pressed and released multiple times. I don't want that to happen if the user legitimately pressed the key only once.

;KEY1I, KEY2I and KEY3I = GPIO pins connected to the keys
;Pin value is low when key is held down

w4key:
  ;begin key scan
  jnb KEY1I,w4keyend
  jnb KEY2I,w4keyend
  jnb KEY3I,w4keyend
  ;here, nothing is pressed so scan again
sjmp w4key
w4keyend:
  ;key pressed. Hope for release
  jnb KEY1I,w4key
  jnb KEY2I,w4key
  jnb KEY3I,w4key
  ;here, key is released so return.
ret

mainline:
  ;do something
  acall w4key
  ;do another thing
...

Solution

  • You can use a timer (AT89S52 has several timers, you can use one of them if there are not otherwise used in your project) and a synchronous state machine. The state machine has 4 states for every key and definite transitions. I found this link that explains the concept quite thorough. Although the provided example code in this link is in C, you can easily "translate" it to your assembly code. If you need help with this, just leave a comment.

    https://www.eeweb.com/profile/tommyg/articles/debouncing-push-buttons-using-a-state-machine-approach