I present to you, this piece of code:
bool keyPressed = false;
void interruptServiceRoutine()
{
keyPressed = true;
}
int main()
{
for (;;)
{
while (!keyPressed);
std::cout << "A key was pressed!";
}
return 0;
}
Take a minute to think about what's wrong with the code above.
Ready? Ok, here are the things I came to think of during my job interview.
- keyPressed is set to true in the ISR. But never (re)set to false anywhere.
- keyPressed should be volatile to ensure the compiler does not optimize it.
- There is a risk for key bounce which may result in several interrupts per key press.
To solve 1 and 2 the code can be modified to look like this:
volatile bool keyPressed = false;
void interruptServiceRoutine()
{
keyPressed = true;
}
int main()
{
for (;;)
{
while (!keyPressed);
std::cout << "A key was pressed!";
keyPressed = false;
}
return 0;
}
In order to tackle 3, delays can be inserted. These are called debouncing periods and usually about 10 ms is enough. Note that key bounces can occur both when the key is pressed and when it is released.
I'll leave it to you to figure out where to insert the debouncing periods.
Kommentarer
Skicka en kommentar