FreeRTOS-Plus-CLI移植

FreeRTOS+CLI 是一个可扩展的框架,允许应用程序编写器定义和注册自己的命令行输入命令,相当于RTOS的命令解析器,在实际项目中很有用。本文介绍如何移植CLI。
FreeRTOS+ CLI(命令行界面)提供了一种简单,小巧,可扩展且RAM高效的方法,使您的FreeRTOS应用程序能够处理命令行输入。

硬件平台:stm32f407zgt6
软件库:HAL

本文测试工程下载链接:https://download.csdn.net/download/qq_26972441/85351855
包括了Free RTOS源码

一. 需要准备FreeRTOS源码,并且找到以下文件放到一个文件夹下

在这里插入图片描述

二. 将文件夹下的c文件添加到keil目录

在这里插入图片描述

三. 使能串口空闲中断和DMA接收

void bsp_usart_USART2_Init(void)
{
  /* USER CODE END USART2_Init 1 */
  huart2.Instance = USART2;
  huart2.Init.BaudRate = 115200;
  huart2.Init.WordLength = UART_WORDLENGTH_8B;
  huart2.Init.StopBits = UART_STOPBITS_1;
  huart2.Init.Parity = UART_PARITY_NONE;
  huart2.Init.Mode = UART_MODE_TX_RX;
  huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE;
  huart2.Init.OverSampling = UART_OVERSAMPLING_16;
  if (HAL_UART_Init(&huart2) != HAL_OK)
  {
    Error_Handler();
  }
	__HAL_UART_ENABLE_IT(&huart2, UART_IT_IDLE); //使能串口空闲中断
  HAL_UART_Receive_DMA(&huart2, usart2_rx_buffer.data, USART_RX_BUFFER_SIZE); //开启串口DMA接收
}

四. 修改serial.c 的xSerialPortInitMinimal函数调用串口初始化函数

xComPortHandle xSerialPortInitMinimal( unsigned long ulWantedBaud, unsigned portBASE_TYPE uxQueueLength )
{
	xComPortHandle xReturn;
	/* Create the queues used to hold Rx/Tx characters. */
	xRxedChars = xQueueCreate( uxQueueLength, ( unsigned portBASE_TYPE ) sizeof( signed char ) );
	xCharsForTx = xQueueCreate( uxQueueLength + 1, ( unsigned portBASE_TYPE ) sizeof( signed char ) );
	
	/* If the queue/semaphore was created correctly then setup the serial port
	hardware. */
	if( ( xRxedChars != serINVALID_QUEUE ) && ( xCharsForTx != serINVALID_QUEUE ) )
	{
    /* 初始化串口1 */
    bsp_usart_USART2_Init();
	}
	else
	{
		xReturn = ( xComPortHandle ) 0;
	}

	/* This demo file only supports a single port but we have to return
	something to comply with the standard demo header file. */
	return xReturn;
}

五. 修改serial.c 的xSerialPutChar函数为轮询方式

signed portBASE_TYPE xSerialPutChar( xComPortHandle pxPort, signed char cOutChar, TickType_t xBlockTime )
{
signed portBASE_TYPE xReturn;

	if( xQueueSend( xCharsForTx, &cOutChar, xBlockTime ) == pdPASS )
	{
		xReturn = pdPASS;
    uint8_t cChar;
    /* 发送队列中有数据,通过轮询方式发送出去 */
    if(xQueueReceive(xCharsForTx, &cChar, 0) == pdTRUE) {
      if((HAL_UART_GetState(&huart2) & HAL_UART_STATE_BUSY_TX) != HAL_UART_STATE_BUSY_TX) {
        HAL_UART_Transmit(&huart2, &cChar, 1, 1000);
      }
    }
	}
	else
	{
		xReturn = pdFAIL;
	}

	return xReturn;
}

六. FreeRTOSConfig.h 增加宏定义

#define configCOMMAND_INT_MAX_OUTPUT_SIZE        1024

七. 完善串口中断服务函数

