Reputation: 1
I'm using the mbed OS with a Nucleo G071RB to send data about a button press event. My issue is that the data is either being send continuously while the button is pressed, or on the press and release events. As far as I can tell, the program should send the data when the button value changes from 0 to 1, but it does not behave this way.
#include "mbed.h"
DigitalIn buttons[2]{{D6,PullUp},{D7,PullUp}};
bool lastButtons[2]{0,0};
void buttonFn()
{
for(int i=0;i<2;i++)
{
if(!buttons[i] && lastButtons[i])
{
printf("%c",i);
lastButtons[i] = !buttons[i];
}
}
}
The buttons[i] object is inverted because they are PullUp buttons.
I've tried using different combinations of logic, for example if the button state is !0 or 1, and the last state is 0, it should evaluate to true and send the statement. It shouldn't do so in any other state.
Upvotes: 0
Views: 34
Reputation: 58087
First of all, lastButtons
is initialized to false
. The if
block can't be entered until lastButtons[i]
is true, but lastButtons[i]
isn't modified anywhere except inside the if
block. So neither of those things ever happens.
But maybe some other part of your code initializes lastButtons[i]
to true
. When buttons[i]
becomes false
for the first time, you enter the if
block, which sets lastButtons[i]
back to false
. And now you're in the same boat as before, that the block can never be entered again.
You need to update lastButtons[i]
every time you read buttons[i]
, even if it's not the edge that you want to take action on. I would write:
if (!buttons[i] && lastButtons[i])
{
printf("%c",i);
}
lastButtons[i] = buttons[i];
Note that for a real application, you'll probably want further logic to debounce the button, otherwise you'll get several extra press events each time the button is actually pushed.
(Another good idea would be to find a way to make the button interrupt-driven rather than polling it.)
Upvotes: 0