3 * Copyright (c) 2020 Project CHIP Authors
4 * Copyright (c) 2018 Nest Labs, Inc.
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
23 * Implements a Button tied to a GPIO and provides debouncing and polling
27 #include "driver/gpio.h"
29 #include "esp_system.h"
32 #include <platform/CHIPDeviceLayer.h>
33 #include <support/CodeUtils.h>
35 extern const char * TAG;
37 esp_err_t Button::Init(gpio_num_t gpioNum, uint16_t debouncePeriod)
42 mDebouncePeriod = debouncePeriod / portTICK_PERIOD_MS;
44 mLastPolledState = false;
46 err = gpio_set_direction(gpioNum, GPIO_MODE_INPUT);
57 uint32_t now = xTaskGetTickCount();
59 bool newState = gpio_get_level(mGPIONum) == 0;
61 if (newState != mLastPolledState)
63 mLastPolledState = newState;
67 else if (newState != mState && (now - mLastReadTime) >= mDebouncePeriod)
70 mPrevStateDur = now - mStateStartTime;
71 mStateStartTime = now;
78 uint32_t Button::GetStateDuration()
80 return (xTaskGetTickCount() - mStateStartTime) * portTICK_PERIOD_MS;