• Stars
    star
    423
  • Rank 102,544 (Top 3 %)
  • Language
    C++
  • License
    GNU General Publi...
  • Created over 12 years ago
  • Updated 10 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Arduino library to debounce button switches, detect presses, releases, and long presses

Arduino Button Library

https://github.com/JChristensen/JC_Button
README file

License

Arduino Button Library Copyright (C) 2018-2019 Jack Christensen GNU GPL v3.0

This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License v3.0 as published by the Free Software Foundation.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program. If not, see https://www.gnu.org/licenses/gpl.html

Introduction

The Button library is for debouncing and reading momentary contact switches like tactile button switches. "Long presses" of arbitrary length can be detected. Works well in state machine constructs. Use the read() function to read each button in the main loop, which should execute as fast as possible.

The simplest way to use a button with an AVR microcontroller is to wire the button between a GPIO pin and ground, and turn on the AVR internal pullup resistor. The Button class constructor takes four arguments, but three have default values that work for a button wired in this manner.

A derived class, ToggleButton, implements button objects that need only "push-on, push-off" functionality.

Examples

The following example sketches are included with the Button library:

  • SimpleOnOff: Just turns the Arduino's pin 13 LED on and off.
  • LongPress: Demonstrates detecting long and short button presses.
  • UpDown: Counts up or down, one number at a time or rapidly by holding the button down.
  • Toggle: Demonstrates ToggleButton functionality.

Constructors

Button(pin, dbTime, puEnable, invert)

Description

The constructor defines a button object.

Syntax

Button(pin, dbTime, puEnable, invert);

Required parameter

pin: Arduino pin number that the button is connected to (byte)

Optional parameters

dbTime: Debounce time in milliseconds. Defaults to 25ms if not given. (unsigned long)
puEnable: true to enable the microcontroller's internal pull-up resistor, else false. Defaults to true if not given. (bool)
invert: false interprets a high logic level to mean the button is pressed, true interprets a low level as pressed. true should be used when a pull-up resistor is employed, false for a pull-down resistor. Defaults to true if not given. (bool)

Returns

None.

Example
// button connected from pin 2 to ground, 25ms debounce, pullup enabled, logic inverted
Button myButton(2);

// same as above but this button needs a longer debounce time (50ms)
Button myButton(3, 50);

// a button wired from the MCU pin to Vcc with an external pull-down resistor
Button myButton(4, 25, false, false);

ToggleButton(pin, initialState, dbTime, puEnable, invert)

Description

The constructor defines a toggle button object, which has "push-on, push-off" functionality. The initial state can be on or off. See the section, ToggleButton Library Functions for functions that apply specifically to the ToggleButton object. The ToggleButton class is derived from the Button class, so all Button functions are available, but because it is inherently a more limited concept, the special ToggleButton functions will be most useful, along with begin() and read().

Syntax

ToggleButton(pin, initialState, dbTime, puEnable, invert);

Required parameter

pin: Arduino pin number that the button is connected to (byte)

Optional parameters

initialState: Initial state for the button. Defaults to off (false) if not given. (bool)
dbTime: Debounce time in milliseconds. Defaults to 25ms if not given. (unsigned long)
puEnable: true to enable the microcontroller's internal pull-up resistor, else false. Defaults to true if not given. (bool)
invert: false interprets a high logic level to mean the button is pressed, true interprets a low level as pressed. true should be used when a pull-up resistor is employed, false for a pull-down resistor. Defaults to true if not given. (bool)

Returns

None.

Example
// button connected from pin 2 to ground, initial state off,
// 25ms debounce, pullup enabled, logic inverted
ToggleButton myToggle(2);

// same as above but this button is initially "on" and also
// needs a longer debounce time (50ms).
ToggleButton myToggle(3, true, 50);

// a button wired from the MCU pin to Vcc with an external pull-down resistor,
// initial state is off.
Button myButton(4, false, 25, false, false);

Button Library Functions

begin()

Description

Initializes the Button object and the pin it is connected to.

Syntax

myButton.begin();

Parameters

None.

Returns

None.

Example
myButton.begin();

read()

Description

Reads the button and returns a boolean value (true or false) to indicate whether the button is pressed. The read() function needs to execute very frequently in order for the sketch to be responsive. A good place for read() is at the top of loop(). Often, the return value from read() will not be needed if the other functions below are used.

Syntax

myButton.read();

Parameters

None.

