Stm32对光电编码器M法测速的代码
时间: 2024-05-11 19:18:50 浏览: 80
下面是一份基于STM32的光电编码器M法测速的代码,供参考:
```
#include "stm32f10x.h"
#define PI 3.1415926535f
#define ENCODER_PPR 600.0f // 光电编码器的脉冲数(每转)
volatile uint16_t encoder_count = 0;
volatile uint16_t last_encoder_count = 0;
volatile uint16_t encoder_speed = 0;
void TIM3_IRQHandler(void)
{
if (TIM_GetITStatus(TIM3, TIM_IT_Update) != RESET)
{
encoder_count = TIM_GetCounter(TIM2);
TIM_SetCounter(TIM2, 0);
if (encoder_count > last_encoder_count)
{
encoder_speed = (encoder_count - last_encoder_count) * 7200 / ENCODER_PPR; // 计算转速(单位:rpm)
}
else
{
encoder_speed = (last_encoder_count - encoder_count) * 7200 / ENCODER_PPR;
}
last_encoder_count = encoder_count;
TIM_ClearITPendingBit(TIM3, TIM_IT_Update);
}
}
int main(void)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
NVIC_InitTypeDef NVIC_InitStructure;
// 初始化TIM2作为计数器
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
TIM_TimeBaseStructure.TIM_Period = 0xFFFF;
TIM_TimeBaseStructure.TIM_Prescaler = 0;
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);
TIM_Cmd(TIM2, ENABLE);
// 初始化TIM3作为计算转速的定时器
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
TIM_TimeBaseStructure.TIM_Period = 1000; // 定时器周期为1ms
TIM_TimeBaseStructure.TIM_Prescaler = 7200 - 1; // 定时器时钟源为72MHz,预分频7200,计数时钟为10kHz
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);
TIM_ITConfig(TIM3, TIM_IT_Update, ENABLE);
TIM_Cmd(TIM3, ENABLE);
// 配置中断优先级
NVIC_InitStructure.NVIC_IRQChannel = TIM3_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
while (1)
{
// do something
}
}
```
该代码中使用了STM32的TIM2和TIM3定时器,其中TIM2作为光电编码器的计数器,每接收到一个脉冲就加1,而TIM3作为计算转速的定时器,每隔1ms就计算一次转速并保存到全局变量encoder_speed中。在TIM3的中断服务函数中,通过计算TIM2的计数值来得到编码器转动的脉冲数,从而计算出转速。需要注意的是,在计算转速时需要将脉冲数转换为转速,这里使用了PPR和7200来进行转换。
阅读全文