// ---------------------------------- // ------- TRXYS TOUCH HELPERS ------ // ---------------------------------- // ( put this code PRIOR to your mainloop code or you will get nice errors :) ) // simple lerp helper function float return_lerp(float _s, int _target,int _time){ _s = _s + (( float(_target) - _s)/float(_time)); return _s; } class aTouch { private: bool prev_touch_state = false; byte pin; int smooth_time = 3; int trigger_threshold = 14; long ts = 0; public: int current_val = 0; int smoothed_val = 0; int diff_val = 0; bool is_triggered = false; bool on_pressed = false; bool on_released = false; bool is_holded = false; aTouch(byte pin) { this->pin = pin; } void readAndProcessInput() { // reset interaction states on_pressed = false; on_released = false; // directly read out values TWICE = BUGFIX for debouncing current_val = touchRead(pin); delayMicroseconds(10); current_val = touchRead(pin); //calculate smoothed input values smoothed_val = return_lerp(smoothed_val,current_val,smooth_time); // calc current differential sum of button diff_val = smoothed_val - current_val; // check if there is a noticable difference input values if( diff_val > trigger_threshold){ if(prev_touch_state == false){ is_triggered = true; prev_touch_state = is_triggered; on_pressed = true; ts = millis(); // set timestamp for hold routine } }else if( diff_val < trigger_threshold*-.4){ if(prev_touch_state == true){ is_triggered = false; prev_touch_state = is_triggered; on_released = true; } } // calculate timed holding function if( ts + 2500 < millis() && is_triggered){ is_holded = true; }else{ is_holded = false; } delayMicroseconds(2); } };
MAIN SCRTIPT
needs a BLEKeyboard lib installed!
#include <Arduino.h> #include <touchy.h> #include <BleKeyboard.h> // ---------------------------------- // -------MAIN LOOP ----------------- // ---------------------------------- // initalize the aTouch objects : aTouch namewahtevet(yourpinnumber); aTouch touch1(2); aTouch touch2(4); aTouch touch3(15); aTouch touch4(13); /* aTouch touch5(12); aTouch touch6(14); aTouch touch7(27); aTouch touch8(33); aTouch touch9(32); */ BleKeyboard bleKeyboard; void setup(){ //Serial.begin(9600); delay(100); Serial.println("Starting BLE work!"); bleKeyboard.begin(); } void loop() { // simply read input and do some calc touch1.readAndProcessInput(); touch2.readAndProcessInput(); touch3.readAndProcessInput(); touch4.readAndProcessInput(); /* touch5.readAndProcessInput(); touch6.readAndProcessInput(); touch7.readAndProcessInput(); touch8.readAndProcessInput(); touch9.readAndProcessInput(); */ if(touch1.is_triggered){ //Keyboard.write("a"); bleKeyboard.write( KEY_UP_ARROW ); } if(touch2.is_triggered){ //Keyboard.write("a"); bleKeyboard.write( KEY_DOWN_ARROW ); } if(touch3.is_triggered){ //Keyboard.write("a"); bleKeyboard.write( KEY_LEFT_ARROW ); } if(touch4.is_triggered){ //Keyboard.write("a"); bleKeyboard.write( KEY_RIGHT_ARROW ); } delay(100); }