A digital input with switch debouncing
Dependents: DebounceIn_Demo RotaryEncoderWaterFlow
DebounceIn.cpp
- Committer:
- takuo
- Date:
- 2015-12-20
- Revision:
- 0:e43521d55082
File content as of revision 0:e43521d55082:
/* A digital input with switch debouncing * Copyright 2015, Takuo Watanabe * * 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 "DebounceIn.h" DebounceIn::DebounceIn(PinName pin, timestamp_t us) : DigitalIn(pin) { _prev = _curr = 0; _rise = _fall = NULL; set_sample_rate(us); } DebounceIn::~DebounceIn() { _ticker.detach(); } int DebounceIn::read() { return _curr; } #ifdef MBED_OPERATORS /** An operator shorthand for read() */ DebounceIn::operator int() { return read(); } #endif void DebounceIn::set_sample_rate(timestamp_t us) { _ticker.detach(); _ticker.attach_us(this, &DebounceIn::sample, us); } void DebounceIn::rise(void (*fptr)(void)) { _rise.attach(fptr); } void DebounceIn::fall(void (*fptr)(void)) { _fall.attach(fptr); } void DebounceIn::sample() { int now = DigitalIn::read(); if (now == _prev) { if (!_curr && now) _rise.call(); if (_curr && !now) _fall.call(); _curr = now; } _prev = now; }