A capacitive touch sensor using a analog input port.

Dependents:   TouchSenseTestProgram

TouchSense.h

Committer:
shintamainjp
Date:
2013-08-14
Revision:
0:5a0704efe081
Child:
1:08658b9787d8

File content as of revision 0:5a0704efe081:

/* 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
     */
    TouchSense(PinName pin) : mypin(pin), calval(0) {
    }
    
    void calibration() {
        uint16_t f1, f2, f3, f4;
        f1 = execute();
        f2 = execute();
        f3 = execute();
        f4 = execute();
        calval = (f1 + f2 + f3 + f4) / 4.0;
    }
    
    bool sense() {
        uint16_t f = execute();        
        return (calval * 3.00) < f;
    }

private:

    uint16_t execute() {
        gpio_init(&gpio, mypin, PIN_OUTPUT);
        gpio_write(&gpio, 1);
        __nop();
        __nop();
        __nop();
        __nop();
        analogin_init(&adc, mypin);
        return analogin_read_u16(&adc);
    }

protected:
    PinName mypin;
    uint16_t calval;
    gpio_t gpio;
    analogin_t adc;
};

} // namespace mbed

#endif