一、Encoder Interface 编码器接口
1、编码器接口可接收增量(正交)编码器的信号,根据编码器旋转产生的正交信号脉冲,自动控制CNT自增或自减,从而指示编码器的位置、旋转方向和旋转速度
2、每个高级定时器和通用定时器都拥有1个编码器接口
3、两个输入引脚借用了输入捕获的通道1和通道2
4、正交编码器
5、编码器接口基本结构
6、实例
(1)TI1、TI2均不反相
(2)TI1反相,TI2不反相
反相的意思是在边沿检测极性选择的时候进行下降沿
a.在输入捕获模式下,需要选择上升沿有效还是下降沿有效
b.在编码器接口模式下,就不在是边沿的极性选择了,而是高低电平的极性选择
上升沿:信号直通,高低电平极性不反转
下降沿:信号通过非门,高低电平极性反转
二、编码器接口测速
1、按照以下接线方式连接,并将STLINK插到电脑上
2、编码器函数驱动模块
(1)编码器库函数的功能
(2)Encoder.c
#include "stm32f10x.h" // Device header
void Encoder_Init(void)
{
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3,ENABLE); //开启时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);
GPIO_InitTypeDef GPIO_InitStructure; //配置GPIO
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;
TIM_ICInitStructure.TIM_ICFilter=0xF;
TIM_ICInit(TIM3,&TIM_ICInitStructure);
TIM_ICInitStructure.TIM_Channel=TIM_Channel_2; //通道2
TIM_ICInitStructure.TIM_ICFilter=0xF;
TIM_ICInit(TIM3,&TIM_ICInitStructure);
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;//返回CNT的值
}
(3)Encoder.h
#ifndef __ENCODER_H
#define __ENCODER_H
void Encoder_Init(void);
int16_t Encoder_Get(void);
#endif
3、编写main.c代码
#include "stm32f10x.h" // Device header
#include "Delay.h"
#include "OLED.h"
#include "Timer.h"
#include "Encoder.h"
int16_t Speed;
int main(void)
{
OLED_Init();
Encoder_Init();
Timer_Init();
OLED_ShowString(1,1,"Speed:");
while(1)
{
OLED_ShowSignedNum(1,7,Speed,5);
// Delay_ms(1000);
}
}
void TIM2_IRQHandler(void)
{
if(TIM_GetITStatus(TIM2,TIM_IT_Update) == SET)
{
Speed =Encoder_Get();
TIM_ClearITPendingBit(TIM2,TIM_IT_Update);
}
}
4、实现效果
编码器接口测速