Add AceButton library

This commit is contained in:
fvanroie 2020-03-09 22:54:40 +01:00
parent 9f68b1c1c2
commit 86c6430e3f
11 changed files with 110 additions and 372 deletions

View File

@ -83,7 +83,7 @@ typedef int16_t lv_coord_t;
# define LV_MEM_SIZE (10U * 1024U) // 10kb with telnet, 12kb without telnet
#endif
#ifndef LV_MEM_SIZE
# define LV_MEM_SIZE (48 * 1024U) // 40KB
# define LV_MEM_SIZE (40 * 1024U) // 40KB
#endif
/* Complier prefix for a big array declaration */
@ -132,7 +132,7 @@ typedef int16_t lv_coord_t;
/* Repeated trigger period in long press [ms]
* Time between `LV_EVENT_LONG_PRESSED_REPEAT */
#define LV_INDEV_DEF_LONG_PRESS_REP_TIME 100
#define LV_INDEV_DEF_LONG_PRESS_REP_TIME 250
/*==================
* Feature usage
@ -157,7 +157,7 @@ typedef void * lv_group_user_data_t;
#endif /*LV_USE_GROUP*/
/* 1: Enable GPU interface*/
#define LV_USE_GPU 1
#define LV_USE_GPU 0
/* 1: Enable file system (might be required for images */
#define LV_USE_FILESYSTEM 0

View File

@ -1,51 +0,0 @@
{
"name": "Button",
"version": "1.0.0",
"keywords": [
"signal",
"input",
"output"
],
"description": "Button is a tiny library to make reading buttons very simple.",
"frameworks": [
"arduino"
],
"platforms": [
"atmelavr",
"atmelsam",
"espressif32",
"espressif8266",
"intel_arc32",
"microchippic32",
"nordicnrf51",
"nordicnrf52",
"ststm32",
"teensy",
"timsp430"
],
"authors": [
{
"email": "arduino@michaeladams.org",
"url": null,
"maintainer": true,
"name": "Michael Adams"
}
],
"repository": {
"type": "git",
"url": "https://github.com/madleech/Button"
},
"homepage": "http://utrainia.com/",
"export": {
"include": null,
"exclude": [
"extras",
"docs",
"tests",
"test",
"*.doxyfile",
"*.pdf"
]
},
"id": 919
}

View File

@ -1,73 +0,0 @@
/*
Button - a small library for Arduino to handle button debouncing
MIT licensed.
*/
#include "Button.h"
#include <Arduino.h>
Button::Button(uint8_t pin) : _pin(pin), _delay(100), _state(HIGH), _ignore_until(0), _has_changed(false)
{}
void Button::begin()
{
pinMode(_pin, INPUT_PULLUP);
}
//
// public methods
//
bool Button::read()
{
// ignore pin changes until after this delay time
if(_ignore_until > millis()) {
// ignore any changes during this period
}
// pin has changed
else if(digitalRead(_pin) != _state) {
_ignore_until = millis() + _delay;
_state = !_state;
_has_changed = true;
}
return _state;
}
// has the button been toggled from on -> off, or vice versa
bool Button::toggled()
{
read();
return has_changed();
}
// mostly internal, tells you if a button has changed after calling the read() function
bool Button::has_changed()
{
if(_has_changed == true) {
_has_changed = false;
return true;
}
return false;
}
// has the button gone from off -> on
bool Button::pressed()
{
if(read() == PRESSED && has_changed() == true)
return true;
else
return false;
}
// has the button gone from on -> off
bool Button::released()
{
if(read() == RELEASED && has_changed() == true)
return true;
else
return false;
}

View File

@ -1,33 +0,0 @@
/*
Button - a small library for Arduino to handle button debouncing
MIT licensed.
*/
#ifndef Button_h
#define Button_h
#include "Arduino.h"
class Button {
public:
Button(uint8_t pin);
void begin();
bool read();
bool toggled();
bool pressed();
bool released();
bool has_changed();
const static bool PRESSED = LOW;
const static bool RELEASED = HIGH;
private:
uint8_t _pin;
uint16_t _delay;
bool _state;
uint32_t _ignore_until;
bool _has_changed;
};
#endif

View File

@ -1,109 +0,0 @@
Button
======
* Author: Michael Adams (<http://www.michael.net.nz>)
* Copyright (C) 2016 Michael D K Adams.
* Released under the MIT license.
Button is a tiny library to make reading buttons very simple. It handles debouncing automatically, and monitoring of state.
Motivation
----------
Ahh buttons. Ahh debouncing! Sometimes you really wish you could ignore all the mechanics of debouncing, reading inputs, monitoring state, and just say... `if (button.pressed())` and know that it'll only run once each time you press a button.
Or how about `if (button.released())`, or `button.toggled()`. It is such a simple concept, but in practice you need to set up timers, monitor input puts, set pullups, etc etc. On anything more than the most simple example, that can become quite a headache.
So fed up with all that I figured there had to be a better way. This library is the result.
Features
--------
* Super simple API.
* Handles debouncing.
* Sets the pin mode automatically.
* Lets you write code that triggers:
** based on the pin state (high or low)
** when a button is pressed
** when a button is released
** or when a button changes (i.e. pressing or releasing)
Requirements
------------
* An Arduino — http://arduino.cc/
* A button
Installation
------------
Download the ZIP archive (https://github.com/madleech/Button/zipball/master), then open the Arduino IDE and choose Sketch > Include Library > Add .ZIP Library... and select your downloaded file.
You should now see in File > Examples > Button entires for the basic\_usage example.
Code Examples
-------------
Here is the 'basic\_usage' example program, included in the download:
#include <Button.h>
Button button1(2); // Connect your button between pin 2 and GND
Button button2(3); // Connect your button between pin 3 and GND
Button button3(4); // Connect your button between pin 4 and GND
void setup() {
button1.begin();
button2.begin();
button3.begin();
while (!Serial) { }; // for Leos
Serial.begin(9600);
}
void loop() {
if (button1.pressed())
Serial.println("Button 1 pressed");
if (button1.released())
Serial.println("Button 2 released");
if (button1.toggled())
Serial.print(button3.read() == Button::PRESSED ? "Button 3 has been pressed" : "Button 3 has been released");
}
Documentation
-------------
**Button(int pin)**
Creates a new Button.
**void begin()**
Call this in your `setup` method to setup the button. All it does is set the correct pin mode.
**bool pressed()**
Returns true when _and only when_ the button is pressed. Until the button is released (in the debounced-sense of the word) this function won't return true again. So in effect, it returns true only while you are pressing the button, or to put it another way, it fires on a rising edge.
**bool released()**
Like `pressed()`, but round the other way. So if you hold down a button, and then release it... that is when it fires.
**bool toggled()**
Returns true whenever the button is pressed or released, i.e., its position is toggled. To find out what the position actually is, you can use the `read()` function.
**bool read()**
Returns the current debounced state of the button, i.e. Button::PRESSED or Button::RELEASED.
**bool has_changed()**
Returns whether the position/state of the button has changed after calling the previous read() function. Unlikely to be used except by Super Gurus.
Quirks and Things to Keep in Mind
---------------------------------
**Highs and lows, lows and highs**
The easiest way to connect a switch on an Arduino is to connect it between an input pin and ground, and use the internal pullup resistor to make sure it doesn't float. This is fine and dandy, but it can get a bit confusing, as a "pressed" button is logic level: low, while a "released" button is logic level: high.
So to make it a bit more obvious what you're talking about, you can use a couple of handy shortcuts: `Button::PRESSED` and `Button::RELEASED` which map to the expected values.
License
-------
Copyright (c) 2016 Michael D K Adams. http://www.michael.net.nz/
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@ -1,29 +0,0 @@
#include <Button.h>
Button button1(2); // Connect your button between pin 2 and GND
Button button2(3); // Connect your button between pin 3 and GND
Button button3(4); // Connect your button between pin 4 and GND
void setup() {
button1.begin();
button2.begin();
button3.begin();
while (!Serial) { }; // for Leos
Serial.begin(9600);
}
void loop() {
if (button1.pressed())
Serial.println("Button 1 pressed");
if (button2.released())
Serial.println("Button 2 released");
if (button3.toggled()) {
if (button3.read() == Button::PRESSED)
Serial.println("Button 3 has been pressed");
else
Serial.println("Button 3 has been released");
}
}

View File

@ -1,25 +0,0 @@
#######################################
# Syntax Coloring Map for Debounce library
#######################################
#######################################
# Datatypes (KEYWORD1)
#######################################
Button KEYWORD1
#######################################
# Methods and Functions (KEYWORD2)
#######################################
read KEYWORD2
toggled KEYWORD2
pressed KEYWORD2
released KEYWORD2
has_changed KEYWORD2
#######################################
# Constants (LITERAL1)
#######################################
PRESSED LITERAL1
RELEASED LITERAL1

View File

@ -1,9 +0,0 @@
name=Button
version=1.0.0
author=Michael Adams <arduino@michaeladams.org>
maintainer=Michael Adams <arduino@michaeladams.org>
sentence=Button is a tiny library to make reading buttons very simple.
paragraph=It handles debouncing automatically, and monitoring of state.
category=Signal Input/Output
url=http://utrainia.com/
architectures=*

View File

@ -69,6 +69,7 @@ lib_deps =
PubSubClient@^2.7.0 ; MQTT client
ArduinoJson@^6.14.1,>6.14.0 ; needs at least 6.14.1
Syslog@^2.0.0
AceButton@^1.4.0
; -- littlevgl config options ----------------------
@ -193,7 +194,9 @@ build_flags =
[env:d1mini-lolintft24]
platform = espressif8266@2.3.2
board = d1_mini
upload_port = COM4 ; Change to the correct port
;upload_port = COM4 ; Change to the correct port
upload_protocol = espota ; Use ArduinoOTA after flashing over serial
upload_port = 10.1.0.148 ; IP of the ESP
monitor_port = COM4 ; Change to the correct port
monitor_speed = 74880
board_build.f_flash = 40000000L

View File

@ -1,28 +1,83 @@
#include "Button.h"
#include "AceButton.h"
#include "hasp_conf.h"
#include "lv_conf.h"
#include "hasp_button.h"
#include "hasp_dispatch.h"
#include "hasp_log.h"
Button * button[HASP_NUM_INPUTS]; // Connect your button between pin 2 and GND
using namespace ace_button;
AceButton * button[HASP_NUM_INPUTS]; // Connect your button between pin 2 and GND
void handleEvent(AceButton *, uint8_t, uint8_t);
void buttonSetup(void)
{
// button[0] = new Button(2);
button[1] = new Button(3);
button[2] = new Button(4);
button[1] = new AceButton(3, HIGH, 1);
button[2] = new AceButton(4, HIGH, 2);
// button[0]->begin();
button[1]->begin();
button[2]->begin();
ButtonConfig * buttonConfig = ButtonConfig::getSystemButtonConfig();
buttonConfig->setEventHandler(handleEvent);
// Features
buttonConfig->setFeature(ButtonConfig::kFeatureClick);
buttonConfig->setFeature(ButtonConfig::kFeatureLongPress);
buttonConfig->setFeature(ButtonConfig::kFeatureRepeatPress);
// buttonConfig->setFeature(ButtonConfig::kFeatureDoubleClick);
// buttonConfig->setFeature(ButtonConfig::kFeatureSuppressClickBeforeDoubleClick);
// Delays
buttonConfig->setClickDelay(LV_INDEV_DEF_LONG_PRESS_TIME);
buttonConfig->setDoubleClickDelay(LV_INDEV_DEF_LONG_PRESS_TIME);
buttonConfig->setLongPressDelay(LV_INDEV_DEF_LONG_PRESS_TIME);
buttonConfig->setRepeatPressDelay(LV_INDEV_DEF_LONG_PRESS_TIME);
buttonConfig->setRepeatPressInterval(LV_INDEV_DEF_LONG_PRESS_REP_TIME);
debugPrintln(F("BTNS: setup(): ready"));
}
void buttonLoop(void)
{
// Should be called every 4-5ms or faster, for the default debouncing time
// of ~20ms.
for(uint8_t i = 0; i < (sizeof button / sizeof *button); i++) {
if(button[i] && button[i]->toggled()) {
dispatchButton(i, button[i]->read() == Button::PRESSED);
}
if(button[i]) button[i]->check();
}
}
// The event handler for the button.
void handleEvent(AceButton * button, uint8_t eventType, uint8_t buttonState)
{
char buffer[128];
// Print out a message for all events.
/* Serial.print(F("handleEvent(): eventType: "));
Serial.print(eventType);
Serial.print(F("; buttonState: "));
Serial.println(buttonState); */
switch(eventType) {
case AceButton::kEventPressed:
memcpy_P(buffer, PSTR("DOWN"), sizeof(buffer));
break;
case AceButton::kEventClicked:
memcpy_P(buffer, PSTR("SHORT"), sizeof(buffer));
break;
case AceButton::kEventDoubleClicked:
memcpy_P(buffer, PSTR("DOUBLE"), sizeof(buffer));
break;
case AceButton::kEventLongPressed:
memcpy_P(buffer, PSTR("LONG"), sizeof(buffer));
break;
case AceButton::kEventRepeatPressed:
memcpy_P(buffer, PSTR("HOLD"), sizeof(buffer));
break;
case AceButton::kEventReleased:
memcpy_P(buffer, PSTR("UP"), sizeof(buffer));
break;
}
dispatchButton(button->getId(), buffer);
}

View File

@ -12,6 +12,19 @@
#include "hasp_gui.h"
#include "hasp.h"
bool isON(const char * payload)
{
return strcmp_P(payload, PSTR("ON")) == 0;
}
String getOnOff(bool state)
{
String result((char *)0);
result.reserve(128);
result = state ? F("ON") : F("OFF");
return result;
}
void dispatchSetup()
{}
@ -63,7 +76,7 @@ void dispatchAttribute(String & strTopic, const char * payload)
} // valid page
}
} else if(strTopic.startsWith(F("output"))) {
uint8_t state = strcmp_P(payload, PSTR("ON")) == 0 ? HIGH : LOW;
uint8_t state = isON(payload) ? HIGH : LOW;
#if defined(ARDUINO_ARCH_ESP8266)
digitalWrite(D1, state);
#endif
@ -95,11 +108,11 @@ void dispatchPage(String strPageid)
debugPrintln("PAGE: " + strPageid);
if(strPageid.length() == 0) {
String strPayload = String(haspGetPage());
mqttSendState("page", strPayload.c_str());
} else {
if(strPageid.toInt() <= 250) haspSetPage(strPageid.toInt());
}
String strPayload = String(haspGetPage());
mqttSendState("page", strPayload.c_str());
}
void dispatchClearPage(String strPageid)
@ -115,43 +128,39 @@ void dispatchClearPage(String strPageid)
void dispatchDim(String strDimLevel)
{
// Set the current state
if(strDimLevel.length() != 0) guiSetDim(strDimLevel.toInt());
debugPrintln("DIM: " + strDimLevel);
if(strDimLevel.length() == 0) {
String strPayload = String(guiGetDim());
mqttSendState("dim", strPayload.c_str());
} else {
guiSetDim(strDimLevel.toInt());
}
// Return the current state
String strPayload = String(guiGetDim());
mqttSendState("dim", strPayload.c_str());
}
void dispatchBacklight(String strPayload)
{
debugPrintln("LIGHT: " + strPayload);
strPayload.toUpperCase();
debugPrintln("LIGHT: " + strPayload);
if(strPayload == F("ON")) {
guiSetBacklight(true);
} else if(strPayload == F("OFF")) {
guiSetBacklight(false);
} else {
String strPayload = String(guiGetBacklight());
mqttSendState("light", strPayload.c_str());
}
// Set the current state
if(strPayload.length() != 0) guiSetBacklight(isON(strPayload.c_str()));
// Return the current state
strPayload = getOnOff(guiGetBacklight());
mqttSendState("light", strPayload.c_str());
}
void dispatchCommand(String cmnd)
{
cmnd.toLowerCase();
debugPrintln("CMND: " + cmnd);
if(cmnd.startsWith(F("page "))) {
cmnd = cmnd.substring(5, cmnd.length());
String strTopic((char *)0);
strTopic.reserve(127);
strTopic.reserve(128);
strTopic = F("page");
dispatchAttribute(strTopic, cmnd.c_str());
// dispatchPage(cmnd);
} else if(cmnd == F("calibrate")) {
guiCalibrate();
} else if(cmnd == F("wakeup")) {
@ -169,8 +178,8 @@ void dispatchCommand(String cmnd)
String strTopic((char *)0);
String strPayload((char *)0);
strTopic.reserve(127);
strPayload.reserve(127);
strTopic.reserve(128);
strPayload.reserve(128);
strTopic = cmnd.substring(0, pos);
strPayload = cmnd.substring(pos + 1, cmnd.length());
@ -225,15 +234,15 @@ void dispatchJsonl(char * strPayload)
}
}
void IRAM_ATTR dispatchIdle(const __FlashStringHelper * state)
void dispatchIdle(const __FlashStringHelper * state)
{
mqttSendState(String(F("idle")).c_str(), String(state).c_str());
}
void dispatchReboot(bool saveConfig)
{
mqttStop(); // Stop the MQTT Client first
if(saveConfig) configWriteConfig();
mqttStop(); // Stop the MQTT Client first
debugStop();
delay(250);
wifiStop();
@ -243,9 +252,9 @@ void dispatchReboot(bool saveConfig)
delay(5000);
}
void dispatchButton(uint8_t i, bool pressed)
void dispatchButton(uint8_t id, char * event)
{
char buffer[127];
snprintf_P(buffer, sizeof(buffer), PSTR("INPUT%d"), i);
mqttSendState(buffer, String(pressed ? F("ON") : F("OFF")).c_str());
char buffer[128];
snprintf_P(buffer, sizeof(buffer), PSTR("INPUT%d"), id);
mqttSendState(buffer, event);
}