Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Filename: touch_toggle.c
- /* Compile with gcc -lwiringPi touch_toggle.c -o touch_toggle
- * Run with sudo ./touch_toggle
- * Do not touch while starting the program so it can initialize properly
- */
- /* SCHEMATIC
- *
- * ,----------------------,
- * | Raspberry Pi |
- * | |
- * | TOUCH_PIN VCC |
- * `-----+-------------+--'
- * | |
- * +---[1MΩ]-----+
- * |
- * Touch surface
- *
- */
- #include <wiringPi.h>
- #include <stdio.h>
- // Note: Pin numbers are in BCM notation (pin number format is set by wiringPiSetupGpio)
- // See pinout.xyz
- #define TOUCH_PIN 20
- #define OUTPUT_PIN 21
- // How long to pull the touch pin low
- // Controls loop speed and affects CPU usage
- #define DELAY 15
- int main(void) {
- wiringPiSetupGpio();
- unsigned int timer;
- unsigned int threshold = 0;
- unsigned char state = 0; // Currently being touched?
- unsigned char out_state = 0; // State of output pin
- signed char hysteresis = 0; // Counter for consecutive readings
- pullUpDnControl(TOUCH_PIN, PUD_OFF); // Not sure if this would ever be set, just to be safe
- pinMode(OUTPUT_PIN, OUTPUT);
- digitalWrite(OUTPUT_PIN, out_state);
- // Measure capacitance to calibrate touch sensitivity
- for (char i=0; i < 10; i++) {
- // Pull touch pin low to discharge
- pinMode(TOUCH_PIN, OUTPUT);
- digitalWrite(TOUCH_PIN, LOW);
- // Wait a bit
- delay(DELAY);
- // Start timer
- timer = micros();
- pinMode(TOUCH_PIN, INPUT);
- // Wait for pin to become high
- while (!digitalRead(TOUCH_PIN));
- // Get time elapsed
- threshold += micros() - timer;
- }
- // Set threshold to twice the average capacitance
- threshold /= 5; // This number might need to be increased if the touch is not sensitive enough
- printf("threshold=%d\n",threshold);
- while (1) {
- pinMode(TOUCH_PIN, OUTPUT);
- digitalWrite(TOUCH_PIN, LOW);
- delay(DELAY);
- timer = micros();
- pinMode(TOUCH_PIN, INPUT);
- while (!digitalRead(TOUCH_PIN));
- timer = micros() - timer;
- if (timer > threshold) {
- if (hysteresis < 0) hysteresis = 0;
- hysteresis++;
- } else {
- if (hysteresis > 0) hysteresis = 0;
- hysteresis--;
- }
- // 3 consecutive readings are required to toggle touch state
- if (hysteresis > 2) {
- if (state == 0) {
- out_state = !out_state;
- digitalWrite(OUTPUT_PIN, out_state);
- state = 1;
- // Print when touch starts and the measured value
- // Can be commented out
- printf("START %d", timer);
- fflush(stdout); // Display instantly (by default only flushed on newline)
- }
- hysteresis = 0;
- } else if (hysteresis < -2) {
- if (state == 1) {
- state = 0;
- printf(" END\n");
- }
- hysteresis = 0;
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement