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.
First of all,
lastButtonsis initialized tofalse. Theifblock can't be entered untillastButtons[i]is true, butlastButtons[i]isn't modified anywhere except inside theifblock. So neither of those things ever happens.But maybe some other part of your code initializes
lastButtons[i]totrue. Whenbuttons[i]becomesfalsefor the first time, you enter theifblock, which setslastButtons[i]back tofalse. 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 readbuttons[i], even if it's not the edge that you want to take action on. I would write: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.)