6 years, 5 months ago.

mbed running two threads

Hi, actually I want to write a program which involves two threads, thread 1 and thread2. Initially thread1 must start running and after executing thread 1, thread 2 should start running. How can I do that. Following is the snippet of my program which I have implemented, but the issue is only thread 1 is running, thread 2 does not gets executed.

  1. include "mbed.h"
  2. include "TextLCD.h"
  3. include "pindef.h"
  4. include "rtos.h"

I2C interface I2C temp_sensor(I2C_SDA, I2C_SCL); Serial pc(UART_TX, UART_RX);

I2C address of temperature sensor DS1631 const int temp_addr = 0x90;

char start=0x51; char read=0xAA; char read_temp[2]; DigitalOut myled(LED1); TextLCD LCD(PA_0,PA_1,PA_4,PB_0,PC_1,PC_0);

DigitalOut led1(LED1); DigitalOut led2(LED2); Thread thread;

void led1_thread(){ led1=!led1; Thread::wait(500);

} void led2_thread() { LCD.printf("temperature:"); float i=0.0; while(1) { temp_sensor.write(temp_addr,&start,1);Start temperature measurement wait(0.76); temp_sensor.write(temp_addr,&read,1);Read command read_temp[0]=0; read_temp[1]=0; temp_sensor.read(temp_addr,read_temp,2);Read the value from 2 byte register wait(0.76);

Convert temperature to Celsius float temp = (float((read_temp[0] << 8) | read_temp[1]) / 256);Conversion of temperature to celsius

Print temperature to the serial monitor LCD.locate(0,1); Write your code here LCD.printf(" %f ",temp);

} }

int main() {

while (true) { thread.start(led1_thread); start the thread 1 Thread::wait(500);

thread.start(led2_thread); start thread 2 Thread::wait(500);

} }

1 Answer

6 years, 5 months ago.

Hint: If you look at the "editing tips" just below the text box, you 'll see how to wrap your code with tags and make it so much easier to read.

// so it looks like code
int main() {
    while (true) { 
        thread.start(led1_thread); // start the thread 1 
        Thread::wait(500);
        thread.start(led2_thread); // start thread 2 
        Thread::wait(500);
    }
}

Your construction for the threads is a bit different than I usually see. It might be ok, but since it doesn't work, perhaps you can review some of the samples from the OS documentation pages.

More typically, you start the threads in main, and then the threads have their own while(1) loop, using the various APIs to sleep, or context switch. Then main has a more-or-less empty while(1). Sorry I can be of more help than this.

The led1_thread and led2_thread should be outside the while loop inside main. The led1_thread and led2_thread should contain a while loop each.

posted by huiying jiang 01 Jun 2018