Interrupt routine change of state too fast.

Status
Not open for further replies.
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
 
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
 
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.
 
Status
Not open for further replies.
Back
Top