stm32f407控制控制180度舵机度舵机
其中主要分为两部分,时钟的初始化和主函数的控制部分。其中主要分为两部分,时钟的初始化和主函数的控制部分。
时钟的初始化:
选用TIM14时钟,F9引脚作为信号控制引脚
void TIM14_PWM_Init(u32 arr,u32 psc)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM14,ENABLE);
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOF, ENABLE);
GPIO_PinAFConfig(GPIOF,GPIO_PinSource9,GPIO_AF_TIM14);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_Init(GPIOF,&GPIO_InitStructure);
TIM_TimeBaseStructure.TIM_Prescaler=psc;
TIM_TimeBaseStructure.TIM_CounterMode=TIM_CounterMode_Up;
TIM_TimeBaseStructure.TIM_Period=arr;
TIM_TimeBaseStructure.TIM_ClockDivision=TIM_CKD_DIV1;
TIM_TimeBaseInit(TIM14,&TIM_TimeBaseStructure);
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OC1Init(TIM14, &TIM_OCInitStructure);
TIM_OC1PreloadConfig(TIM14, TIM_OCPreload_Enable);
TIM_ARRPreloadConfig(TIM14,ENABLE);
TIM_Cmd(TIM14, ENABLE);
}
主函数控制:
使用按键进行控制,时钟频率设置为50HZ,周期20ms,
舵机属性:0.5ms————–0;1.0ms————45;1.5ms————90;2.0ms———–135;2.5ms———–180度。
占空比控制属性:5 / 200 = 0.5ms / 20ms;对应转动0度。5代表pwmval,200为arr
int main(void)
{
u8 key;
u16 pwmval = 0;
KEY_Init();
delay_init(168);
uart_init(115200);
TIM14_PWM_Init(200-1,8400-1); // 50hz,20ms,50 = (168M / (200 * 8400))/2 , t = 20ms = 1 / 50,
pwmval = 5 ;
while(1)
{
key_scan(0);
if(keydown_data==KEY0_DATA)
{
pwmval = 5;
printf(“%d”,pwmval);
}