Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

A clever student hatched a plan to debounce a switch connected to INT2 (assume P

ID: 3592027 • Letter: A

Question

A clever student hatched a plan to debounce a switch connected to INT2 (assume PPS was done correctly and the INT2 interrupt was left at the default priority, 4). There was available a delay function, which would delay by its parameter in microseconds (here's its declaration): void delay( unsigned int musecs); Assume it works properly. So the student wrote this ISR: volatile unsigned short int buttonPresses = 0; void __attribute__((__interrupt__,__auto_psv__)) _INT2Interrupt(void) { IFS1bits.INT2IF = 0; SRbits.IPL = 1; // re-enable interrupts delay(40000); buttonPresses++; } (a) What could possibly go wrong? For some reason, that didn't quite work right, so the student scratched his (or her) head for a while, then made a little change: volatile unsigned short int buttonPresses = 0; void __attribute__((__interrupt__,__auto_psv__)) _INT2Interrupt(void) { SRbits.IPL = 1; // re-enable interrupts delay(40000); IFS1bits.INT2IF = 0; buttonPresses++; } (b) What could possibly go wrong? (c) How would you solve this problem using INT2 to detect switch closures? (Hint: you might want to use another device to help.)

Explanation / Answer

This code looks for changes, and only displays something when the switch changes.

By the way, you should be doing neither delay nor Serial.print inside an interrupt, as both of the rely upon interrupts being active, and interrupts are not active inside an ISR.

Debouncing

A simple technique is just to build in a short delay, for example 10 milliseconds (ms). For example:

In the above code the delay is inside loop (where it is OK to use it) and causes a short pause to allow the switch to stop bouncing.

Debouncing without delay

The above code is fine in simple applications, and if you test it, you should find that the message "Switch closed." and "Switch opened." should only occur once per switch press. But, there's a problem. If you hang around the Arduino forums for a little while you will probably see people telling you "don't use delay". There are various reasons for this, not the least is which that using delay stops your code from doing anything else useful (like testing sensors, controlling motors, flashing LEDs, etc.).

The code below does not use delay, but rather checks for the time that has elapsed after you hit the switch, and sees if the "debounceTime" (in this case 10 ms) has elapsed. If not, it ignores the transition.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote