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 int Button(unsigned int *port, unsigned int pin, unsigned int time, unsigned int active_state);

Description

The function eliminates the influence of contact flickering upon pressing a button (debouncing). The Button pin is tested just after the function call and then again after the debouncing period has expired. If the pin was in the active state in both cases then the function returns 255 (true).

Parameters
  • port: button port address
  • pin: button pin
  • time: debouncing period in milliseconds
  • active_state: determines what is considered as active state. Valid values: 0 (logical zero) and 1 (logical one)
Returns
  • 255 if the pin was in the active state for given period.
  • 0 otherwise
Requires

Nothing.

Example

Stellaris

unsigned int oldstate;

void main() {

  GPIO_Digital_Input(&GPIO_PORTE_DATA_BITS, _GPIO_PINMASK_1);    // Set PE1 as digital input
  GPIO_Digital_Output(&GPIO_PORTF_DATA_BITS, _GPIO_PINMASK_ALL); // Set GPIO_PORTF as digital output
  oldstate = 0;
  
  do {
    if (Button(&GPIO_PORTE_DATA, 1, 1, 1))                      // detect logical one on PE1 pin
      oldstate = 1;
    if (oldstate && Button(&GPIO_PORTE_DATA, 1, 1, 0)) {        // detect one-to-zero transition on PE1 pin
      GPIO_PORTF_DATA = ~GPIO_PORTF_DATA;                       // invert GPIO_PORTF value
      oldstate = 0;
    }
  } while(1);                                                   // endless loop
}

STM32

unsigned int oldstate;

void main() {

  GPIO_Digital_Input(&GPIOA_IDR, _GPIO_PINMASK_0);         // Set PA0 as digital input
  GPIO_Digital_Output(&GPIOD_ODR, _GPIO_PINMASK_ALL);      // Set PORTD as digital output
  oldstate = 0;
  
  do {
    if (Button(&GPIOA_IDR, 0, 1, 1))                      // detect logical one on PA0 pin
      oldstate = 1;
    if (oldstate && Button(&GPIOA_IDR, 0, 1, 0)) {        // detect one-to-zero transition on PA0 pin
      GPIOD_ODR = ~GPIOD_ODR;                             // invert PORTD value
      oldstate = 0;
    }
  } while(1);                                             // endless loop
}
Notes

None.

Copyright (c) 2002-2019 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