借助江协科技ppt学习
介绍编码器
黑色为正转,红色为反转。
对应三种模式
配置顺序
配置时钟->GPIO初始化->时基单元配置->输入捕获配置(因为TI1FP1和TI2FP2由输出捕获来的)
代码部分
#include "stm32f10x.h" // Device header
void Encoder_Init(void)
{
//开启时钟
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
/*GPIO初始化*/
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;//将引脚初始化为上拉输入
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6 | GPIO_Pin_7;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
/*时基单元初始化*/
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up; //向上计数
TIM_TimeBaseInitStructure.TIM_Period = 65536 - 1; //ARR的值
TIM_TimeBaseInitStructure.TIM_Prescaler = 1 - 1; //PSC的值
TIM_TimeBaseInitStructure.TIM_RepetitionCounter = 0; //高级定时器才会用到
TIM_TimeBaseInit(TIM3, &TIM_TimeBaseInitStructure);
//输入捕获初始化
TIM_ICInitTypeDef TIM_ICInitStructure;
TIM_ICStructInit(&TIM_ICInitStructure); //执行此函数,给结构体所有成员都赋一个默认值
TIM_ICInitStructure.TIM_Channel = TIM_Channel_1; //定时器通道1
TIM_ICInitStructure.TIM_ICFilter = 0xF; //输入滤波器参数,可以过滤信号抖动
TIM_ICInit(TIM3, &TIM_ICInitStructure); //配置TIM3的输入捕获通道
TIM_ICInitStructure.TIM_Channel = TIM_Channel_2; //选择配置定时器通道2
TIM_ICInitStructure.TIM_ICFilter = 0xF; //输入滤波器参数,可以过滤信号抖动
TIM_ICInit(TIM3, &TIM_ICInitStructure); //将结构体变量交给TIM_ICInit,配置TIM3的输入捕获通道
//编码器接口配置
TIM_EncoderInterfaceConfig(TIM3, TIM_EncoderMode_TI12, TIM_ICPolarity_Rising, TIM_ICPolarity_Rising);
TIM_Cmd(TIM3, ENABLE); //定时器开始运行
}
int16_t Encoder_Get(void)
{
int16_t Temp;
Temp = TIM_GetCounter(TIM3);
TIM_SetCounter(TIM3, 0);
return Temp;
}
//主函数
#include "stm32f10x.h"
#include "Delay.h"
#include "OLED.H"
#include "Timer.h"
#include "encoder.h"
int16_t Speed ;
int main()
{
Timer_Init();
OLED_Init();
Encoder_Init();
OLED_ShowString(1,1,"Speed:");
while(1)
{
OLED_ShowSignedNum(1,7,Speed,5);
// Delay_ms(500);
}
}
void TIM2_IRQHandler(void) //TIM2定时器中断函数 1s刷新speed
{
if(TIM_GetITStatus(TIM2,TIM_IT_Update)== SET) //判断挂起位
{
Speed = Encoder_Get();
TIM_ClearITPendingBit(TIM2,TIM_IT_Update); //清除挂起位
}
}