Button class with auto repeat function.

Button.cpp

Committer:
vargham
Date:
2017-07-14
Revision:
5:faff91d60ae3
Parent:
4:d54859273629

File content as of revision 5:faff91d60ae3:

/**
* @file    Button.cpp
* @brief   Button library
* @author  Mark Peter Vargha, vmp@varghamarkpeter.hu
*
* Copyright (c) 2017
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

#include "Button.h"

void Button::startInterrupt()
{
    _in.rise(Callback<void()>(this, &Button::isrRise));
    _in.fall(Callback<void()>(this, &Button::isrFall));
}

void Button::stopInterrupt()
{
    _in.rise(NULL);
    _in.fall(NULL);
}

void Button::isrFall(void)
{
    if (_activeState == 0) onPress();
    else onRelease();
}

void Button::isrRise(void)
{
    if (_activeState == 0) onRelease();
    else onPress();
}

void Button::onPress(void)
{
    _timer.reset();
    if (_prevState == 0) //First
    {
        _timer.start();
        if (_fireUpDown && _onButtonEvent) _onButtonEvent(BUTTON_DOWN, _pinName);
    }
    _autoRepeatStarter.detach();
    if (_autoRepeatTime > 0) _autoRepeatStarter.attach(Callback<void()>(this, &Button::startAutoRepeat), (_longPressTime / 1000.0f));
    _prevState = 1;
}

void Button::onRelease(void)
{
    _timer.stop();
    _tickerAutoRepeat.detach();
    _autoRepeatStarter.detach();
    if (_fireUpDown && _onButtonEvent) _onButtonEvent(BUTTON_UP, _pinName);
    if (_prevState == 1 && _onButtonEvent)
    {
        if (_timer.read_ms() >= _longPressTime) //Long press
        {
            _onButtonEvent(BUTTON_LONG_PRESS, _pinName);
        }
        else if (_timer.read_ms() >= _shortPressTime) //Short press
        {
            _onButtonEvent(BUTTON_PRESS, _pinName);
        }
    }
    _prevState = 0;
    _timer.reset();
}

void Button::startAutoRepeat(void)
{
    _tickerAutoRepeat.detach();
    if (_autoRepeatTime > 0) _tickerAutoRepeat.attach(Callback<void()>(this, &Button::autoRepeat), (_autoRepeatTime / 1000.0f));
}

void Button::autoRepeat(void)
{
    if (_onButtonEvent) _onButtonEvent(BUTTON_PRESS, _pinName);
}