Search code examples
embeddedcortex-mrtosucos

When calling OS_EXIT_CRITICAL(), STM32 runs into HardFault


It is very odd.

OSInit();
OSTimeDly(10);
OSTaskCreate(start_task,(void *)0,(OS_STK *)&START_TASK_STK[TASK_STK_SIZE-1],START_TASK_PRIO);
OSStart();

In OSTimeDly(10),there is OS_Enter_CRITICAL() and OS_Exit_Critical(),and when the code is running into OS_Exit_Critical(),HardFault will happen.

void  OSTimeDly (INT32U ticks)
{
INT8U      y;
#if OS_CRITICAL_METHOD == 3u                     /* Allocate storage for CPU     status register           */
OS_CPU_SR  cpu_sr = 0u;
#endif



if (OSIntNesting > 0u) {                     /* See if trying to call from an ISR                  */
    return;
}
if (OSLockNesting > 0u) {                    /* See if called with scheduler locked                */
    return;
}
if (ticks > 0u) {                            /* 0 means no delay!                                  */
    OS_ENTER_CRITICAL();
    y            =  OSTCBCur->OSTCBY;        /* Delay current task                                 */
    OSRdyTbl[y] &= (OS_PRIO)~OSTCBCur->OSTCBBitX;
    if (OSRdyTbl[y] == 0u) {
        OSRdyGrp &= (OS_PRIO)~OSTCBCur->OSTCBBitY;
    }
    OSTCBCur->OSTCBDly = ticks;              /* Load ticks in TCB                                  */
    OS_EXIT_CRITICAL();
    OS_Sched();                              /* Find next task to run!                             */
    }
}

But,if I change the code to this:

#if OS_CRITICAL_METHOD == 3u                     /* Allocate storage for CPU status register           */
OS_CPU_SR  cpu_sr = 0u;
#endif
INT8U y;
...

OSInit();
OS_ENTER_CRITICAL();
y            =  OSTCBCur->OSTCBY;        /* Delay current task   */
OSRdyTbl[y] &= (OS_PRIO)~OSTCBCur->OSTCBBitX;
if (OSRdyTbl[y] == 0u) {
    OSRdyGrp &= (OS_PRIO)~OSTCBCur->OSTCBBitY;
}
OS_EXIT_CRITICAL();
//OSTimeDly(10);
OSTaskCreate(start_task,(void *)0,(OS_STK *)&START_TASK_STK[TASK_STK_SIZE-1],START_TASK_PRIO);
OSStart();

There are also OS_ENTER_CRITICAL() and OS_EXIT_CRITICAL(), But when the code is running into OS_EXIT_CRITICAL(), no HardFault happens.Why? I don't think there is any different.


Solution

  • You are calling OSTimeDly() before you have started the operating system.

    If you want to delay/pause/wait prior to starting the OS (via OSStart()), you will have to use a "dummy loop" with a volatile, or use a hardware timer (better), etc.