Semphores and threads

elvarliiv wrote on Monday, May 07, 2018:

Hello

I am using freeRTOS(v9) 1st time, so I am kind a new in this field. I am trying to figure out, why my stm32discovery board crashes and I somehow have a feeling that it might be related to using sempahores wrongly.

I am recieving CAN messages and if I recieve certain ID messages, I want to run a task. At the moment I am only using 2 tasks. Basicly I need to control a car - one thread is for speed and the other one for steering. Both threads are equally prioritized (osPriorityHigh).
In CAN_Rx callback function, i give semaphore like this:

 case CAN_ID_1:
    xSemaphoreGiveFromISR(GasBinarySemHandle, &task_woken);
    if (task_woken) {
        portYIELD_FROM_ISR(task_woken);
    }
case CAN_ID_2:
    xSemaphoreGiveFromISR(WheelBinarySemHandle, &task2_woken);
    if (task2_woken) {
        portYIELD_FROM_ISR(task2_woken);
    }

And my threads for loops are like this:

thread1 {
    for (;;) {
        if (xSemaphoreTake(GasBinarySemHandle, portMAX_DELAY)) {
            //do something
        }
    }
}

and

thread2 {
    for (;;) {
        if (xSemaphoreTake(WheelBinarySemHandle, portMAX_DELAY)) {
            //do something
        }
    }
}

My main question here is, is this the right way to use semaphores or could wrongly used semaphores cause my program to crash. Then I use only one thread and semaphore, everything works nicely.

heinbali01 wrote on Monday, May 07, 2018:

Hello Elvar Liiv,

My main question here is, is this the right way to use semaphores or could
wrongly used semaphores cause my program to crash. Then I use only one thread
and semaphore, everything works nicely.

There is nothing against using a single task with a single semaphore. You could use a queue in stead of a semaphore, and send a specific message, like eWheel and eGas.

But it is interesting to know why your application is crashing.

When you call xSemaphoreGiveFromISR(), is that really from an interrupt context, or from some library call-back? If it is not from an ISR, you better not use the FromISR() function.

What do you mean with “crashes”? Does the CPU get an exception? Or maybe, does the code land in some configASSERT()?
Do you have in-circuit debugging? That could be very helpful to inspect a crash.