### Full Example: Multifunctional Button Control Source: https://context7.com/gyverlibs/gyverbutton/llms.txt Demonstrates the full range of library features including debouncing, timeouts, and event handling for single, double, triple, and hold actions. ```cpp #include "GyverButton.h" #define BTN_PIN 3 GButton btn(BTN_PIN); int value = 0; void setup() { Serial.begin(9600); btn.setDebounce(50); // антидребезг 50 мс btn.setTimeout(400); // удержание через 400 мс btn.setClickTimeout(500); // пауза между кликами 500 мс btn.setStepTimeout(150); // инкремент каждые 150 мс btn.setType(HIGH_PULL); btn.setDirection(NORM_OPEN); } void loop() { btn.tick(); // Базовые события if (btn.isPress()) Serial.println(">>> Нажатие"); if (btn.isRelease()) Serial.println("<<< Отпускание"); // Одиночный клик — включить/выключить if (btn.isSingle()) { Serial.println("Одиночный: переключение режима"); } // Двойной клик — сброс значения if (btn.isDouble()) { value = 0; Serial.println("Двойной: сброс value = 0"); } // Тройной клик — установить максимум if (btn.isTriple()) { value = 100; Serial.println("Тройной: value = 100"); } // Удержание — вход в режим настройки if (btn.isHolded()) { Serial.print("Удержание! Кликов перед этим: "); Serial.println(btn.getHoldClicks()); } // Автоинкремент при удержании if (btn.isStep()) { value++; if (value > 100) value = 0; Serial.print("Step: value = "); Serial.println(value); } // Обработка произвольного количества кликов if (btn.hasClicks()) { int n = btn.getClicks(); if (n > 3) { Serial.print("Множественный клик: "); Serial.println(n); } } } ``` -------------------------------- ### Getting current state with state() Source: https://context7.com/gyverlibs/gyverbutton/llms.txt Returns the current instantaneous state of the button. ```cpp #include "GyverButton.h" GButton btn(3); void setup() { Serial.begin(9600); } void loop() { btn.tick(); if (btn.state()) { Serial.println("Кнопка сейчас нажата"); } else { Serial.println("Кнопка сейчас отпущена"); } delay(100); } ``` -------------------------------- ### Getting click count with getClicks() Source: https://context7.com/gyverlibs/gyverbutton/llms.txt Returns the number of clicks recorded, allowing for multi-click logic handling. ```cpp #include "GyverButton.h" GButton btn(3); void setup() { Serial.begin(9600); btn.setClickTimeout(400); } void loop() { btn.tick(); if (btn.hasClicks()) { int clicks = btn.getClicks(); switch (clicks) { case 1: Serial.println("Действие 1"); break; case 2: Serial.println("Действие 2"); break; case 3: Serial.println("Действие 3"); break; case 4: Serial.println("Действие 4"); break; case 5: Serial.println("Действие 5"); break; default: Serial.println("Много кликов!"); break; } } } ``` -------------------------------- ### Initialize and Use GyverButton Source: https://github.com/gyverlibs/gyverbutton/blob/main/README.md Demonstrates full library functionality including initialization, configuration of debounce/timeouts, and event handling within the loop. ```cpp // Пример использования библиотеки GyverButton, все возможности в одном скетче. #define BTN_PIN 3 // кнопка подключена сюда (BTN_PIN --- КНОПКА --- GND) #include "GyverButton.h" GButton butt1(BTN_PIN); // Варианты инициализации: // GButton btn; // без привязки к пину (виртуальная кнопка) и без указания типа (по умолч. HIGH_PULL и NORM_OPEN) // GButton btn(пин); // с привязкой к пину и без указания типа (по умолч. HIGH_PULL и NORM_OPEN) // GButton btn(пин, тип подключ.); // с привязкой к пину и указанием типа подключения (HIGH_PULL / LOW_PULL) и без указания типа кнопки (по умолч. NORM_OPEN) // GButton btn(пин, тип подключ., тип кнопки); // с привязкой к пину и указанием типа подключения (HIGH_PULL / LOW_PULL) и типа кнопки (NORM_OPEN / NORM_CLOSE) // GButton btn(BTN_NO_BTN_PIN, тип подключ., тип кнопки); // без привязки к пину и указанием типа подключения (HIGH_PULL / LOW_PULL) и типа кнопки (NORM_OPEN / NORM_CLOSE) int value = 0; void setup() { Serial.begin(9600); butt1.setDebounce(50); // настройка антидребезга (по умолчанию 80 мс) butt1.setTimeout(300); // настройка таймаута на удержание (по умолчанию 500 мс) butt1.setClickTimeout(600); // настройка таймаута между кликами (по умолчанию 300 мс) // HIGH_PULL - кнопка подключена к GND, пин подтянут к VCC (BTN_PIN --- КНОПКА --- GND) // LOW_PULL - кнопка подключена к VCC, пин подтянут к GND // по умолчанию стоит HIGH_PULL butt1.setType(HIGH_PULL); // NORM_OPEN - нормально-разомкнутая кнопка // NORM_CLOSE - нормально-замкнутая кнопка // по умолчанию стоит NORM_OPEN butt1.setDirection(NORM_OPEN); } void loop() { butt1.tick(); // обязательная функция отработки. Должна постоянно опрашиваться if (butt1.isClick()) Serial.println("Click"); // проверка на один клик if (butt1.isSingle()) Serial.println("Single"); // проверка на один клик if (butt1.isDouble()) Serial.println("Double"); // проверка на двойной клик if (butt1.isTriple()) Serial.println("Triple"); // проверка на тройной клик if (butt1.hasClicks()) // проверка на наличие нажатий Serial.println(butt1.getClicks()); // получить (и вывести) число нажатий if (butt1.isPress()) Serial.println("Press"); // нажатие на кнопку (+ дебаунс) if (butt1.isRelease()) Serial.println("Release"); // отпускание кнопки (+ дебаунс) if (butt1.isHold()) { // если кнопка удерживается Serial.print("Holding "); // выводим пока удерживается Serial.println(butt1.getHoldClicks()); // можно вывести количество кликов перед удержанием! } if (butt1.isHold()) Serial.println("Holding"); // проверка на удержание //if (butt1.state()) Serial.println("Hold"); // возвращает состояние кнопки if (butt1.isStep()) { // если кнопка была удержана (это для инкремента) value++; // увеличивать/уменьшать переменную value с шагом и интервалом Serial.println(value); // для примера выведем в порт } } ``` -------------------------------- ### Initialize GButton Objects Source: https://context7.com/gyverlibs/gyverbutton/llms.txt Create button instances with different pin assignments and connection types. ```cpp #include "GyverButton.h" // Виртуальная кнопка без привязки к пину GButton virtualBtn; // Кнопка на пине 3 с настройками по умолчанию (HIGH_PULL, NORM_OPEN) GButton btn1(3); // Кнопка с указанием типа подключения GButton btn2(4, HIGH_PULL); // подтянута к VCC, кнопка к GND GButton btn3(5, LOW_PULL); // подтянута к GND, кнопка к VCC // Полная инициализация с типом кнопки GButton btn4(6, HIGH_PULL, NORM_OPEN); // нормально разомкнутая GButton btn5(7, HIGH_PULL, NORM_CLOSE); // нормально замкнутая // Виртуальная кнопка с настройками типа GButton btn6(BTN_NO_PIN, HIGH_PULL, NORM_OPEN); ``` -------------------------------- ### GButton Constructor Source: https://context7.com/gyverlibs/gyverbutton/llms.txt Initializes a new button object with specific pin, connection type, and button state configuration. ```APIDOC ## GButton Constructor ### Description Creates a button instance. Supports virtual buttons (no pin) and physical buttons with configurable pull-up/down and normal state. ### Parameters - **pin** (int) - Required - Arduino pin number or BTN_NO_PIN for virtual buttons. - **type** (int) - Optional - HIGH_PULL or LOW_PULL. - **direction** (int) - Optional - NORM_OPEN or NORM_CLOSE. ### Request Example ```cpp GButton btn(3, HIGH_PULL, NORM_OPEN); ``` ``` -------------------------------- ### Initialize GyverButton Source: https://github.com/gyverlibs/gyverbutton/blob/main/README.md Various ways to initialize a GButton object, ranging from virtual buttons without pins to specific pin and connection type configurations. ```cpp GButton btn; // без привязки к пину (виртуальная кнопка) и без указания типа (по умолч. HIGH_PULL и NORM_OPEN) GButton btn(пин); // с привязкой к пину и без указания типа (по умолч. HIGH_PULL и NORM_OPEN) GButton btn(пин, тип подключ.); // с привязкой к пину и указанием типа подключения (HIGH_PULL / LOW_PULL) и без указания типа кнопки (по умолч. NORM_OPEN) GButton btn(пин, тип подключ., тип кнопки); // с привязкой к пину и указанием типа подключения (HIGH_PULL / LOW_PULL) и типа кнопки (NORM_OPEN / NORM_CLOSE) GButton btn(BTN_NO_PIN, тип подключ., тип кнопки); // без привязки к пину и указанием типа подключения (HIGH_PULL / LOW_PULL) и типа кнопки (NORM_OPEN / NORM_CLOSE) ``` -------------------------------- ### GyverButton Configuration Methods Source: https://github.com/gyverlibs/gyverbutton/blob/main/keywords.txt Methods used to configure the behavior of the button instance. ```APIDOC ## Configuration Methods ### Description Methods to set timing parameters, input types, and operational modes for the button. ### Methods - **setDebounce** - Sets the debounce time. - **setTimeout** - Sets the hold timeout. - **setStepTimeout** - Sets the step timeout. - **setClickTimeout** - Sets the click timeout. - **setType** - Sets the button type (e.g., NORM_OPEN, NORM_CLOSE). - **setDirection** - Sets the input direction (e.g., HIGH_PULL, LOW_PULL). - **setTickMode** - Sets the tick mode (e.g., MANUAL, AUTO). ``` -------------------------------- ### Configuration Methods Source: https://context7.com/gyverlibs/gyverbutton/llms.txt Methods to configure button behavior including debouncing, timeouts, and polling modes. ```APIDOC ## Configuration Methods ### setDebounce(int ms) Sets the debounce time in milliseconds (default 80ms). ### setTimeout(int ms) Sets the hold timeout in milliseconds (default 300ms). ### setClickTimeout(int ms) Sets the maximum time between clicks for multi-click detection (default 500ms). ### setStepTimeout(int ms) Sets the interval for isStep() increment function (default 400ms). ### setType(int type) Sets connection type: HIGH_PULL or LOW_PULL. ### setDirection(int dir) Sets normal state: NORM_OPEN or NORM_CLOSE. ### setTickMode(int mode) Sets polling mode: MANUAL or AUTO. ``` -------------------------------- ### Configure and Poll GyverButton Source: https://github.com/gyverlibs/gyverbutton/blob/main/README.md Methods for setting button parameters and polling the button state. ```cpp void setDebounce(uint16_t debounce); // установка времени антидребезга (по умолчанию 80 мс) void setTimeout(uint16_t timeout); // установка таймаута удержания (по умолчанию 300 мс) void setClickTimeout(uint16_t timeout); // установка таймаута между кликами (по умолчанию 500 мс) void setStepTimeout(uint16_t step_timeout); // установка таймаута между инкрементами (по умолчанию 400 мс) void setType(uint8_t type); // установка типа кнопки (HIGH_PULL - подтянута к питанию, LOW_PULL - к gnd) void setDirection(uint8_t dir); // установка направления (разомкнута/замкнута по умолчанию - NORM_OPEN, NORM_CLOSE) void setTickMode(uint8_t tickMode); // (MANUAL / AUTO) ручной или автоматический опрос кнопки функцией tick() // MANUAL - нужно вызывать функцию tick() вручную // AUTO - tick() входит во все остальные функции и опрашивается сама void tick(); // опрос кнопки void tick(boolean state); // опрос внешнего значения (0 нажато, 1 не нажато) (для матричных, резистивных клавиатур и джойстиков) boolean isPress(); // возвращает true при нажатии на кнопку. Сбрасывается после вызова boolean isRelease(); // возвращает true при отпускании кнопки. Сбрасывается после вызова boolean isClick(); // возвращает true при клике. Сбрасывается после вызова boolean isHolded(); // возвращает true при удержании дольше timeout. Сбрасывается после вызова boolean isHold(); // возвращает true при нажатой кнопке, не сбрасывается boolean state(); // возвращает состояние кнопки boolean isSingle(); // возвращает true при одиночном клике. Сбрасывается после вызова boolean isDouble(); // возвращает true при двойном клике. Сбрасывается после вызова boolean isTriple(); // возвращает true при тройном клике. Сбрасывается после вызова boolean hasClicks(); // проверка на наличие кликов. Сбрасывается после вызова uint8_t getClicks(); // вернуть количество кликов uint8_t getHoldClicks();// вернуть количество кликов, предшествующее удерживанию boolean isStep(); // возвращает true по таймеру setStepTimeout, смотри пример void resetStates(); // сбрасывает все is-флаги и счётчики ``` -------------------------------- ### Handle analog keyboards with AnalogKey Source: https://context7.com/gyverlibs/gyverbutton/llms.txt Maps multiple buttons connected to a single analog pin via a resistor ladder. Integrates with GButton instances to provide standard button event handling. ```cpp #include "AnalogKey.h" #include "GyverButton.h" // AnalogKey<пин, количество_кнопок> AnalogKey keys; // Виртуальные кнопки для каждой кнопки клавиатуры GButton btn0, btn1, btn2, btn3; void setup() { Serial.begin(9600); // Привязка значений АЦП к кнопкам (измерить для своей клавиатуры) keys.attach(0, 1023); // кнопка 0 = 1023 keys.attach(1, 930); // кнопка 1 = 930 keys.attach(2, 850); // кнопка 2 = 850 keys.attach(3, 780); // кнопка 3 = 780 keys.setWindow(25); // окно погрешности (по умолчанию 20) } void loop() { // Передаём состояние аналоговых кнопок в виртуальные btn0.tick(keys.status(0)); btn1.tick(keys.status(1)); btn2.tick(keys.status(2)); btn3.tick(keys.status(3)); // Теперь можно использовать все функции GButton if (btn0.isClick()) Serial.println("Кнопка 0 - клик"); if (btn1.isDouble()) Serial.println("Кнопка 1 - двойной клик"); if (btn2.isHolded()) Serial.println("Кнопка 2 - удержание"); if (btn3.isStep()) Serial.println("Кнопка 3 - инкремент"); } ``` -------------------------------- ### state() Source: https://context7.com/gyverlibs/gyverbutton/llms.txt Returns the current physical state of the button. ```APIDOC ## state() ### Description Returns the current state of the button (true = pressed, false = released). ``` -------------------------------- ### Configure Connection Type Source: https://context7.com/gyverlibs/gyverbutton/llms.txt Set the electrical connection type for the button. ```cpp #include "GyverButton.h" GButton btn(3); void setup() { // HIGH_PULL: BTN_PIN --- КНОПКА --- GND (pinMode = INPUT_PULLUP) btn.setType(HIGH_PULL); // LOW_PULL: BTN_PIN --- КНОПКА --- VCC (pinMode = INPUT) // btn.setType(LOW_PULL); } void loop() { btn.tick(); } ``` -------------------------------- ### AnalogKey Class - Analog Keypad Source: https://context7.com/gyverlibs/gyverbutton/llms.txt A template class for managing analog keypads where multiple buttons are connected to a single analog pin via a resistor divider. It works in conjunction with virtual `GButton` objects. ```APIDOC ## Класс AnalogKey — Аналоговая клавиатура ### Description Template class for working with analog keypads where multiple buttons are connected through a resistor divider to a single analog pin. Works with virtual GButton objects. ### Usage `AnalogKey` ### Methods - `attach(button_index, adc_value)`: Maps an ADC value to a specific button index. - `setWindow(tolerance)`: Sets the tolerance window for ADC readings. - `status(button_index)`: Returns the status of a specific button (used with `GButton::tick`). - `pressed()`: Returns the index of the pressed button or -1 if none are pressed. ### Parameters - **PIN**: The analog pin connected to the resistor divider. - **NUM_KEYS**: The total number of buttons on the keypad. - **button_index**: The index of the button (0 to NUM_KEYS-1). - **adc_value**: The analog-to-digital converter reading for a specific button press. - **tolerance**: The acceptable range of variation for ADC readings. ### Example (Using with GButton) ```cpp #include "AnalogKey.h" #include "GyverButton.h" // AnalogKey AnalogKey keys; // Virtual buttons for each keypad button GButton btn0, btn1, btn2, btn3; void setup() { Serial.begin(9600); // Map ADC values to buttons (measure for your specific keypad) keys.attach(0, 1023); // button 0 = 1023 keys.attach(1, 930); // button 1 = 930 keys.attach(2, 850); // button 2 = 850 keys.attach(3, 780); // button 3 = 780 keys.setWindow(25); // tolerance window (default 20) } void loop() { // Pass analog button states to virtual buttons btn0.tick(keys.status(0)); btn1.tick(keys.status(1)); btn2.tick(keys.status(2)); btn3.tick(keys.status(3)); // Now you can use all GButton functions if (btn0.isClick()) Serial.println("Button 0 - Click"); if (btn1.isDouble()) Serial.println("Button 1 - Double Click"); if (btn2.isHolded()) Serial.println("Button 2 - Hold"); if (btn3.isStep()) Serial.println("Button 3 - Step"); } ``` ``` -------------------------------- ### GyverButton State and Event Methods Source: https://github.com/gyverlibs/gyverbutton/blob/main/keywords.txt Methods used to poll the button state and detect specific user interactions. ```APIDOC ## State and Event Methods ### Description Methods to check the current state of the button and detect events like clicks, holds, and releases. ### Methods - **tick** - Updates the button state. - **isPress** - Returns true if the button is pressed. - **isRelease** - Returns true if the button is released. - **isClick** - Returns true if a click occurred. - **isHolded** - Returns true if the button is held. - **isHold** - Returns true while the button is held. - **state** - Returns the current raw state. - **hasClicks** - Checks for pending clicks. - **getClicks** - Returns the number of clicks. - **getHoldClicks** - Returns the number of hold clicks. - **isSingle/isDouble/isTriple** - Detects specific click counts. - **isStep** - Detects a step event. - **resetStates** - Resets all internal states. ``` -------------------------------- ### Configure Debounce Time Source: https://context7.com/gyverlibs/gyverbutton/llms.txt Set the debounce interval in milliseconds to filter contact noise. ```cpp #include "GyverButton.h" GButton btn(3); void setup() { btn.setDebounce(50); // установить антидребезг 50 мс } void loop() { btn.tick(); if (btn.isClick()) { // клик без дребезга контактов } } ``` -------------------------------- ### GyverButton Configuration API Source: https://github.com/gyverlibs/gyverbutton/blob/main/README.md Functions to configure the behavior of the GyverButton library, such as debounce time, timeouts, button type, and direction. ```APIDOC ## GyverButton Configuration ### Description Configure various parameters of the GyverButton to customize its behavior. ### Functions - `void setDebounce(uint16_t debounce)`: Sets the debounce time in milliseconds. Default is 80ms. - `void setTimeout(uint16_t timeout)`: Sets the hold timeout in milliseconds. Default is 300ms. - `void setClickTimeout(uint16_t timeout)`: Sets the timeout between clicks in milliseconds. Default is 500ms. - `void setStepTimeout(uint16_t step_timeout)`: Sets the timeout between increments for step actions in milliseconds. Default is 400ms. - `void setType(uint8_t type)`: Sets the button type. Use `HIGH_PULL` if the button is pulled up to power, or `LOW_PULL` if pulled down to ground. - `void setDirection(uint8_t dir)`: Sets the button's default state. Use `NORM_OPEN` for normally open or `NORM_CLOSE` for normally closed. - `void setTickMode(uint8_t tickMode)`: Sets the button polling mode. Use `MANUAL` to call `tick()` manually, or `AUTO` for automatic polling within other functions. ``` -------------------------------- ### Configure Polling Mode Source: https://context7.com/gyverlibs/gyverbutton/llms.txt Switch between manual tick() calls and automatic polling. ```cpp #include "GyverButton.h" GButton btn(3); void setup() { Serial.begin(9600); btn.setTickMode(AUTO); // автоматический опрос } void loop() { // tick() не нужен, опрос происходит автоматически if (btn.isClick()) { Serial.println("Click"); } } ``` -------------------------------- ### isSingle() / isDouble() / isTriple() Source: https://context7.com/gyverlibs/gyverbutton/llms.txt Detects specific click counts. ```APIDOC ## isSingle() / isDouble() / isTriple() ### Description Returns true when a single, double, or triple click is detected respectively. The flag is reset after the call. ``` -------------------------------- ### Configure Step Timeout Source: https://context7.com/gyverlibs/gyverbutton/llms.txt Set the interval between automatic triggers during a button hold. ```cpp #include "GyverButton.h" GButton btn(3); int value = 0; void setup() { Serial.begin(9600); btn.setStepTimeout(200); // инкремент каждые 200 мс } void loop() { btn.tick(); if (btn.isStep()) { value++; Serial.println(value); } } ``` -------------------------------- ### Configure Click Timeout Source: https://context7.com/gyverlibs/gyverbutton/llms.txt Set the maximum interval between clicks to detect multi-click events. ```cpp #include "GyverButton.h" GButton btn(3); void setup() { Serial.begin(9600); btn.setClickTimeout(400); // 400 мс между кликами } void loop() { btn.tick(); if (btn.isSingle()) Serial.println("Одиночный клик"); if (btn.isDouble()) Serial.println("Двойной клик"); if (btn.isTriple()) Serial.println("Тройной клик"); } ``` -------------------------------- ### Configure Button Direction Source: https://context7.com/gyverlibs/gyverbutton/llms.txt Define the default state of the button as normally open or normally closed. ```cpp #include "GyverButton.h" GButton btn(3); void setup() { btn.setDirection(NORM_OPEN); // нормально разомкнутая // btn.setDirection(NORM_CLOSE); // нормально замкнутая } void loop() { btn.tick(); } ``` -------------------------------- ### hasClicks() / getClicks() Source: https://context7.com/gyverlibs/gyverbutton/llms.txt Advanced click counting. ```APIDOC ## hasClicks() / getClicks() ### Description hasClicks() returns true if clicks were recorded. getClicks() returns the number of clicks recorded. ``` -------------------------------- ### Detect clicks before hold with getHoldClicks() Source: https://context7.com/gyverlibs/gyverbutton/llms.txt Retrieves the number of clicks performed immediately before a button hold event. Useful for distinguishing between simple holds and hold events preceded by multiple clicks. ```cpp #include "GyverButton.h" GButton btn(3); void setup() { Serial.begin(9600); } void loop() { btn.tick(); if (btn.isHolded()) { int clicksBefore = btn.getHoldClicks(); Serial.print("Кликов перед удержанием: "); Serial.println(clicksBefore); // 0 = просто удержание // 1 = клик + удержание // 2 = два клика + удержание } } ``` -------------------------------- ### isStep(clicks) - Increment with Clicks Source: https://context7.com/gyverlibs/gyverbutton/llms.txt An extended version of `isStep()` that triggers only when a specific number of clicks precede the hold. This allows for implementing different increment speeds based on user input sequences. ```APIDOC ## isStep(clicks) — Increment with Clicks ### Description An extended version of `isStep()` that triggers only upon a specific number of clicks before holding. This allows for implementing different increment speeds. ### Method `isStep(clicks)` ### Parameters - **clicks** (int) - Required - The number of clicks that must precede the hold event for this function to return true. - `0`: Simple hold. - `1`: One click followed by a hold. - `2`: Two clicks followed by a hold. ### Return Value - `bool`: `true` if the step condition with the specified number of preceding clicks is met, `false` otherwise. ### Example ```cpp #include "GyverButton.h" GButton btn(3); int value = 0; void setup() { Serial.begin(9600); btn.setStepTimeout(200); } void loop() { btn.tick(); // Simple hold - slow increment (+1) if (btn.isStep(0)) { value += 1; Serial.println(value); } // One click + hold - medium increment (+10) if (btn.isStep(1)) { value += 10; Serial.println(value); } // Two clicks + hold - fast increment (+100) if (btn.isStep(2)) { value += 100; Serial.println(value); } } ``` ``` -------------------------------- ### Configure Hold Timeout Source: https://context7.com/gyverlibs/gyverbutton/llms.txt Define the duration in milliseconds after which a press is registered as a hold. ```cpp #include "GyverButton.h" GButton btn(3); void setup() { Serial.begin(9600); btn.setTimeout(500); // удержание через 500 мс } void loop() { btn.tick(); if (btn.isHolded()) { Serial.println("Кнопка удержана!"); } } ``` -------------------------------- ### isRelease() Source: https://context7.com/gyverlibs/gyverbutton/llms.txt Detects a single release event. ```APIDOC ## isRelease() ### Description Returns true once when the button is released (with debouncing). The flag is reset after the call. ``` -------------------------------- ### Reset button states with resetStates() Source: https://context7.com/gyverlibs/gyverbutton/llms.txt Clears all event flags and click counters. Essential when switching between different operational modes to prevent stale input processing. ```cpp #include "GyverButton.h" GButton btn(3); bool menuActive = false; void setup() { Serial.begin(9600); } void loop() { btn.tick(); if (btn.isHolded()) { menuActive = !menuActive; btn.resetStates(); // сброс после смены режима Serial.println(menuActive ? "Меню открыто" : "Меню закрыто"); } if (menuActive) { if (btn.isClick()) Serial.println("Навигация по меню"); } else { if (btn.isClick()) Serial.println("Обычное действие"); } } ``` -------------------------------- ### Detecting a click with isClick() Source: https://context7.com/gyverlibs/gyverbutton/llms.txt Returns true upon completion of a full click (press and release). The flag resets after the call. ```cpp #include "GyverButton.h" GButton btn(3); void setup() { Serial.begin(9600); } void loop() { btn.tick(); if (btn.isClick()) { Serial.println("Клик!"); } } ``` -------------------------------- ### GyverButton State Detection API Source: https://github.com/gyverlibs/gyverbutton/blob/main/README.md Functions to detect various button events like presses, releases, clicks, holds, and multiple clicks. ```APIDOC ## GyverButton State Detection ### Description Functions to check for specific button events. Most of these functions return `true` only once per event and are reset after being called. ### Functions - `boolean isPress()`: Returns `true` when the button is pressed. Resets after call. - `boolean isRelease()`: Returns `true` when the button is released. Resets after call. - `boolean isClick()`: Returns `true` on a single click. Resets after call. - `boolean isHolded()`: Returns `true` when the button has been held longer than the configured `setTimeout`. Resets after call. - `boolean isHold()`: Returns `true` as long as the button is held down. Does not reset after call. - `boolean state()`: Returns the current state of the button (`true` if pressed, `false` if released). - `boolean isSingle()`: Returns `true` for a single click. Resets after call. - `boolean isDouble()`: Returns `true` for a double click. Resets after call. - `boolean isTriple()`: Returns `true` for a triple click. Resets after call. - `boolean hasClicks()`: Checks if any clicks have occurred. Resets after call. - `uint8_t getClicks()`: Returns the number of detected clicks. Resets after call. - `uint8_t getHoldClicks()`: Returns the number of clicks that occurred before a hold action. Resets after call. - `boolean isStep()`: Returns `true` when the step timeout configured by `setStepTimeout` is reached. See example for usage. - `void resetStates()`: Resets all internal state flags and counters. ``` -------------------------------- ### Detect pressed button index with AnalogKey::pressed() Source: https://context7.com/gyverlibs/gyverbutton/llms.txt Returns the index of the currently pressed button or -1 if none are active. Useful for simple scenarios where GButton features are not required. ```cpp #include "AnalogKey.h" AnalogKey keys; void setup() { Serial.begin(9600); keys.attach(0, 1023); keys.attach(1, 900); keys.attach(2, 800); } void loop() { int key = keys.pressed(); if (key != -1) { Serial.print("Нажата кнопка: "); Serial.println(key); } delay(100); } ``` -------------------------------- ### Detecting triple click with isTriple() Source: https://context7.com/gyverlibs/gyverbutton/llms.txt Returns true when a triple click is detected. The flag resets after the call. ```cpp #include "GyverButton.h" GButton btn(3); void setup() { Serial.begin(9600); } void loop() { btn.tick(); if (btn.isTriple()) { Serial.println("Тройной клик!"); } } ``` -------------------------------- ### isClick() Source: https://context7.com/gyverlibs/gyverbutton/llms.txt Detects a completed click event. ```APIDOC ## isClick() ### Description Returns true when a click (press + release) is completed. The flag is reset after the call. ``` -------------------------------- ### tick() Source: https://context7.com/gyverlibs/gyverbutton/llms.txt Main polling function for the button. Must be called continuously in loop(). ```APIDOC ## tick() ### Description Main function for button polling. Must be called continuously in loop() when in MANUAL mode. Can accept an external state for virtual buttons. ### Parameters - **externalState** (bool) - Optional - External state for virtual buttons (1 = pressed, 0 = released). ``` -------------------------------- ### Implement conditional auto-increment with isStep(clicks) Source: https://context7.com/gyverlibs/gyverbutton/llms.txt Triggers auto-increment only when a specific number of clicks precedes the hold. Allows for variable increment speeds based on user input patterns. ```cpp #include "GyverButton.h" GButton btn(3); int value = 0; void setup() { Serial.begin(9600); btn.setStepTimeout(200); } void loop() { btn.tick(); // Просто удержание — медленный инкремент (+1) if (btn.isStep(0)) { value += 1; Serial.println(value); } // Один клик + удержание — средний инкремент (+10) if (btn.isStep(1)) { value += 10; Serial.println(value); } // Два клика + удержание — быстрый инкремент (+100) if (btn.isStep(2)) { value += 100; Serial.println(value); } } ``` -------------------------------- ### isPress() Source: https://context7.com/gyverlibs/gyverbutton/llms.txt Detects a single press event. ```APIDOC ## isPress() ### Description Returns true once when the button is pressed (with debouncing). The flag is reset after the call. ``` -------------------------------- ### Polling buttons with tick() Source: https://context7.com/gyverlibs/gyverbutton/llms.txt The tick() function must be called continuously in the loop. It supports both physical pins and virtual buttons with external state inputs. ```cpp #include "GyverButton.h" GButton physicalBtn(3); GButton virtualBtn; void setup() { Serial.begin(9600); } void loop() { // Опрос физической кнопки physicalBtn.tick(); // Опрос виртуальной кнопки с внешним состоянием // 1 = нажата, 0 = не нажата bool externalState = (analogRead(A0) > 500); virtualBtn.tick(externalState); if (physicalBtn.isClick()) Serial.println("Physical click"); if (virtualBtn.isClick()) Serial.println("Virtual click"); } ``` -------------------------------- ### Checking for clicks with hasClicks() Source: https://context7.com/gyverlibs/gyverbutton/llms.txt Returns true if clicks were recorded. Typically used with getClicks(). ```cpp #include "GyverButton.h" GButton btn(3); void setup() { Serial.begin(9600); } void loop() { btn.tick(); if (btn.hasClicks()) { Serial.print("Количество кликов: "); Serial.println(btn.getClicks()); } } ``` -------------------------------- ### getHoldClicks() - Clicks Before Hold Source: https://context7.com/gyverlibs/gyverbutton/llms.txt Retrieves the number of clicks that occurred immediately before a button hold event. This is useful for differentiating between a simple hold and a sequence of clicks followed by a hold. ```APIDOC ## getHoldClicks() ### Description Returns the number of clicks made directly before holding the button. ### Method `getHoldClicks()` ### Parameters None ### Return Value - `int`: The number of clicks before the hold event. - `0`: Simple hold. - `1`: One click followed by a hold. - `2`: Two clicks followed by a hold. ### Example ```cpp #include "GyverButton.h" GButton btn(3); void setup() { Serial.begin(9600); } void loop() { btn.tick(); if (btn.isHolded()) { int clicksBefore = btn.getHoldClicks(); Serial.print("Clicks before hold: "); Serial.println(clicksBefore); } } ``` ``` -------------------------------- ### Implement auto-increment with isStep() Source: https://context7.com/gyverlibs/gyverbutton/llms.txt Triggers a repeating event at intervals defined by setStepTimeout() while a button is held. Requires calling tick() in the main loop. ```cpp #include "GyverButton.h" GButton btnUp(2); GButton btnDown(3); int value = 50; void setup() { Serial.begin(9600); btnUp.setStepTimeout(100); // быстрый инкремент btnDown.setStepTimeout(100); } void loop() { btnUp.tick(); btnDown.tick(); // Клик = +1/-1 if (btnUp.isClick()) { value++; Serial.println(value); } if (btnDown.isClick()) { value--; Serial.println(value); } // Удержание = автоинкремент if (btnUp.isStep()) { value++; Serial.println(value); } if (btnDown.isStep()) { value--; Serial.println(value); } } ``` -------------------------------- ### Detecting double click with isDouble() Source: https://context7.com/gyverlibs/gyverbutton/llms.txt Returns true when a double click is detected. The flag resets after the call. ```cpp #include "GyverButton.h" GButton btn(3); void setup() { Serial.begin(9600); } void loop() { btn.tick(); if (btn.isDouble()) { Serial.println("Двойной клик!"); } } ``` -------------------------------- ### AnalogKey::pressed() - Pressed Button Number Source: https://context7.com/gyverlibs/gyverbutton/llms.txt Returns the index of the currently pressed button on an analog keypad, or -1 if no button is pressed. This method is convenient for simpler scenarios where direct button index detection is sufficient without using `GButton` objects. ```APIDOC ## AnalogKey::pressed() — Pressed Button Number ### Description Returns the index of the pressed button or -1 if none is pressed. Convenient for simple scenarios without using GButton. ### Method `pressed()` ### Parameters None ### Return Value - `int`: The index of the pressed button (0 to NUM_KEYS-1), or -1 if no button is pressed. ### Example ```cpp #include "AnalogKey.h" AnalogKey keys; void setup() { Serial.begin(9600); keys.attach(0, 1023); keys.attach(1, 900); keys.attach(2, 800); } void loop() { int key = keys.pressed(); if (key != -1) { Serial.print("Pressed button: "); Serial.println(key); } delay(100); } ``` ``` -------------------------------- ### Detecting button release with isRelease() Source: https://context7.com/gyverlibs/gyverbutton/llms.txt Returns true once when the button is released. The flag resets after the call. ```cpp #include "GyverButton.h" GButton btn(3); void setup() { Serial.begin(9600); } void loop() { btn.tick(); if (btn.isRelease()) { Serial.println("Кнопка отпущена!"); } } ``` -------------------------------- ### Detecting single click with isSingle() Source: https://context7.com/gyverlibs/gyverbutton/llms.txt Returns true after a single click once the double-click timeout expires. ```cpp #include "GyverButton.h" GButton btn(3); void setup() { Serial.begin(9600); } void loop() { btn.tick(); if (btn.isSingle()) { Serial.println("Одиночный клик"); } } ``` -------------------------------- ### isHold() Source: https://context7.com/gyverlibs/gyverbutton/llms.txt Checks if the button is currently being held. ```APIDOC ## isHold() ### Description Returns true while the button is held after the timeout has passed. The flag is not reset. ``` -------------------------------- ### GyverButton Polling API Source: https://github.com/gyverlibs/gyverbutton/blob/main/README.md Functions for polling the button state, either manually or automatically, and handling external input states. ```APIDOC ## GyverButton Polling ### Description Functions to poll the button's state or update it with external input. ### Functions - `void tick()`: Polls the button state. This function needs to be called regularly if `setTickMode` is set to `MANUAL`. - `void tick(boolean state)`: Polls the button state using an external input value. `0` indicates pressed, `1` indicates not pressed. Useful for matrix keypads, resistive touchscreens, and joysticks. ``` -------------------------------- ### Detecting button press with isPress() Source: https://context7.com/gyverlibs/gyverbutton/llms.txt Returns true once when the button is pressed, accounting for debouncing. The flag resets after the call. ```cpp #include "GyverButton.h" GButton btn(3); void setup() { Serial.begin(9600); } void loop() { btn.tick(); if (btn.isPress()) { Serial.println("Кнопка нажата!"); // Выполняется один раз в момент нажатия } } ``` -------------------------------- ### resetStates() - Reset States Source: https://context7.com/gyverlibs/gyverbutton/llms.txt Resets all event flags and click counters within the button object. This is particularly useful when switching between different operational modes or states to ensure a clean slate for new event detection. ```APIDOC ## resetStates() — Reset States ### Description Resets all event flags and click counters. Useful when switching between operation modes. ### Method `resetStates()` ### Parameters None ### Return Value None ### Example ```cpp #include "GyverButton.h" GButton btn(3); bool menuActive = false; void setup() { Serial.begin(9600); } void loop() { btn.tick(); if (btn.isHolded()) { menuActive = !menuActive; btn.resetStates(); // Reset after changing mode Serial.println(menuActive ? "Menu Opened" : "Menu Closed"); } if (menuActive) { if (btn.isClick()) Serial.println("Navigating menu"); } else { if (btn.isClick()) Serial.println("Normal action"); } } ``` ``` -------------------------------- ### isHolded() Source: https://context7.com/gyverlibs/gyverbutton/llms.txt Detects when a hold timeout is reached. ```APIDOC ## isHolded() ### Description Returns true once when the hold time exceeds the timeout. The flag is reset after the call. ``` -------------------------------- ### Checking hold state with isHold() Source: https://context7.com/gyverlibs/gyverbutton/llms.txt Returns true continuously while the button is held after the timeout. The flag does not reset. ```cpp #include "GyverButton.h" GButton btn(3); void setup() { Serial.begin(9600); } void loop() { btn.tick(); if (btn.isHold()) { Serial.println("Удерживается..."); // Выводится каждую итерацию loop пока кнопка удерживается } } ```