6 years, 11 months ago.

nucleo, why is condition (button == 1) true more times?

hello, in this code i want to program blinking led, which starts to blink after pressed button, and after another press, it will blink faster, but condition (mybutton == 1) is true, whether the button is pressed or not. Can you help me please? Thanks

  1. include "mbed.h" DigitalIn mybutton(PC_13); DigitalOut myled(PA_5); int main() { while(1) { if (mybutton == 1) Button is pressed { while(1) {

myled = 1; LED is ON wait(1); myled = 0; LED is OFF wait(1); if (mybutton == 1) Button is pressed { while(1) { myled = 1; LED is ON wait(0.2); myled = 0; LED is OFF wait(0.2); } } } } } }

Please use

<<code>>
your code
<</code>>

So that formatting is preserved otherwise it's hard to read and we can't tell which bits if any are commented out.

#include "mbed.h"

DigitalIn mybutton(PC_13);
DigitalOut myled(PA_5);

int main() { 
  while(1) {
     if (mybutton == 1)  // Button is pressed
        { 
        while(1)  {
         myled = 1; // LED is ON
         wait(1);
         myled = 0;  //LED is OFF 
         wait(1); 
         if (mybutton == 1) //  Button is pressed 
           {
            while(1) {
              myled = 1; // LED is ON
              wait(0.2);
              myled = 0; // LED is OFF
              wait(0.2);
            }
          }
        }
      }
    }
 }
posted by Andy A 10 Apr 2017

1 Answer

6 years, 11 months ago.

From what I can tell of your code each of your if (button==1) lines is followed by a while(1) so as soon as the button is pressed you enter an infinite loop and never exit again. Is that what you intend?

How is the button connected? It's fairly common for a button to be wired so that pressing the button makes the input low rather than high. You can often get that for LEDs too where 0 is on, 1 is off.

To be sure either look at the schematics for your specific board or try a simple test program, something like this:

#include "mbed.h"
 
DigitalIn mybutton(PC_13);
DigitalOut myled(PA_5);
 
int main() { 
  for (int i = 0;i<10;i++) {
    myled=0;
    wait(1);
    myled=1;
    wait(0.2);
  }
  while(1) {
     myled = mybutton;
  }
 }

The first bit is to check which way the LED is, if you get short flashes then it's 1 for on, 0 for off, if it's on most of the time then it's 0 for on, 1 for off.

The second part is to check the button. If then LED is off when the button isn't pressed and on when it is then they are both the same, if the LED is 1 for on then the button is 1 for pressed etc... If the LED is on when the button isn't pressed then they are opposites, if the LED is 1 for on then the button is 0 for pressed.

If you find the code confusing using 0 for pressed you can always use a #define and the start e.g.

#define BUTTON_PRESSED 0
...
if (mybuton == BUTTON_PRESSED)

This also makes it easy if you ever need to move the code to a different board that is wired differently.