acastles91
Member
I am trying to link a variable with a change of state in an interrupt routine.
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
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