因此,我正在尝试使用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
}
}
最佳答案
这取决于您的时钟设置。您需要首先配置时钟,因为只有在重设2.097MHz之后,许多L1都将具有默认时钟,并且设置的周期为0.152598951 sek,伺服接收的脉冲宽度为0.07至0.15sek,约为75倍长(我认为PCS应该为15,以归档16 * 20000个时钟周期。根据您的设置,计时器时钟应大于100MHz,这对于L1是不可能的
计时器计数滴答声,滴答声需要多长时间取决于时钟速度和计时器时钟分频器。
要归档20ms,您需要将PSC保留为零值且ARR = 41939
当然1ms是2097,而2ms是4194
您需要计算正确的值
配置PLL的最简单方法是使用WYSIWYG CubeMX时钟编辑器
关于c - 使用STM32L TIM PWM控制伺服电机,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43731766/