Tutorial 2: Port B Keypad Decoder

Decoding a keypad is a common and useful task. The PIC16F877 has several useful features for making keypad decoding easy. Firstly, pins of PORTB have an internal pullup resistor which can switched on saving the need for external pullup resistors. Secondly, PORTB<4:7> has an interrupt on change which when enabled detects if any changes have occured on any of the pins in  PORTB<4:7>. In this example a KEYPAD4x4 is connected directly to PORTB, in practice you would connect via a serial resistor (refer Microchip Application Note AN552). PORTB<0:3> are used to scan the Keypad, while PORTB<4:7> with pullup resistors enabled are used to read the result. The keyscan routine returns an ASCII value for the key pressed, which is displayed on PORTC. A handy Virtual Breadboard component DIGITAL8 configured for ASCII view is used to see the value of the Key on PORTC.

Download FEATURE877_Tutorial2.zip and unzip into folder <your path>\Tutorial 2

Filename Version Description
tut2.pjt 1.0 MPLAB Project
tut2.asm 1.0 PIC16F877 Assembler code
keyscan.asm 1.0 Support Routines for Scanning the Keypad
tut2.HEX 1.0 Precompiled HEX
tut2.LST 1.0 Precompiled LST
tut2.vbb 1.0 Virtual Breadboard simulation

Running the Simulation

Open tut2.vbb and press RUN. Use the keypad to press a new key. After a short delay the value of the key pressed should appear in the DIGITAL8 component.

Code Walk Through

 

 

Points to Note

There is a tricky gotcha with the Pullups on PORTB. The PIC16F877 sees the pullups internally but externally to the rest of the circuit the pullup voltages do not appear. It is as if there is a reverse diode on the pin. If you need the pullup in your external circuit you will need to use the discrete PULLUP component until this is fixed.

The KEYPAD4x4 component uses BOUNCE mode to simulate the mechanical contact bouncing typical of switches. If BOUNCE is not used however, the KEYPAD will switch from one key to another without breaking the contact. Without a break, no change on PORTB will occurs if a key on the same column is pressed. And if no change occurs on PORTB the interrupt will not be triggered to read the new keypress so the Key display is not updated.

Features Demonstrated

TRISB

PORTB

PORTB PULLUP

TRISC

PORTC

PORTB Change Interrupt

Wakeup from Sleep