Final Commit

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers DebounceIn.cpp Source File

DebounceIn.cpp

00001 /* A digital input with switch debouncing
00002  * Copyright 2015, Takuo Watanabe
00003  *
00004  * Licensed under the Apache License, Version 2.0 (the "License");
00005  * you may not use this file except in compliance with the License.
00006  * You may obtain a copy of the License at
00007  *
00008  *   http://www.apache.org/licenses/LICENSE-2.0
00009  *
00010  * Unless required by applicable law or agreed to in writing, software
00011  * distributed under the License is distributed on an "AS IS" BASIS,
00012  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
00013  * See the License for the specific language governing permissions and
00014  * limitations under the License.
00015  */
00016 
00017 #include "DebounceIn.h"
00018 
00019 DebounceIn::DebounceIn(PinName pin, timestamp_t us) : DigitalIn(pin) {
00020     _prev = _curr = 0;
00021     _rise = _fall = NULL;
00022     set_sample_rate(us);
00023 }
00024 
00025 DebounceIn::~DebounceIn() {
00026     _ticker.detach();
00027 }
00028 
00029 int DebounceIn::read() {
00030     return _curr;
00031 }
00032 
00033 #ifdef MBED_OPERATORS
00034     /** An operator shorthand for read()
00035      */
00036     DebounceIn::operator int() {
00037         return read();
00038     }
00039 #endif
00040 
00041 void DebounceIn::set_sample_rate(timestamp_t us) {
00042     _ticker.detach();
00043     _ticker.attach_us(this, &DebounceIn::sample, us);
00044 }
00045 
00046 void DebounceIn::rise(void (*fptr)(void)) {
00047     _rise.attach(fptr);
00048 }
00049 
00050 void DebounceIn::fall(void (*fptr)(void)) {
00051     _fall.attach(fptr);
00052 }
00053 
00054 void DebounceIn::sample() {
00055     int now = DigitalIn::read();
00056     if (now == _prev) {
00057         if (!_curr && now) _rise.call();
00058         if (_curr && !now) _fall.call();
00059         _curr = now;
00060     }
00061     _prev = now;
00062 }