AnsweredAssumed Answered

4x3 keypad improved with autorepeat and debounce

Question asked by piovan.stefano on Dec 24, 2010
Latest reply on Jan 2, 2011 by piovan.stefano
Hi all,

Here's an improved code for the 4x3 keypad with debounce and autorepeat.
With STM8S 2MHz clock it performs pretty close to the PC keyboard.
The action() function is out from the keypad management state machine for clarity.
Suggestions and improvements are welcome.

Hope it helps.

Merry Xmas and happy holidays
Steven



u8 key = 255;
u8 oldkey = 255;
u8 AutoRptMax = 64;
u8 AutoRptCount = 0;

while(1)
    {
        key = GetKeyPressed(); //Scan the keypad to getting the code of the key pressed
    
        // < Is it a valid key pressed ? >
        if (key < 12) // YES
        {
            // < Is key still the old one ? >
            if (key == oldkey) // YES
            {
                // (Start counting for autorepeat to occour)
                DelayMS(50);
                AutoRptCount++;
                
                // < Is time to execute the key action? >
                if (AutoRptCount >= AutoRptMax) // YES
                {
                    Action(key); // perform the action according to the key code
                    AutoRptCount = 0; // reset the autorepeat counter to get ready for the next autorepeat event
                    AutoRptMax = 16; // make the autorepeat limit short for speeding up the next repetition when keeps keypressing
                }
            }
            else // NO, the key is new brand
            {
                Action(key); // perform the action according to the key code
                DelayMS(50); // and also make a little debouncing
            }
            
        } // END if (key < 12)
        
        else // NO, the key is not among the 12 defined keys
        {
            // < Was the key pad released ? >
            if (oldkey < 255 ) // YES
            {
                AutoRptCount = 0; // reset the autorepeat counter
                AutoRptMax = 128; // and restart using the first typing delay long
            }            
        }
        
        oldkey = key;
    }




void Action(u8 key)

{
    switch(key)
    {
        case 9: // backspace (mode entry is "right after writing" so we need to cursor left twice)
            LCD_DATA(0x10,0);
            LCD_CHR(32);
            LCD_DATA(0x10,0);
        break;

        case 11:
            LCD_DATA(0x14,0); // cursor right
        break;
       
        default:
            LCD_CHR(key + 48 + 1); // display keycode
        break;
    }
}


void DelayMS(int delay)

{
    int nCount = 0;
    while (delay != 0)
    {
        nCount = 100;
        while (nCount != 0)
        {
            nCount--;
        }
        delay--;
    }
}

Outcomes