Advertisement
TolentinoCotesta

Interrupt based debounce

Mar 7th, 2019
175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.07 KB | None | 0 0
  1. // usiamo micros() al posto di millis solo per valutare con più precisione i tempi in gioco
  2. #define US_DEBOUNCE_TIME 300000
  3. #define interruptPin 2
  4. #define ledPin 13
  5.  
  6. bool int_flag = false;
  7. unsigned long int_time;
  8.  
  9. void pinChange() {  
  10.   // flag attivo, ma tempo ancora non trascorso
  11.   if(!int_flag){
  12.     int_flag = true;
  13.     int_time = micros();  
  14.   }
  15. }
  16.  
  17. void setup() {
  18.   Serial.begin(115200);
  19.   pinMode(ledPin, OUTPUT);
  20.   pinMode(interruptPin, INPUT_PULLUP);
  21.   attachInterrupt(digitalPinToInterrupt(interruptPin), pinChange, CHANGE);
  22. }
  23.  
  24. void loop() {
  25.   // Se flag è attivo e sono passati US_DEBOUNCE_TIME eseguo il codice
  26.   if( int_flag && ( micros() - int_time > US_DEBOUNCE_TIME )){      
  27.     int_flag = false;
  28.     if( digitalRead(interruptPin) == HIGH ){
  29.       //Serial.println("Livello Pin 2 HIGH");
  30.       digitalWrite(ledPin, HIGH);
  31.     }
  32.     else{
  33.       //Serial.println("Livello Pin 2 LOW");
  34.       digitalWrite(ledPin, LOW);
  35.     }
  36.    
  37.     //Serial.print("uS da interrupt + esecuzione codice: ");
  38.     Serial.println(micros() - int_time);    
  39.   }
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement