Coder Social home page Coder Social logo

dlloydev / toggle Goto Github PK

View Code? Open in Web Editor NEW
10.0 1.0 2.0 112 KB

Arduino button debounce library for various switch types, port expanders and other 8-bit data sources. Fast and robust debounce algorithm.

License: MIT License

C++ 100.00%
debounce switch toggle sp3t arduino debounce-button limit-switch microswitch pushbutton spdt

toggle's Introduction

Toggle arduino-library-badge PlatformIO Registry

Arduino button debounce library for various switch types, port expanders and other 8-bit data sources. Fast and robust debounce algorithm.

Features

  • Fast, robust and symetrical debouncing of both press and release button transitions
  • Works with various switch types and connections.
  • Identifies 7 unique transitions for 3-position switches
  • Use momentary button as toggle switch (configurable)
  • Return up to 225 codes from one button

Examples (Wokwi)

  • Do a test run for evaluation.
  • Your suggestions, Issues and Discussions are welcome here.
ESP32-S2 UNO
Toggle_Basic Toggle_Basic
Use_Button_As_Toggle.ino Use_Button_As_Toggle.ino
Eight_Buttons.ino Eight_Buttons.ino
Pressed_For.ino Pressed_For.ino
Released_For.ino Released_For.ino
Retrigger_While_Pressed.ino Retrigger_While_Pressed.ino
Press_Code.ino Press_Code.ino
ESP32_Input_Pulldown.ino

Toggle Library Reference

To use this library

#include <Toggle.h>

Constructors

Toggle();
Toggle(inA);
Toggle(inA, inB);
Toggle(*in);
Description

The constructor defines a button object. If the default constructor is used when declaring an array of pointers to button objects, then it must be followed by a call to begin in setup.

Required parameter

inA: Arduino pin number that the button or switch is connected to (byte) , or *in: Arduino variable representing the input signal (byte)

Optional parameter

inB: Second Arduino pin number (byte). Use 2 inputs when connecting to 3 position switches.

Returns

None.

Example
Toggle myInput(2);      // Button connected pin 2 to GND, INPUT_PULLUP, debounced
Toggle myInput(2, 3);   // SPDT switch connected pins 2 and 3 to GND, INPUT_PULLUP, debounced
Toggle myInput(*Input); // Byte variable as input, debounced

poll()

Description

This function is placed at the top of the loop. Initializes the Button object and the pin it is connected to.

Syntax

myInput.poll();

Optional parameter

bit: selects the bit number from an input data (byte)

Returns

None.

Primary Functions

There are 5 primary functions when using 1 input pin or data bit. Shown below is a plot showing the returned values that are verically offset for clarity:

image

onChange()

Description

This function checks the status register to see if the button or switch has changed state and reports whether the onPress or onRelease flag has been set. Calling onChange() does not modify the status register.

Syntax

myInput.onChange();

Parameters

None.

Returns

no change (0) , onPress (1), onRelease (2) (byte)

Example
if (myInput.onChange() == 2) {
	// button was released
} else if (myInput.onChange() == 1) {
  // button was pressed
} else {
  // no change
}

onPress()

onRelease()

Description

These functions check the the status register to see if the button or switch has set the onPress or onRelease flag. These functions will return the flag status and clear the respective flag.

Syntax

myInput.onPress();

myInput.onRelease();

Parameters

None.

Returns

true or false, (bool)

Example 1
if (myInput.onPress())
{
	// do something (true only once per press)
}

isPressed()

isReleased()

Description

These functions checks the curent debounced output and its history to see if the button or switch is pressed or released.

Syntax

myInput.isPressed();

myInput.isReleased();

Optional parameter

bit: selects the bit number from an input data (byte)

Returns

true or false, (bool)

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

toggle()

Description

This function can be used to convert a momentary push button to a toggle switch. By default, the retuen value will toggle true-false then false-true for each onPress action of the button.

  • The setToggleState() function sets the initial state (true or false)
  • The setToggleTrigger() function sets the trigger mode: false: onPress, true: onRelease
Parameters

None.

Returns

true or false, (bool). Toggles as configured by setToggleTrigger(). Default is trigger onPress

Timer Functions

clearTimer()

Description

Simply clears the ms timer used for the timer functions.

Syntax

myInput.clearTimer();

Parameters

None.

Returns

None.

blink(ms, mode)

Description

This function sets the duration in milliseconds that the returned value is true. The mode parameter sets what blink responds to: onChange (0), onPress( 1) default, onRelease (2).

Syntax

myInput.blink(ms);

Parameters

ms: The number of milliseconds (unsigned int)

mode: Blink onChange (0), onPress( 1) default, onRelease (2) (byte)

Returns

true or false, depending on whether the elapsed time has expired after any state change set by the mode parameter. (bool)

Example

Toggle_Basic.ino

pressedFor(ms)

releasedFor(ms)

Description

These functions return true if the button or switch has been in the pressedFor or releasedFor state for at least the given number of milliseconds.

Syntax

myInput.pressedFor(ms);
myInput.releasedFor(ms);

Parameters

ms: The number of milliseconds (unsigned int)

Returns

true or false, depending on whether the elapsed time has expired after the state change. (bool)

Example
if (myInput.pressedFor(500)) {
   // true (once only) if button has been pressed for 500ms
}

retrigger(ms)

Description

This function checks the duration in milliseconds that the button or switch is is in the state as selected by timer mode and returns true (once only) each time the given millisecond duration has expired.

Syntax

myInput.retrigger(ms);

Parameters

ms: The number of milliseconds (unsigned int)

Returns

true or false, returns true (once only) each time the given ms duration has expired while the button is in the state as selected by timer mode. (bool)

Example
if (retrigger(500)) {
// count every 500ms interval while the button is being pressed   
} 

pressCode()

Description
  • Up to 225 possible codes with one button. The returned code (byte) is easy to interpret when viewed in hex format. For example, 47 is 4 long, 7 short presses. F2 is double-click, F7 is 7 Fast clicks.
  • Fast-click mode is detected if the first several clicks (presses) are less than 0.2 sec, then all presses are counted as fast, up to 15 max (code FF)
  • Detection of long presses occurs if the first press is greater than 0.2 sec, then all presses greater than 0.2 sec are counted as long and all presses less than 0.2 sec are counted as short presses.
  • Detect up to 15 short presses
  • Detect up to 14 long presses
  • Returns code after button is released for 0.5 sec
  • simplifies your code while adding maximum functionality to one button
Example
byte pCode = sw1.pressCode(1); // (1) serial print results
Example Sketch Press_Code.ino

Trial run on WOKWi

Set and Get Functions

setInputMode()

Description

This function sets the various options for the input source.

Syntax

myInput.inMode::input_option;

Returns

None.

Options
myInput.setInputMode(sw1.inMode::input_input);     // high impedance input
myInput.setInputMode(sw1.inMode::input_pullup);    // pullup resistor enabled (default)
myInput.setInputMode(sw1.inMode::input_pulldown);  // pulldown resistor enabled (ESP32) 
myInput.setInputMode(sw1.inMode::input_byte);      // input byte (8-bit)

setInputInvert()

Description

Set true if the button or switch pulls the signal high when pressed. Default is false (button or switch pulls the signal low when pressed).

Syntax

myInput.setInputInvert(true);

Returns

None.

setSampleUs()

Description

Sets the sample period in microseconds. Default is 5000 μs.

Syntax

myInput.setSampleUs(us);

Returns

None.

getElapsedMs(()

Description

Gets the elapsed ms since the last state change selected by timer mode.

Syntax

myInput.getElapsedMs();

Returns

Elapsed milliseconds (unsigned int).


References

toggle's People

Contributors

dlloydev avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

toggle's Issues

Triggering on first push

I have a button attached to my esp32.
And the first push is triggering the pressedfor method

#define FR_PIN  36
#define FR_PIN_FIRST_CHECK_INTERVAL_MS 10000

Toggle button(FR_PIN);

void setup(){
    Serial.begin(115200);
    button.begin(FR_PIN);
}

void loop(){
    button.poll();
    if (button.onPress()) {
          Serial.printf("[FACTORY] - Waiting for reset.\n");
    }
    if (button.onRelease()) {
          Serial.printf("[FACTORY] - Reset aborted.\n");
    }
    if (button.pressedFor(FR_PIN_FIRST_CHECK_INTERVAL_MS)) {
          Serial.printf("[FACTORY] - Reset initiated.\n");
    }
}

Debug on just a single push first time

[FACTORY] - Waiting for reset.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset initiated.
[FACTORY] - Reset aborted.

Debug on a single push the 2nd time

[FACTORY] - Waiting for reset.
[FACTORY] - Reset aborted.

What is the problem? Should i reset some kind of a timer?

challenge with enum value and FastLed library

you are using this enum

enum CLICK : uint16_t {FAST = 200, DONE = 500};

challenge is that the fastLed library is also using DONE for a #define

so if you try to compile

#include <FastLED.h>
#include <Toggle.h>

void setup() {}
void loop() {}

the compiler will complain about the double definition

first it's a cryptic

~/Documents/Arduino/libraries/FastLED/src/platforms/avr/clockless_trinket.h:308:14: error: expected identifier before 'asm'
 #define DONE asm __volatile__("2:" ASM_VARS );
              ^

but then everything is revealed

~/Documents/Arduino/libraries/Toggle/src/Toggle.h:50:40: note: in expansion of macro 'DONE'
     enum CLICK : uint16_t {FAST = 200, DONE = 500};
                                        ^~~~

I guess the easiest fix is to change the enum's keyword or create a private namespace for your library (or change the fasted library and its poor choice of using #define...)

clarify usage of Toggle::inputMode::input_pulldown versus setInverted

Hi

it's unclear how you would use setInputMode(Toggle::inputMode::input_pulldown) versus setInputInvert(true)

working exemple here with setInputInvert and messing around with the pin state after the begin (which means I overwrite likely what the class has done to the pin which requires intimate knowledge of the library to know in which order to do things)

https://wokwi.com/projects/347839208139784788

Request:

  • how would you use setInputMode() and not have to mess around in the code with pinMode?
  • improvement: possibility to establish the inputMode at constructor level

pressedFor not true only once

the example

if (myInput.pressedFor(500)) {
   // true (once only) if button has been pressed for 500ms
}

does not seem to work. I get repeated output with this code in Wokwi

#include <Toggle.h>                         // https://github.com/Dlloydev/Toggle

Toggle sw;
const unsigned long longPressDelay = 3000ul;

void setup() {
  Serial.begin(115200);
  sw.begin(3);
  Serial.println("READY");
}

void loop() {
  sw.poll();
  if (sw.pressedFor(longPressDelay)) Serial.println("LONG PRESS");
}

is that a wokwi issue ?

what code would let me check for both short and long press on a button? checking for onPress() will not work with pressedFor() apparently.

Possible conflict with DallasTemperature?

I've used your excellent Toggle library in other projects successfully. But after adding it to my current project it fails to recognise 'short' button presses, i.e. those delivering lows under 200 ms. It does recognise the 'long' button presses ( > 500 ms).

This conflict over resources, if that's what it is, appears to be with the DallasTemperature library. Because if I comment out its statement
// sensors.requestTemperatures();
then your short presses are correctly detected.

I was depending on Toggle so any advice you can offer would be appreciated please. I'm not a C/C++ programmer, so ideally not in over-technical terms!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.