5 years, 7 months ago.

How to get led to blink, and print times the LED turned on using the ‘printf’ function.

sorry does anyone know how to get this to work.

1. Write a program using ‘DigitalOut’ on the mbed board to blink LED1 at 1Hz and print the number of times the LED turned on using the ‘printf’ function. I tried to use a counter but it did not seem to work.

#include "mbed.h"
 
DigitalOut myled1(LED1);   
 
int main() {                 

    myled1 = 1; 
int counter = 0; //initialise counter object to zero
void count(){
counter++;        //increment counter object
  db.locate(0);
  db.printf("%06d", counter);
wait(1);       to get the 1 hz 
}

1 Answer

5 years, 7 months ago.

Hi David,

So a few initial notes regarding your program:

  1. Are you using a seperate library or Serial object to define the db variable? I am not sure whether you have pasted your code in its entirety or if it is just a snippet.
  2. Your void count(){ function declaration needs to be placed outside of main(), however for a small program like this I would use a while loop within main() instead. This will allow you to blink the LED and increment the counter forever (a loop that never stops running). For example:

#include "mbed.h"
 
DigitalOut myled1(LED1);   
 
int main() {                 
    myled1 = 1; 
    int counter = 0; //initialise counter object to zero
    while (true) {
        myled1 = !myled1; // Turn on/off myled1
        counter++; //increment counter object
        db.locate(0); // Where is your "db" object declared?
        db.printf("%06d", counter);
        wait(1);
    }
}

After you add a declaration for your db object (on line 11 above), you should then be able to view the increment counter printf's. I also added the code myled1 = !myled1 to alternate the blinking each loop. The !myled1 essentially means to turn off the LED if it is currently on, or to turn on the LED if it is currently off.

Also, if you would like to just view the printf output via your computer, I would take a look at the introductory debugging tutorial here: https://os.mbed.com/docs/latest/tutorials/debugging-using-printf-statements.html

Please let me know if you have any questions!

- Jenny, team Mbed

If this solved your question, please make sure to click the "Thanks" link below!