'Toggle a LED on and off with the push of a button on NUCLEO410RB using Mbed Studio in C++

#include "mbed.h"  
 
DigitalOut myLed(LED1); 
DigitalIn myButton(BUTTON1);  
 
int main() { 

    while(true){ 
        //active low push button 
        if(myButton == 0){ 
            //use 100 ms as wait time to sense 1 button press 
            ThisThread::sleep_for(100); 
            if(myButton == 0)  
                myLed=1; 
            else 
                myLed=0; 
        } 
    } 
}

I am asked to modify the code so that when I press the button it turns the LED on and if I press it again it turns it off. I can get the light to stay on, but I can't seem to understand how to turn it off. Below is what I have so far.

#include "mbed.h"  
 
DigitalOut myLed(LED1); 
DigitalIn myButton(BUTTON1);  

 
int main() { 

    while(true){ 
        //active low push button 
        if(myButton == 0){ 
            //use 100 ms as wait time to sense 1 button press 
            ThisThread::sleep_for(100); 
            if(myButton == 1)  
                myLed=1; 
        }
     
    } 
}

If you all could give me some suggestions, I would appreciate it!!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source