所以我正在尝试使用STM32L1通过PWM控制伺服。下面是完整的代码,不需要库。当我上传并运行此代码时,伺服器会滴答数次,而不是实际平稳地移动到所需的位置 600(0*)、1100(50*)、1600(100*) 和 2100(150*)。我相信这与预分频值计算有关,而且我不确定以微秒为单位提到 ARR 是否正确,如果不是,我如何将其配置为读取微秒而不是毫秒。有关详细信息,请参阅代码中的注释。
#include <stdio.h>
#include "stm32l1xx.h"
// Keil::Device:Startup
// initialization of GPIOB
void TIM4_Init(){
RCC->AHBRSTR |= RCC_AHBRSTR_GPIOARST; /* Reset GPIOB clock */
RCC->AHBENR |= RCC_AHBENR_GPIOBEN; /* Enable GPIOB clock */
GPIOB->MODER &= ~(0x03 << (2*6)); /* Clear bit 11 & 12 Alternate mode*/
GPIOB->MODER |= 0x02 << (2*6); /* set as Alternate mode*/
GPIOB->OSPEEDR &= ~(0x03<< (2*6)); /* 40 MHz speed */
GPIOB->OSPEEDR |= 0x03<< (2*6); /* 40 MHz speed */
GPIOB->PUPDR &= ~(1<<6); /* NO PULL-UP PULL-DOWN */
GPIOB->OTYPER &= ~(1<<6); /* PUSH-PULL */
GPIOB->AFR[0] |= 0x2 << (4*6); /* Pin6 set as alternate function 2 (TIM4) */
RCC->APB1ENR |= RCC_APB1ENR_TIM4EN;
TIM4->PSC = 16; //prescale value, AHB/APB1 Fmax=32MHz / 2
TIM4->ARR = 20000-1; //motor Freq = 50Hz, Period(ARR)= 1/50 = 20000us
// initialization of TIM & PWM
TIM4->CCMR1 |= TIM_CCMR1_OC1M; // 111: PWM mode 2 - In upcounting, channel 1 is inactive
//as long as TIMx_CNT<TIMx_CCR1 else active.
// In downcounting, channel 1 is active as long as
//TIMx_CNT>TIMx_CCR1 else inactive.
TIM4->CCMR1 |= TIM_CCMR1_OC1PE;
TIM4->CR1 |= TIM_CR1_ARPE;
TIM4->CCER |= TIM_CCER_CC1E;
TIM4->EGR |= TIM_EGR_UG;
TIM4->SR &= ~TIM_SR_UIF;
TIM4->DIER |= TIM_DIER_UIE;
TIM4->CR1 |= TIM_CR1_CEN;
}
// set servo to 4 positions in sequence
int main(void){
int i;
int position=600; // initial motor position
TIM4_Init();
while (1){
if ((position >=600)|| (position <=2100))
position = position+500; // motor positions will be 600(0*), 1100(50*), 1600(100*)
//, 2100(150*)
TIM4->CCR1 = position;
for(i=0;i<1000;i++); // short delay
}
}