Important changes to forums and questions
All forums and questions are now archived. To start a new conversation or read the latest updates go to forums.mbed.com.
6 years, 8 months ago.
Thread called only once when thread is created
Hi , I tried a thread program to glow an LED in the Disco-L476VG board.But the thread i s called only once when created.
I have toggled another LED in main thread which keeps going but new thread is called only once.
My prog
#include "mbed.h" #include "rtos.h" Thread thread; DigitalOut led_red(LED2); DigitalOut led_green(LED1); void led2_thread(DigitalOut *led) { while (true) { *led = !*led; Thread::wait(1); } } int main() { thread.start(led2_thread,&led_red); while (true) { led_green = !led_green; Thread::wait(500); } }
What would be the prob,I am using mbed-os version 5.3.3 .
Is thread is not stable with STM32 ?
Thanks, E.k
4 Answers
6 years, 8 months ago.
You cannot read the value of the LED through *led
, as it returns the object (and does not use the operator overloading which is normally used) and thus always evaluates to the same value. E.g. *led
on my NUCLEO-F411RE returns 32 all the time, thus the same value is written to the LED.
Instead, do this:
*led = !led->read();
6 years, 8 months ago.
Hello Karthick,
Instead of calling Thread::wait(float)
try to call wait(float)
(or wait_ms(int)
) as below.
NOTE: I assume that the 500s delay in main's while
loop was a typo not an intention.
#include "mbed.h" #include "rtos.h" Thread thread; DigitalOut led_green(LED1); DigitalOut led_red(LED2); void led2_thread(DigitalOut* led) { while (true) { *led = !*led; wait(1.0); } } int main(void) { thread.start(callback(led2_thread, &led_red)); while (true) { led_green = !led_green; wait(0.5); } }
Sorry, it seems that the typo wasn't in the main's while
loop but in the led2_thread
function. Nevertheless, both solutions (with wait(float)
above as well as with Thread::wait(int)
below) should work fine.
#include "mbed.h" #include "rtos.h" Thread thread; DigitalOut led_green(LED1); DigitalOut led_red(LED2); void led2_thread(DigitalOut* led) { while (true) { *led = !*led; Thread::wait(1000); } } int main(void) { thread.start(callback(led2_thread, &led_red)); while (true) { led_green = !led_green; Thread::wait(500); } }
6 years, 8 months ago.
I believe that Thread::wait(500) is 500 milliseconds. The pre-OS wait(500) is both a blocking wait, and is measured in seconds. (It takes a float, so wait(0.5) would be 500 msec.
6 years, 8 months ago.
*led = !*led;
works also fine.
Thread::wait(500);
waits for 500 ms, that is ok. But in led2_thread, you wait only for 1 ms. So your eyes must be damned fast to see the LED blinking :-)