stm32半自动化控制sg90舵机代码(c语言版)

void rotateSG90(int angle,TIM_HandleTypeDef htim)
{
	//输出丿丿20ms的PWM信号,然后关闭这个PWM
	htim.Init.Prescaler = 40-1;
  htim.Init.CounterMode = TIM_COUNTERMODE_UP;
  htim.Init.Period = 4000-1;
	switch(angle)
	{
		case 0:
			__HAL_TIM_SET_COMPARE(&htim2,TIM_CHANNEL_1,100);
			HAL_Delay(20);	
			break;
		case 45:
			__HAL_TIM_SET_COMPARE(&htim2,TIM_CHANNEL_1,200);
			HAL_Delay(20);
			break;
		
		case 90:
			__HAL_TIM_SET_COMPARE(&htim2,TIM_CHANNEL_1,300);
			HAL_Delay(20);	
			break;
		case 135:
			__HAL_TIM_SET_COMPARE(&htim2,TIM_CHANNEL_1,400);
			HAL_Delay(20);	
		break;
		case 180:
			__HAL_TIM_SET_COMPARE(&htim2,TIM_CHANNEL_1,500);
			HAL_Delay(20);	
			break;
	}

}
说明:时钟频率需要设置为8MHZ,另外需要先随便设置一个TIM定时器,推荐timer2

你可能感兴趣的:(stm32,c语言,嵌入式硬件,ros2,机器人)