[uCOS/RTOS] 如何在中断中使用pvPortMalloc函数

[复制链接]
3844|1
 楼主| shipeng1989 发表于 2023-12-7 20:26 | 显示全部楼层 |阅读模式
本帖最后由 shipeng1989 于 2023-12-18 15:29 编辑

为了实现串口接收不定长数据到消息队列,前段时间我在网上找到一个串口数据接收逻辑感觉很完美,于是直接拿来使用。他是这样做的:
1.定义一个消息队列队列单元设置4个字节用来保存指针数据,队列长度随意;

2.当接收到串口数据后先申请动态内存;

3.再将接收到的数据copy到申请的内存中;

4.将申请到的内存地址放入队列中;
5.在任务中从容的处理消息队列。

以下是源代码:

  1. #define USE_FREERTOS_MALLOC        0
  2. #if USE_FREERTOS_MALLOC
  3. #define my_malloc(x)        pvPortMalloc(x)
  4. #define my_free(x)                vPortFree(x)
  5. #else
  6. #define my_malloc(x)        malloc(x)
  7. #define my_free(x)                free(x)
  8. #endif

  9. typedef struct
  10. {
  11.         uint8_t        length;
  12.         uint8_t        DatArea[];
  13. }UsartReceiveData_t;

  14. void USART1_IRQHandler(void)
  15. {
  16.         static uint8_t rx_index = 0;
  17.         if(USART_ReadIntFlag(USART1, USART_INT_IDLE))
  18.         {
  19.                 USART1->DATA;//CLEAR USART IDLE FLAG
  20.                 BaseType_t xHigherPriorityTaskWoken = pdFALSE;
  21.                 uint8_t rx_len = UPDATE==StatusSystemEnum ? rx_index : sizeof(DMA_USART1_RxBuf) - DMA1_Channel5->CHNDATA_B.NDATA;
  22.                 UsartReceiveData_t *RxStruct = (UsartReceiveData_t*)my_malloc(rx_len+1);
  23.                 if (NULL!=RxStruct)
  24.                 {
  25.                         memcpy(RxStruct->DatArea,DMA_USART1_RxBuf,rx_len);RxStruct->length = rx_len;
  26.                         if (NULL==U1RxQueue || pdPASS!=xQueueSendFromISR(U1RxQueue, (uint8_t*)&RxStruct, &xHigherPriorityTaskWoken))printf("U1RxQueue sending failed!");
  27.                         else portYIELD_FROM_ISR(xHigherPriorityTaskWoken);//Request a context switch (Start task switching after interrupt)
  28.                 }
  29.                 else printf("USART1 RxStruct my_malloc failed!");

  30.                 DMA_Disable(DMA1_Channel5);
  31.                 DMA_ConfigDataNumber(DMA1_Channel5, sizeof(DMA_USART1_RxBuf));
  32.                 DMA_Enable(DMA1_Channel5);

  33.                 rx_index = 0;
  34.         }
  35.         else if(USART_ReadIntFlag(USART1, USART_INT_RXBNE))//Only for DWIN UPDATE,See "main.c" on line:501
  36.         {
  37.                 uint8_t buf8 = USART1->DATA;
  38.                 DMA_USART1_RxBuf[rx_index++] = buf8;
  39.                 if ((UART_DWIN->STS & USART_FLAG_TXBE) != (uint16_t)RESET)UART_DWIN->DATA_B.DATA = buf8;
  40.         }
  41. }
当用malloc函数时一切安好,后面听小人言pvPortMalloc函数更安全于是就听信了谗言结果我就是那个宋高宗,软件分分钟就崩溃了。后经百般检索了解到pvPortMalloc函数不能在中断中调用,不知各位高人有无**之法?


pattywu 发表于 2023-12-8 11:45 | 显示全部楼层
所谓的安全,是在中断外的安全,不是中断中。
您需要登录后才可以回帖 登录 | 注册

本版积分规则

31

主题

141

帖子

1

粉丝
快速回复 在线客服 返回列表 返回顶部