Datasheet
PICkit™ 3 Debug Express Lessons
© 2009 Microchip Technology Inc. DS41370C-page 31
FIGURE 3-22: LESSON 4 “SWITCH INPUT” SOURCE CODE
3.4.3.1 VARIABLES
This program has 2 declared variables, the global variable LED_Display and the local
variable Switch_Count. A global variable will be placed in a dedicated location in the
file register space as discussed in Lesson 3. A local variable is placed on the software
stack, and is created when a function is entered, and destroyed (removed from the
stack) when the function exits.
3.4.3.2 SWITCH INPUT
The demo board switch is connected to I/O pin RB0, which is normally pulled up to V
DD
internally. When the switch is pressed, it pulls RB0 to ground (low state).
The PORTx Special Function Registers are used to read the state of an input pin.
Therefore, reading PORTBbits.RB0 will give the value of the signal on the RB0 pin.
Don’t forget – in the header file, this was defined as Switch_Pin, which is what the
code uses to read the pin value:
#define Switch_Pin PORTBbits.RB0
/** V A R I A B L E S *************************************************/
#pragma udata // declare statically allocated uinitialized variables
unsigned char LED_Display; // 8-bit variable
/** D E C L A R A T I O N S *******************************************/
#pragma code// declare executable instructions
void main (void)
{
while (Switch_Count < DetectsInARow);
unsigned char Switch_Count = 0;
LED_Display = 1; // initialize
TRISD = 0b00000000; // PORTD bits 7:0 are all outputs (0)
INTCON2bits.RBPU = 0; // enable PORTB internal pullups
WPUBbits.WPUB0 = 1; // enable pull up on RB0
ANSELH = 0x00; // AN8-12 are digital inputs (AN12 on RB0)
TRISBbits.TRISB0 = 1; // PORTB bit 0 (connected to switch) is input (1)
while (1)
{
LATD = LED_Display; // output LED_Display value to PORTD LEDs
LED_Display <<= 1; // rotate display by 1
if (LED_Display == 0)
LED_Display = 1;
// rotated bit out, so set bit 0
while (Switch_Pin != 1);// wait for switch to be released
Switch_Count = 5;
do
{ // monitor switch input for 5 lows in a row to debounce if
(Switch_Pin == 0)
{ // pressed state detected
Switch_Count++;
}
else
{
Switch_Count = 0;
}
Delay10TCYx(25); // delay 250 cycles or 1ms. }