Returns

true if the button is pressed, else false (bool)

Example
myButton.read();

isPressed()

isReleased()

Description

These functions check the button state from the last call to read() and return false or true accordingly. These functions do not cause the button to be read.

Syntax

myButton.isPressed();
myButton.isReleased();

Parameters

None.

Returns

true or false, depending on whether the button has been pressed (released) or not (bool)

Example
if ( myButton.isPressed() )
{
	//do something
}
else
{
	//do something else
}

wasPressed()

wasReleased()

Description

These functions check the button state to see if it changed between the last two calls to read() and return false or true accordingly. These functions do not cause the button to be read. Note that these functions may be more useful than isPressed() and isReleased() since they actually detect a change in the state of the button, which is usually what we want in order to cause some action.

Syntax

myButton.wasPressed();
myButton.wasReleased();

Parameters

None.

Returns

true or false, depending on whether the button was pressed (released) or not (boolean)

Example
if ( myButton.wasPressed() )
{
	//do something
}

pressedFor(ms)

releasedFor(ms)

Description

These functions check to see if the button is pressed (or released), and has been in that state for the specified time in milliseconds. Returns false or true accordingly. These functions are useful to detect "long presses". Note that these functions do not cause the button to be read.

Syntax

myButton.pressedFor(ms);
myButton.releasedFor(ms);

Parameters

ms: The number of milliseconds (unsigned long)

Returns

true or false, depending on whether the button was pressed (released) for the specified time (bool)

Example
if ( myButton.pressedFor(1000) )
{
    // button has been pressed for one second
}

lastChange()

Description

Under certain circumstances, it may be useful to know when a button last changed state. lastChange() returns the time the button last changed state, in milliseconds (the value is derived from the Arduino millis() function).

Syntax

myButton.lastChange();

Parameters

None.

Returns

The time in milliseconds when the button last changed state (unsigned long)

Example
unsigned long msLastChange = myButton.lastChange();

ToggleButton Library Functions

changed()

Description

Returns a boolean value (true or false) to indicate whether the toggle button changed state the last time read() was called.

Syntax

myToggle.changed();

Parameters

None.

Returns

true if the toggle state changed, else false (bool)

Example
if (myToggle.changed())
{
    // do something
}
else
{
    // do something different
}

toggleState()

Description

Returns a boolean value (true or false) to indicate the toggle button state as of the last time read() was called.

Syntax

myToggle.toggleState();

Parameters

None.

Returns

true if the toggle is "on", else false (bool)

Example
if (myToggle.toggleState())
{
    // do something
}
else
{
    // do something different
}

More Repositories

1

DS3232RTC

Arduino Library for Maxim Integrated DS3232 and DS3231 Real-Time Clocks
C++
393
star
2

Timer

A fork of Simon Monk's Arduino Timer library
C++
372
star
3

Timezone

Arduino library to facilitate time zone conversions and automatic daylight saving (summer) time adjustments.
C++
279
star
4

tinySPI

Arduino hardware SPI library for ATtiny44/84, 45/85, 461/861, 2313/4313.
C++
154
star
5

extEEPROM

Arduino library to support external I2C EEPROMs.
C++
114
star
6

movingAvg

A simple Arduino library for calculating moving averages.
C++
90
star
7

MCP79412RTC

Arduino library for the Microchip MCP79411/12 Real-Time Clock/Calendar
C++
22
star
8

CurrentTransformer

Arduino Current Transformer Library
C++
16
star
9

mini1284

A minimal breadboard-friendly design for the ATmega1284P MCU
16
star
10

JC_EEPROM

Arduino library to support external I2C EEPROMs.
C++
14
star
11

usb-condom

A little something for the tinfoil hat crowd.
13
star
12

Thermocouple

Thermocouple library for Arduino and MAX6675
Java
11
star
13

millionOhms_SW

Warning One Million Ohms (firmware): Amuse your friends and confuse your enemies! Keep the uninititated away from your desk or out of your lab!
C++
10
star
14

PowerOutageMonitor_SW

Sketch for an Arduino-based Power Outage Logger
C++
9
star
15

TinyWireM

My modifications to the TinyWireM library from the Arduino Playground
C++
8
star
16

serialLogger

An Arduino-Compatible Serial Data Logger
C++
8
star
17

JC_Sunrise

Arduino library to calculate sunrise and sunset times.
C++
8
star
18

PowerOutageMonitor_HW

