07:【江科大stm32】:编码器通过定时器测速

编码器通过定时器测速

编码器的转动方向不同,则输出波形的相位也不同。如下图所示:
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述编码器标准库的编程接口:

在这里插入图片描述
①Encoder.c文件的代码如下:

#include "stm32f10x.h"                  // Device header

//使用PA6(TIM3_CH1)和PA7(TIM3_CH2)进行编码器的输入

void Encoder_Init(void)
{
	//1. 使能TIM3的时钟
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3,ENABLE);
	
	//2. 选择内部时钟源
	//TIM_InternalClockConfig(TIM3);//由于时钟计数来源编码器的脉冲,所以不用内部时钟源
	
	
	//3.配置时基单元
	TIM_TimeBaseInitTypeDef TIM_TimeInitStruct;
	TIM_TimeInitStruct.TIM_ClockDivision = TIM_CKD_DIV1;//时钟源滤波分频
//TIM_TimeInitStruct.TIM_CounterMode = TIM_CounterMode_Up;//向上计数
	TIM_TimeInitStruct.TIM_Period = 65536 - 1;//计数器
	TIM_TimeInitStruct.TIM_Prescaler = 1 - 1;//预分频器,1MHz,即1us计数1次
	TIM_TimeInitStruct.TIM_RepetitionCounter = 0;//重复计数器
	TIM_TimeBaseInit(TIM3,&TIM_TimeInitStruct);
	
	//4.对输入捕获引脚进行初始化
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);
	GPIO_InitTypeDef GPIOInitStruct;
	GPIOInitStruct.GPIO_Mode = GPIO_Mode_IPU;//上拉输入
	GPIOInitStruct.GPIO_Pin = GPIO_Pin_6 | GPIO_Pin_7;
	GPIO_Init(GPIOA,&GPIOInitStruct);
	
	//5.对输入捕获单元进行初始化
	TIM_ICInitTypeDef TIM_ICInitStruct;
	TIM_ICStructInit(&TIM_ICInitStruct);//个捕获通道赋默认值
	TIM_ICInitStruct.TIM_Channel = TIM_Channel_1;//选择通道CH1,它不像输出比较每个通道都有一个函数TIM_OC?Init()
	TIM_ICInitStruct.TIM_ICFilter = 0xF;//对捕获的信号进行滤波
	TIM_ICInitStruct.TIM_ICPolarity = TIM_ICPolarity_Rising;//电平不反向
//TIM_ICInitStruct.TIM_ICPrescaler = TIM_ICPSC_DIV1;//对捕获信号进行1分频
//TIM_ICInitStruct.TIM_ICSelection = TIM_ICSelection_DirectTI;//选择直接连接
	TIM_ICInit(TIM3, &TIM_ICInitStruct);
	
	TIM_ICInitStruct.TIM_Channel = TIM_Channel_2;//选择通道CH2,它不像输出比较每个通道都有一个函数TIM_OC?Init()
	TIM_ICInitStruct.TIM_ICFilter = 0xF;//对捕获的信号进行滤波
	TIM_ICInitStruct.TIM_ICPolarity = TIM_ICPolarity_Rising;//电平不反向
	TIM_ICInit(TIM3, &TIM_ICInitStruct);
	
	//6.配置编码器接口
	TIM_EncoderInterfaceConfig(TIM3,TIM_EncoderMode_TI12,TIM_ICPolarity_Rising,TIM_ICPolarity_Rising);
	
	TIM_Cmd(TIM3,ENABLE);
}

int16_t Encoder_Get(void)
{
	return TIM_GetCounter(TIM3);//获取计数器的值
}

int16_t Encoder_GetSpeed(void)
{
	int16_t temp;
	temp = TIM_GetCounter(TIM3);
	TIM_SetCounter(TIM3,0);//给计数器清零
	return temp;
}

②主程序文件代码如下:

/*
	通过外部中断使用旋转编码器计次
*/

#include "stm32f10x.h"                 
#include "OLED.h"
#include "Timer.h"
#include "Encoder.h"

int16_t Speed;

int main(void)
{
	OLED_Init();
	OLED_Clear();
	Timer_Init();
	Encoder_Init();
	OLED_ShowString(1,1,"Speed:");
	while(1)
	{
		OLED_ShowSignedNum(1,7,Speed,5);
	}
}

void TIM2_IRQHandler(void)//定时器中断设置的是每隔1s执行一次,
{
	if(TIM_GetITStatus(TIM2,TIM_IT_Update) == SET)//判断中断标志位
	{
		TIM_ClearITPendingBit(TIM2,TIM_IT_Update);//清除中断标志位
		Speed = Encoder_GetSpeed();
	}
}

通过每隔1s就获取定时器TIM3计数器里面的值等于速度。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值