void USART2_IRQHandler(void)
{
  BaseType_t pxHigherPriorityTaskWoken = pdFALSE;
  if(__HAL_UART_GET_FLAG(&huart2, UART_FLAG_IDLE) != RESET) { //IDLE中断(说明接收到了一帧数据)
    __HAL_UART_CLEAR_IDLEFLAG(&huart2); //清除IDLE中断标志位
    HAL_UART_DMAStop(&huart2);
    usart2_rx_buffer.finish_flag = 1;
    usart2_rx_buffer.len = USART_RX_BUFFER_SIZE - __HAL_DMA_GET_COUNTER(huart2.hdmarx);//hdma_usart1_rx.Instance->NDTR;
    
    /* usart1 rx data process */ 
    for(uint16_t i = 0; i < usart2_rx_buffer.len; ++i) {
      xQueueSendFromISR(xRxedChars, &usart2_rx_buffer.data[i], &pxHigherPriorityTaskWoken);
    }  
    HAL_UART_Receive_DMA(&huart2, usart2_rx_buffer.data, USART_RX_BUFFER_SIZE);
  }
  HAL_UART_IRQHandler(&huart2);
	portYIELD_FROM_ISR(pxHigherPriorityTaskWoken);
}

八 . 主函数调用如下函数

vRegisterSampleCLICommands();
vUARTCommandConsoleStart( 512, 1 );

九 . 注册测试函数

void vRegisterSampleCLICommands( void )
{
	/* Register all the command line commands defined immediately above. */
	FreeRTOS_CLIRegisterCommand( &xTaskStats );	
	FreeRTOS_CLIRegisterCommand( &xThreeParameterEcho );
	FreeRTOS_CLIRegisterCommand( &xParameterEcho );
	FreeRTOS_CLIRegisterCommand( &xTestEcho );
	#if( configGENERATE_RUN_TIME_STATS == 1 )
	{
		FreeRTOS_CLIRegisterCommand( &xRunTimeStats );
	}
	#endif
	
	#if( configINCLUDE_QUERY_HEAP_COMMAND == 1 )
	{
		FreeRTOS_CLIRegisterCommand( &xQueryHeap );
	}
	#endif

	#if( configINCLUDE_TRACE_RELATED_CLI_COMMANDS == 1 )
	{
		FreeRTOS_CLIRegisterCommand( &xStartStopTrace );
	}
	#endif
}

static const CLI_Command_Definition_t xTestEcho =
{
	"task-test",
	"\r\ntask-test:\r\n Test Function\r\n",
	prvEchoTestCommand, /* The function to run. */
	-1 /* The user can enter any number of commands. */
};

十 .函数指针指向的回调函数

static int test[5] = {1, 2, 3, 4 ,5};
static BaseType_t prvEchoTestCommand( char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString )
{
  const char * const pcHeader = "  Test data (uint: mm)  \r\n****************************************\r\n";

		/* Remove compile time warnings about unused parameters, and check the
		write buffer is not NULL.  NOTE - for simplicity, this example assumes the
		write buffer length is adequate, so does not check for buffer overflows. */
		( void ) pcCommandString;
		( void ) xWriteBufferLen;
		configASSERT( pcWriteBuffer );

    strcpy( pcWriteBuffer, pcHeader );
    pcWriteBuffer += strlen( pcWriteBuffer );
  
    for(uint8_t i = 0; i < 5; ++i) {
      sprintf( pcWriteBuffer, "test[%d] distance: %d\t\t\r\n", i, test[i]);
      pcWriteBuffer += strlen( pcWriteBuffer );
    }

		/* There is no more data to return after this single string, so return
		pdFALSE. */
		return pdFALSE;
}

十一. 创建CLI任务

void vUARTCommandConsoleStart( uint16_t usStackSize, UBaseType_t uxPriority )
{
	/* Create the semaphore used to access the UART Tx. */
	xTxMutex = xSemaphoreCreateMutex();
	configASSERT( xTxMutex );

	/* Create that task that handles the console itself. */
	xTaskCreate( 	prvUARTCommandConsoleTask,	/* The task that implements the command console. */
					"CLI",						/* Text name assigned to the task.  This is just to assist debugging.  The kernel does not use this name itself. */
					usStackSize,				/* The size of the stack allocated to the task. */
					NULL,						/* The parameter is not used, so NULL is passed. */
					uxPriority,					/* The priority allocated to the task. */
					NULL );						/* A handle is not required, so just pass NULL. */
}

十二. CLI任务具体内容及实现过程

