基于stm32f103编码器测量电机转速库函数版代码
时间: 2023-08-21 11:03:45 浏览: 116
下面是一个基于STM32F103的编码器测量电机转速库函数版代码:
```c
#include "stm32f10x.h"
volatile uint16_t EncoderValue = 0;
volatile uint16_t EncoderLastValue = 0;
volatile uint16_t EncoderPulseCount = 0;
volatile uint16_t EncoderRPM = 0;
void Encoder_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_ICInitTypeDef TIM_ICInitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_Init(GPIOA, &GPIO_InitStructure);
TIM_TimeBaseStructure.TIM_Period = 65535;
TIM_TimeBaseStructure.TIM_Prescaler = 0;
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);
TIM_ICInitStructure.TIM_Channel = TIM_Channel_1;
TIM_ICInitStructure.TIM_ICPolarity = TIM_ICPolarity_Rising;
TIM_ICInitStructure.TIM_ICSelection = TIM_ICSelection_DirectTI;
TIM_ICInitStructure.TIM_ICPrescaler = TIM_ICPSC_DIV1;
TIM_ICInitStructure.TIM_ICFilter = 0x0F;
TIM_ICInit(TIM2, &TIM_ICInitStructure);
TIM_ICInitStructure.TIM_Channel = TIM_Channel_2;
TIM_ICInitStructure.TIM_ICPolarity = TIM_ICPolarity_Falling;
TIM_ICInitStructure.TIM_ICSelection = TIM_ICSelection_IndirectTI;
TIM_ICInitStructure.TIM_ICPrescaler = TIM_ICPSC_DIV1;
TIM_ICInitStructure.TIM_ICFilter = 0x0F;
TIM_ICInit(TIM2, &TIM_ICInitStructure);
TIM_Cmd(TIM2, ENABLE);
TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE);
TIM_ITConfig(TIM2, TIM_IT_CC1, ENABLE);
TIM_ITConfig(TIM2, TIM_IT_CC2, ENABLE);
NVIC_EnableIRQ(TIM2_IRQn);
}
void TIM2_IRQHandler(void)
{
if(TIM_GetITStatus(TIM2, TIM_IT_Update) != RESET)
{
TIM_ClearITPendingBit(TIM2, TIM_IT_Update);
}
if(TIM_GetITStatus(TIM2, TIM_IT_CC1) != RESET)
{
EncoderValue = TIM_GetCapture1(TIM2);
EncoderPulseCount = EncoderValue - EncoderLastValue;
EncoderLastValue = EncoderValue;
TIM_ClearITPendingBit(TIM2, TIM_IT_CC1);
}
if(TIM_GetITStatus(TIM2, TIM_IT_CC2) != RESET)
{
EncoderValue = TIM_GetCapture2(TIM2);
EncoderPulseCount = EncoderLastValue - EncoderValue;
EncoderLastValue = EncoderValue;
TIM_ClearITPendingBit(TIM2, TIM_IT_CC2);
}
}
void Encoder_CalculateRPM(void)
{
EncoderRPM = (EncoderPulseCount * 60) / 360;
EncoderPulseCount = 0;
}
int main(void)
{
Encoder_Init();
while(1)
{
Encoder_CalculateRPM();
// Do something with EncoderRPM
}
}
```
这段代码使用了STM32的定时器和输入捕捉功能来测量编码器的脉冲信号,并计算电机的转速。您需要根据您的具体硬件和应用程序进行适当的修改。
阅读全文