ucosiii提供了一条API函数:void OSTaskStkChk(OS_TCB *p_tcb,CPU_STK_SIZE *p_free,CPU_STK_SIZE *p_used,OS_ERR *p_err)
在单片机中使用uC/OS III 时,RAM的空间是需要考虑的,在创建任务的时候需要指定任务的堆栈大小,给大了呢浪费资源,给小了呢又会导致堆栈溢出。uC/OS III提供了堆栈使用情况的统计函数,这有便于我们对与堆栈大小的确认。
************************************************************************************************************************
* STACK CHECKING
* Description: This function is called to calculate the amount of free memory left on the specified task's stack.
* Arguments : p_tcb is a pointer to the TCB of the task to check. If you specify a NULL pointer then
* you are specifying that you want to check the stack of the current task.
* p_free is a pointer to a variable that will receive the number of free 'entries' on the task's stack.
* p_used is a pointer to a variable that will receive the number of used 'entries' on the task's stack.
* p_err is a pointer to a variable that will contain an error code.
* OS_ERR_NONE upon success
* OS_ERR_PTR_INVALID if either 'p_free' or 'p_used' are NULL pointers
* OS_ERR_TASK_NOT_EXIST if the stack pointer of the task is a NULL pointer
* OS_ERR_TASK_OPT if you did NOT specified OS_OPT_TASK_STK_CHK when the task
* was created
* OS_ERR_TASK_STK_CHK_ISR you called this function from an ISR
************************************************************************************************************************
void OSTaskStkChk(OS_TCB *p_tcb,CPU_STK_SIZE *p_free,CPU_STK_SIZE *p_used,OS_ERR *p_err)
p_tcb 指向任务的TCB,当为空时,表示检测调用本函数的任务的栈
p_free 用于存储空闲栈大小的CPU_STK_SIZE类型的变量指针
p_used 用于存储已使用栈大小的CPU_STK_SIZE类型的变量指针
p_err 用于存储本函数返回的错误代码的变量指针
//测量任务堆栈大小例子:
OSTaskStkChk()可以计算出指定任务的空闲空间大小,以及已使用空间的大小。这个函数的使用前提是:任务创建的时候需要指定options 含OS_TASK_OPT_STK_CHK 和 OS_TASK_OPT_STK_CLR。
void stkCheck_task(OS_TCB *p_tcb,void *p_arg, char *title_str) //计算堆栈任务函数
{
OS_ERR err;
CPU_STK_SIZE free;
CPU_STK_SIZE used;
p_arg = p_arg;
OSTaskStkChk(p_tcb,&free,&used,&err);
printf("%s:tcb_free:%d\ttcb_used:%d\r\n",title_str, free, used); //free是剩余的堆栈空间,used是已用的堆栈空间,title_str是提示打印那个堆栈任务的空间的提示信息
}
stkCheck_task()该函数可以直接放在,想要检测堆栈使用空间情况的任务中,
也可以将stkCheck_task()函数创建一个任务用来实时检测其他任务堆栈的空间使用情况。