/* monitor Task */ /* Includes ----------------------------------------------------------------- */ #include "task/user_task.h" /* USER INCLUDE BEGIN */ #include "bsp/pwm.h" /* USER INCLUDE END */ /* Private typedef ---------------------------------------------------------- */ /* Private define ----------------------------------------------------------- */ /* Private macro ------------------------------------------------------------ */ /* Private variables -------------------------------------------------------- */ /* USER STRUCT BEGIN */ static uint8_t servo_direction = 0; // 0: 向90度移动, 1: 向45度移动 /* USER STRUCT END */ /* Private function --------------------------------------------------------- */ /* Exported functions ------------------------------------------------------- */ void Task_monitor(void *argument) { (void)argument; /* 未使用argument,消除警告 */ /* 计算任务运行到指定频率需要等待的tick数 */ const uint32_t delay_tick = osKernelGetTickFreq() / MONITOR_FREQ; osDelay(MONITOR_INIT_DELAY); /* 延时一段时间再开启任务 */ uint32_t tick = osKernelGetTickCount(); /* 控制任务运行频率的计时 */ /* USER CODE INIT BEGIN */ // 初始化舵机PWM // 舵机频率为50Hz BSP_PWM_SetFreq(BSP_PWM_TIM1_CH2, 50.0f); BSP_PWM_Start(BSP_PWM_TIM1_CH2); // 设置初始位置为45度 // 45度对应约1.25ms脉宽,占空比 = 1.25/20 = 0.0625 BSP_PWM_SetComp(BSP_PWM_TIM1_CH2, 0.0625f); /* USER CODE INIT END */ while (1) { tick += delay_tick; /* 计算下一个唤醒时刻 */ /* USER CODE BEGIN */ // 舵机角度控制 // 45度: 1.25ms脉宽, 占空比 = 1.25/20 = 0.0625 // 90度: 1.5ms脉宽, 占空比 = 1.5/20 = 0.075 if (servo_direction == 0) { // 移动到90度 BSP_PWM_SetComp(BSP_PWM_TIM1_CH2, 0.075f); servo_direction = 1; } else { // 移动到45度 BSP_PWM_SetComp(BSP_PWM_TIM1_CH2, 0.0625f); servo_direction = 0; } /* USER CODE END */ osDelayUntil(tick); /* 运行结束,等待下一次唤醒 */ } }