Arduino-Based Power Outage Logger PC Board
8
star
19

tinyTorch

Hardware design for a small LED flashlight powered by an ATtiny84A.
Eagle
6
star
20

MCP9808

Arduino Library for Microchip MCP9808 Maximum Accuracy Digital Temperature Sensor
C++
6
star
21

gpsFreq

Arduino frequency counter library, uses a 1 Hz (PPS) signal from a GPS receiver as an accurate time base
C++
6
star
22

nightLight

An Arduino-based demonstration/educational project with several interesting hardware and software features.
Java
5
star
23

rtc79412

Breakout Board for the Microchip MCP79412 Real-Time Clock/Calendar
5
star
24

geiger

Firmware for the MightyOhm Geiger Counter
C
4
star
25

tinyTorch-fw

Firmware for a small LED flashlight powered by an ATtiny84A.
C++
4
star
26

ledFire_HW

LED PWM Fire Effect using ATtiny84A (hardware design)
3
star
27

FiveLEDs

My spin on Technoblogy's Five LEDs Puzzle.
C++
3
star
28

ledFire_FW

LED PWM Fire Effect using ATtiny84A (firmware)
Arduino
3
star
29

aaLogger_SW

Code for the Double-A DataLogger - A low-power Arduino-based data logger.
Arduino
3
star
30

GroveStreams

GroveStreams Library for Arduino
C++
3
star
31

ds18b20

C++
3
star
32

CurrentMonitor

Arduino-compatible board to measure AC mains current with current transformers
2
star
33

piXBee

Interfaces Andrew Rapp's XBee-Arduino library to C++ running on a Raspberry Pi.
C++
2
star
34

jcGoldieClock

My firmware for LarryD's Goldie Clock
C++
2
star
35

MCP9800

Arduino Library for Microchip MCP9800/1/2/3 2-Wire High-Accuracy Temperature Sensors
C++
2
star
36

larson84

Firmware for the tinyLarson scanner
C++
2
star
37

jc_MAX31856

Arduino library for the Maxim Integrated MAX31856 Thermocouple to Digital Converter
C++
2
star
38

tinyLarson

Larson scanner powered by an ATtiny84a
2
star
39

tinyTimer

A small battery-operated timer based on an ATtiny84A.
1
star
40

rtc7941x

MCP78411/12 RTC Break-Out Board with MCP9800/2 Temperature Sensor
1
star
41

aaLogger_HW

Schematic and board for the Double-A DataLogger - A low-power Arduino-based data logger.
1
star
42

Vetinari_SW

Arduino
1
star
43

aaXBee_HW

Double-A XBee Sensor Node
Eagle
1
star
44

Vetinari_HW

1
star
45

xmasCandles

Arduino-powered Christmas Window Candles
Arduino
1
star
46

gsXBee

Arduino XBee Library for GroveStreams Wireless Sensor Network
C++
1
star
47

bbhTinyX5

ATtinyX5 Breadboard Helper, the easiest way to breadboard an ATtiny microcontroller!
1
star
48

entropyTest

A sketch to test the Arduino Entropy library at http://code.google.com/p/avr-hardware-random-number-generation/ and capture the data to an SD card.
Arduino
1
star
49

dotstar4

Simple board to hold four APA102C addressable RGB LEDs.
1
star
50

Ethernet

A modified version of the Ethernet library from Arduino 1.8.5 that supports both the WIZnet W5100 and W5200 chips.
C++
1
star
51

ac-timer-panel

Small PCB to support switch and LEDs for AC timer project.
1
star
52

bbhTinyX4

ATtinyX4 Breadboard Helper, the easiest way to breadboard an ATtiny microcontroller!
1
star
53

ac-timer-hw

Arduino-based daily timer for AC appliances.
1
star
54

aaXBee

Arduino-based wireless sensor node using XBee-ZB. Powered by two AA cells.
C++
1
star
55

Trace

Bash script to run traceroute for a given IP and log the results to a file.
Shell
1
star
56

backup

A simple rsync backup script
Shell
1
star
57

dehumid

A daily timer sketch for Arduino to control a 120VAC appliance according to a schedule with a solid-state relay.
C++
1
star
58

Minimal-Sensor-Network

A minimal Arduino/XBee/Pachube sensor network
1
star
59

Arduino-Breadboard-Helpers

Two small breakout boards that make building an Arduino-compatible breadboard a snap!
1
star