1 year, 7 months ago.

How do I toggle LED1 on and off by pressing the User button?

What is the code to toggle LED1 on and off by pressing the blue user button? I'm using the STM32 Nucleo F303RE.

1 Answer

1 year, 7 months ago.

#include "mbed.h"
 
DigitalIn userButton(USER_BUTTON);
DigitalOut led(LED1);

bool buttonDown = false;

main() {
 while (true) {  // run forever
  if (userButton) {  // button is pressed
     if  (!buttonDown) {  // a new button press
      led = !led;                 // toogle LED
      buttonDown = true;     // record that the button is now down so we don't count one press lots of times
      wait_ms(10);              // ignore anything for 10ms, a very basic way to de-bounce the button. 
     } 
   } else { // button isn't pressed
    buttonDown = false;
   }
 }
}

userButton will be 1 when pressed and 0 when not pressed so you could use if (userButton == 1) rather than if (userButton) if you find that makes the code easier for you to follow. The shorter version is using the c convention is that anything other than 0 is evaluated as being true.

Similarly led = !led is doing the same thing to toggle the led. The lines if (led == 1) led = 0; else led = 1; or led=(led==1)?0:1; would both have exactly the same effect.