Question
Controlling servo with tim1 close but it does not work
Posted on April 04, 2014 at 16:00
Hello All,
I'm trying to control a servo. I found code on a site that was in Russian, and google translate did not help me much to understand it. Basically we want a period of 20ms and we want to be high during at least 1ms of that 20ms for start position up to 2ms for end position of the servo. I'm using tim1 and using PA.7. The original example was using a pin that I'm using for something else. My systemclock is ''uint32_t SystemCoreClock = 168000000;''. I dont know why they enable the int, I didnt find the int handler anywhere. Any help would be appreciated, I just discovered how servos work this week and cant believe I didn't use them before. Now I just have to add support for at least one to my project.void initServo(void){
/*
* Servo min(1ms) = 1580
* Servo max(2ms) = 3160
*
*/
TIM_BDTRInitTypeDef bdtr;
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
/* TIM1 clock enable */
RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1, ENABLE);
/* GPIOE clock enable */
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);
/* TIM1 channel 1 pin (PA.7) configuration */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_7;
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_NOPULL;
GPIO_Init(GPIOA, &GPIO_InitStructure);
/* Connect TIM pins to AF2 */
GPIO_PinAFConfig(GPIOA, GPIO_PinSource7, GPIO_AF_TIM1);
TIM_TimeBaseStructInit (&TIM_TimeBaseStructure);
TIM_TimeBaseStructure.TIM_Prescaler = SystemCoreClock/5000000; // pers 6
TIM_TimeBaseStructure.TIM_Period = 31600; // 20ms for servo period
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM1 , &TIM_TimeBaseStructure);
// PWM1 Mode configuration: Channel1
// Edge -aligned; not single pulse mode
TIM_OCStructInit (& TIM_OCInitStructure);
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OC1Init(TIM1 , &TIM_OCInitStructure);
TIM_BDTRStructInit(&bdtr);
bdtr.TIM_AutomaticOutput = TIM_AutomaticOutput_Enable;
TIM_BDTRConfig(TIM1, &bdtr);
// Enable Timer Interrupt and Timer
TIM_ITConfig(TIM1, TIM_IT_Update, ENABLE); //
TIM_Cmd(TIM1 , ENABLE);
TIM_SetCompare1(TIM1, 2370); // 2370 = 1.5ms - for Servo
}