STM32
直播中

张亮

8年用户 1388经验值
私信 关注
[问答]

STM32F107+CubeMX+FreeRTOS+LWIP连接成功后,信号量无法使用怎么解决?

各位大哥,遇到一个在FreeRTOS+LWIP使用信号量的问题。
项目工程是通过CubeMX生成的,使用FreeRTOS + LWIP。
简化代码,FreeRTOS初始化两个任务,一个默认任务、一个等待信号量任务。在默认任务中和PC上面的TCP server建立连接。在另外一个等待信号量。

信号量任务
extern osSemaphoreId EthBinSemHandle;
void task_usart_function()
{
    osSemaphoreWait(EthBinSemHandle, 0); //消耗第一次初始化之后的信号量
    UsrLog("Usart Task Start");
    for (;;)
    {
        if (osSemaphoreWait(EthBinSemHandle, osWaitForever) == osOK)
        {UsrLog("Processing");}
        else
        {UsrLog("Wait Failed");}
    }
}


默认任务
static volatile uint8_t sec_tic = 1;
extern osSemaphoreId EthBinSemHandle;
void task_default_function(void)
{
    // Application init code
    connect_server(get_connect_state(CLIENT_SERVER));
    for (;;)
    {
        HAL_IWDG_Refresh( hiwdg);
        if ((sec_tic + 15) % 15 == 0)
        {
            //每隔15秒释放一次信号量
            osSemaphoreRelease(EthBinSemHandle);
        }
        sec_tic++;
        osDelay(1000);
    }
}

void connect_server(conn_state_t* conn_state)
{
    if (get_link_state() == TRUE    conn_state->connected == FALSE)
    {
        connect_init(conn_state, get_config_local_port(CLIENT_SERVER));
/* 在connect_init()里面主要操作了netconn_new以及netconn_bind.
    local_server->conn = netconn_new(NETCONN_TCP);
    if ((ret = netconn_bind(local_server->conn, NULL, port)) == ERR_OK)

*/
        connect_connect(conn_state,  (get_server_data(CLIENT_SERVER)->ip_addr), get_server_data(CLIENT_SERVER)->port);
/*在connect_connect()里面主要是
        ret = netconn_connect(conn_state->conn, ip_addr, port);
        一旦执行了netconn_connect()之后,信号量的使用就没办法用了。
*/
    }
}



TCP通信没有问题,也可以PING通。如果注释掉//connect_connect()函数,每隔15秒,可以在串口看到一个打印,说明信号量释放成功。
如果使用connect_connect函数,在PC上TCP客户端可以发现,链接已经链接成功。
此时,如果执行osSemaphoreRelease(EthBinSemHandle);整个系统会死机。如果不执行osSemaphoreRelease(EthBinSemHandle);,可以进行正常的TCP通信。

问题出在TCP建立连接之后,osSemaphoreRelease(EthBinSemHandle);函数会hang住,尝试暂停debug了一下,发现是在queue.c中,
configASSERT( !( ( pvItemToQueue == NULL )    ( pxQueue->uxItemSize != ( UBaseType_t ) 0U ) ) );导致整体系统处于for循环的情况。
检查了一下pxQueue->uxItemSize的数值为0x10000000.

不知道应该怎么搞了。不知道还有朋友遇到这样的问题吗??


回帖(1)

偶是糕富帅

2024-4-19 15:58:24
在使用信号量之前,需要先创建一个信号量对象并初始化。

在CubeMX生成的代码中,可以在`MX_FREERTOS_Init()`函数中添加信号量的创建和初始化代码。例如:

```
osSemaphoreDef(EthBinSem);
osSemaphoreId EthBinSemHandle;

void MX_FREERTOS_Init(void)
{
  /* Other code */

  /* Create the semaphore */
  osSemaphoreDef(EthBinSem);
  EthBinSemHandle = osSemaphoreCreate(osSemaphore(EthBinSem), 1);

  /* Other code */
}
```

然后,在等待信号量的任务中使用此信号量:

```
extern osSemaphoreId EthBinSemHandle;

void task_usart_function()
{
  osSemaphoreWait(EthBinSemHandle, osWaitForever);

  // 执行其他任务操作

  osSemaphoreRelease(EthBinSemHandle);
}
```

确保在等待信号量之前,使用`osSemaphoreWait()`函数来等待信号量,然后在任务完成后,使用`osSemaphoreRelease()`函数释放信号量。

这样,信号量就可以在FreeRTOS + LWIP中成功使用了。
举报

更多回帖

发帖
×
20
完善资料,
赚取积分