static void prvUARTCommandConsoleTask( void *pvParameters )
{
signed char cRxedChar;
uint8_t ucInputIndex = 0;
char *pcOutputString;
static char cInputString[ cmdMAX_INPUT_SIZE ], cLastInputString[ cmdMAX_INPUT_SIZE ];
BaseType_t xReturned;
xComPortHandle xPort;

	( void ) pvParameters;

	/* Obtain the address of the output buffer.  Note there is no mutual
	exclusion on this buffer as it is assumed only one command console interface
	will be used at any one time. */
	pcOutputString = FreeRTOS_CLIGetOutputBuffer();

	/* Initialise the UART. */
	xPort = xSerialPortInitMinimal( configCLI_BAUD_RATE, cmdQUEUE_LENGTH );

	/* Send the welcome message. */
	vSerialPutString( xPort, ( signed char * ) pcWelcomeMessage, ( unsigned short ) strlen( pcWelcomeMessage ) );

	for( ;; )
	{
		/* Wait for the next character.  The while loop is used in case
		INCLUDE_vTaskSuspend is not set to 1 - in which case portMAX_DELAY will
		be a genuine block time rather than an infinite block time. */
		while( xSerialGetChar( xPort, &cRxedChar, portMAX_DELAY ) != pdPASS );

		/* Ensure exclusive access to the UART Tx. */
		if( xSemaphoreTake( xTxMutex, cmdMAX_MUTEX_WAIT ) == pdPASS )
		{
			/* Echo the character back. */
			xSerialPutChar( xPort, cRxedChar, portMAX_DELAY );

			/* Was it the end of the line? */
			if( cRxedChar == '\n' || cRxedChar == '\r' )
			{
				/* Just to space the output from the input. */
				vSerialPutString( xPort, ( signed char * ) pcNewLine, ( unsigned short ) strlen( pcNewLine ) );

				/* See if the command is empty, indicating that the last command
				is to be executed again. */
				if( ucInputIndex == 0 )
				{
					/* Copy the last command back into the input string. */
					strcpy( cInputString, cLastInputString );
				}

				/* Pass the received command to the command interpreter.  The
				command interpreter is called repeatedly until it returns
				pdFALSE	(indicating there is no more output) as it might
				generate more than one string. */
				do
				{
					/* Get the next output string from the command interpreter. */
					xReturned = FreeRTOS_CLIProcessCommand( cInputString, pcOutputString, configCOMMAND_INT_MAX_OUTPUT_SIZE );

					/* Write the generated string to the UART. */
					vSerialPutString( xPort, ( signed char * ) pcOutputString, ( unsigned short ) strlen( pcOutputString ) );

				} while( xReturned != pdFALSE );

				/* All the strings generated by the input command have been
				sent.  Clear the input string ready to receive the next command.
				Remember the command that was just processed first in case it is
				to be processed again. */
				//strcpy( cLastInputString, cInputString ); //该语句在输入字符数超过cmdMAX_INPUT_SIZE时会导致程序进入hardfault
        strncpy(cLastInputString, cInputString, cmdMAX_INPUT_SIZE); //复制指定个数的命令
				ucInputIndex = 0;
				memset( cInputString, 0x00, cmdMAX_INPUT_SIZE );

				vSerialPutString( xPort, ( signed char * ) pcEndOfOutputMessage, ( unsigned short ) strlen( pcEndOfOutputMessage ) );
			}
			else
			{
				if( cRxedChar == '\r' )
				{
					/* Ignore the character. */
				}
				else if( ( cRxedChar == '\b' ) || ( cRxedChar == cmdASCII_DEL ) )
				{
					/* Backspace was pressed.  Erase the last character in the
					string - if any. */
					if( ucInputIndex > 0 )
					{
						ucInputIndex--;
						cInputString[ ucInputIndex ] = '\0';
					}
				}
				else
				{
					/* A character was entered.  Add it to the string entered so
					far.  When a \n is entered the complete	string will be
					passed to the command interpreter. */
					if( ( cRxedChar >= ' ' ) && ( cRxedChar <= '~' ) )
					{
						if( ucInputIndex < cmdMAX_INPUT_SIZE )
						{
							cInputString[ ucInputIndex ] = cRxedChar;
							ucInputIndex++;
						}
					}
				}
			}

			/* Must ensure to give the mutex back. */
			xSemaphoreGive( xTxMutex );
		}
	}
}

在这里插入图片描述
在这里插入图片描述

原理:
1、通过结构体构建回调函数
2、将实体函数通过函数指针注册
3、将CLI命令结构体添加到任务队列
4、通过CLI任务进行命令匹配

十三. 测试效果

1、输入help会将所添加的command列出来。
在这里插入图片描述
2、输入task-stats 会将RTOS所有任务列出来。
在这里插入图片描述
3、输入我们自己创建的command task-test
会将结果返回。

在这里插入图片描述

  • 3
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值