A capacitive touch sensor using a analog input port.

Dependents:   TouchSenseTestProgram

TouchSense.h

Committer:
shintamainjp
Date:
2013-08-15
Revision:
1:08658b9787d8
Parent:
0:5a0704efe081

File content as of revision 1:08658b9787d8:

/* mbed Microcontroller Library
 * Copyright (c) 2013 Shinichiro Nakamura
 *
 * 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.
 */

#ifndef TOUCHSENSE_H
#define TOUCHSENSE_H

#include "platform.h"
#include "gpio_api.h"
#include "analogin_api.h"

namespace mbed
{

/**
 * A capacitive touch sensor using analog input port.
 *
 * Example:
 * @code
 * #include "mbed.h"
 *
 * TouchSense tp(p18);
 *
 * int main() {
 *     tp.calibration();
 *     while(1) {
 *         if (tp.sense()) {
 *             printf("ON\r\n");
 *         } else {
 *             printf("OFF\r\n");
 *         }
 *         wait(0.1);
 *     }
 * }
 * @endcode
 */
class TouchSense
{

public:
    /**
     * Create a TouchSense connected to the specified pin
     *
     * @param pin TouchSense pin to connect to
     * @param thr Threshold (1 to 20)
     */
    TouchSense(PinName pin, int thr = 10) : mypin(pin), calval(0) {
        for (int i = 0; i < DATA_COUNT; i++) {
            data[i] = 0;
        }
        if (thr < THRMIN) {
            thr = THRMIN;
        }
        if (thr > THRMAX) {
            thr = THRMAX;
        }
        threshold = thr;    
        execute();
    }

    void calibration() {
        uint32_t r = 0;
        for (int i = 0; i < DATA_COUNT; i++) {
            r += execute();
            wait_us(100);
        }
        r = r / DATA_COUNT;
        calval = r;
    }

    bool sense() {
        data[index] = execute();
        index = (index + 1) % DATA_COUNT;
        uint32_t r = 0;
        for (int i = 0; i < DATA_COUNT; i++) {
            r += data[i];
        }
        r = r / DATA_COUNT;
        return (calval * threshold) < r;
    }

private:

    uint16_t execute() {
        uint16_t r;
        analogin_init(&adc, mypin);
        r = analogin_read_u16(&adc) >> 4;
        gpio_init(&gpio, mypin, PIN_OUTPUT);
        gpio_write(&gpio, 1);
        return r;
    }

protected:
    PinName mypin;
    uint16_t calval;
    gpio_t gpio;
    analogin_t adc;
    static const int DATA_COUNT = 8;
    uint32_t data[DATA_COUNT];
    int index;
    int threshold;
    static const int THRMIN = 1;
    static const int THRMAX = 20;
};

} // namespace mbed

#endif