STM32CubeMX + freeRTOS线程操作(二)

接上 线程操作(一)

上一个例程中使用的是1个按键来进行线程的恢复和挂起,现在改用另一种形式来进行。 同样还是上面的那两个任务LED1_Thread、LED2_Thread;只不过在任务中使用定时的方式来进行线程挂起与切换。

在这里使用了一个freeRTOS中的一个API函数uint32_t osKernelSysTick(void)用来获得内核Systick定时器的值。

/**
* @brief  Get the value of the Kernel SysTick timer
* @param  None
* @retval None
* @note   MUST REMAIN UNCHANGED: \b osKernelSysTick shall be consistent in every CMSIS-RTOS.
*/
uint32_t osKernelSysTick(void)
{
  if (inHandlerMode()) {
    return xTaskGetTickCountFromISR();
  }
  else {
    return xTaskGetTickCount();
  }
}

1、LED1_Thread中代码的实现

在该线程中,首先获得内核Systick定时器的值再加上5000ms,计数值大于等于内核Systick定时器时LED1开始闪烁,否则将自身挂起。等待线程2将其恢复。

* USER CODE BEGIN Header_LED_Thread1 */
/**
  * @brief  Function implementing the LED1 thread.
  * @param  argument: Not used
  * @retval None
  */
/* USER CODE END Header_LED_Thread1 */
void LED_Thread1(void const * argument)
{
  /* USER CODE BEGIN 5 */
  /* Infinite loop */
	static uint32_t timerCount = 0;
  for(;;)
  {
		timerCount = osKernelSysTick()+5000;
		/* Toggle LED1 every 200 ms for 5 s */
		while(timerCount >= osKernelSysTick()) {
			HAL_GPIO_TogglePin(GPIOF,GPIO_PIN_9);
			osDelay(200);
		}
		  /* Turn off LED */
		HAL_GPIO_WritePin(GPIOF,GPIO_PIN_9,GPIO_PIN_SET);
		/* Suspend Thread 1 */
		osThreadSuspend(NULL);
		
		timerCount = osKernelSysTick()+5000;
		 /* Toggle LED every 400 ms for 5 s */
    while (timerCount >= osKernelSysTick()){
		   HAL_GPIO_TogglePin(GPIOF,GPIO_PIN_9);
			 osDelay(400);
		}
		/* Resume Thread 2 */
    osThreadResume(LED2Handle);
	}
  /* USER CODE END 5 */
}

2、LED2_Thread中代码的实现

/* USER CODE BEGIN Header_LED2_Thread */
/**
* @brief Function implementing the LED2 thread.
* @param argument: Not used
* @retval None
*/
/* USER CODE END Header_LED2_Thread */
void LED2_Thread(void const * argument)
{
  /* USER CODE BEGIN LED2_Thread */
  /* Infinite loop */
  for(;;)
  {
    static uint32_t timerCount = 0;
		timerCount = osKernelSysTick()+10000;
		/* Toggle LED1 every 200 ms for 5 s */
		while(timerCount >= osKernelSysTick()) {
			HAL_GPIO_TogglePin(GPIOF,GPIO_PIN_10);
			osDelay(500);
		}
		/* Turn off LED */
		HAL_GPIO_WritePin(GPIOF,GPIO_PIN_10,GPIO_PIN_SET);
		/* Resume Thread 1 */
        osThreadResume(LED1Handle);
		/* Suspend Thread 2 */
		osThreadSuspend(NULL);
  }
  /* USER CODE END LED2_Thread */
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值