I have an optical sensor connected via analog, my issue is when the sensor is triggered it is running my integer increment multiple times, the behavior i am seeking is trigger once and wait for sensor to be de-triggered before allowing another increment.
my code is as follows:
int trig = analogRead(Trigger);
// trigger on: >850, trigger off: ~29
if (trig > 800) {
count++;
}
I have tried to follow the debounce tutorial to no success - adding a delay causes an issue with my 4 digit 7 segement display.
Keep in mind that using delay will pause everything that the arduino is doing for the length of the delay. An alternative way of doing this would be to save a flag, whether that be an integer, boolean, or byte that you can turn off or turn on depending on if the sensor was recently triggered. So, if your sensor is tripped at 850, you can turn on the flag which would prevent the increment from happening again. Once the sensor goes below 29, you can turn the flag off, which would allow the counter to be incremented on the next trip.
boolean flag = false;
void loop() {
int trig = analogRead(Trigger);
if(trig > 800 && !flag) {
count++;
flag = true;
}
else if(trig < 30 && flag) {
flag = false;
}
}