Forum Rule: Always post complete source code & details to reproduce any issue!
Results 1 to 4 of 4

Thread: Interrupt routine change of state too fast.

  1. #1
    Junior Member
    Join Date
    Dec 2019
    Posts
    9

    Interrupt routine change of state too fast.

    I am trying to link a variable with a change of state in an interrupt routine.

    Code:
    const int sensor = 21;
    volatile int triggerCounter = 0;
    
    void sumTrigger(){
      triggerCounter += 1;
      Serial.println("Trigger Counter");
      Serial.print(triggerCounter);
    };
    
    
    void sensorInterruptOn(){
    
      attachInterrupt(digitalPinToInterrupt(sensor), sumTrigger, CHANGE);
    
    };
    
    
    void triggerSwitch(){
      if (triggerCounter == 4){
          Serial.println("Trigger");
          triggerCounter = 0;
      }
    };
    
    void setup(){
    
    pinMode(sensor, INPUT);
    Serial.begin(115200);
    sensorInterruptOn();
    
    }
    
    void loop(){
    
    triggerSwitch();
    
    }
    The sensor is a reflective sensor that reads accurately when a surface is in front of it or not, as 0 and 1. It works fine when I'm polling it and controlling the surface slowly with a stepper motor, but when I try to get the same behavior with an interrupt, as the one above, my teensy seems to go much faster. Every change of state, instead of being reported once, is printed at least 20 times as "Trigger Counter" in the serial monitor. I don't understand what is going on exactly, but it feels like bouncing maybe? Is there a way to get only one change of state instead of 20? Thank you

  2. #2
    Senior Member
    Join Date
    Nov 2012
    Posts
    1,244
    That does seem to be "contact" bounce. Try the bounce library to handle the pin with a debounce time of 1 ms and increase if necessary.
    See the Examples|Bounce|change code (or the one in Bounce2)

    Pete

  3. #3
    Senior Member
    Join Date
    May 2015
    Location
    USA
    Posts
    329
    You could also add a few lines to sumTrigger() so that if isn't hasn't been 1 ms since the last switch, do nothing.

  4. #4
    Junior Member
    Join Date
    Dec 2019
    Posts
    9
    Thank you for your suggestion Pete, I didn't know about that library. It worked!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •