Button Library

The Button Library provides routines for detecting button presses and debouncing (eliminating the influence of contact flickering upon pressing a button).

Library Routines

Button

Prototype

unsigned short Button(unsigned short *port, unsigned short pin, unsigned short time, unsigned short active_state);

Returns

  • 255 if the pin was in the active state for given period.
  • 0 otherwise

Description

Function eliminates the influence of contact flickering upon pressing a button (debouncing).

Parameter port specifies the location of the button; parameter pin is the pin number on designated port and goes from 0..7; parameter time is a debounce period in milliseconds; parameter active_state can be either 0 or 1, and it determines if the button is active upon logical zero or logical one.

Requires

Button pin must be configured as input.

Example

Example reads RB0, to which the button is connected; on transition from 1 to 0 (release of button), PORTD is inverted:

bit oldstate;                                    // Old state flag

void main() {

  ANSEL  = 0;                                    // Configure AN pins as digital I/O
  ANSELH = 0;
  C1ON_bit = 0;                                  // Disable comparators
  C2ON_bit = 0;

  TRISB0_bit = 1;                                // set RB0 pin as input
  
  TRISC = 0x00;                                  // Configure PORTC as output
  PORTC = 0xAA;                                  // Initial PORTC value
  oldstate = 0;
  
  do {
    if (Button(&PORTB, 0, 1, 1)) {               // Detect logical one
      oldstate = 1;                              // Update flag
    }
    if (oldstate && Button(&PORTB, 0, 1, 0)) {   // Detect one-to-zero transition
      PORTC = ~PORTC;                            // Invert PORTC
      oldstate = 0;                              // Update flag
    }
  } while(1);                                    // Endless loop
}
Copyright (c) 2002-2012 mikroElektronika. All rights reserved.
What do you think about this topic ? Send us feedback!
Want more examples and libraries? 
Find them on LibStock - A place for the code