关于STM32编码器接口模式
//读计数个数
int TIM2_Encoder_Read(void)
{
TIM2_Encoder_Write(0); //计数器清0
delay_ms(10); //检测时间,可调节
return (int)((s16)(TIM2->CNT)); //数据类型转换
//记录边沿变化次数(几个栅格被记录4次)
}
这是图片
#include "TIME2.h"
void TIM2_Config(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
NVIC_InitTypeDef NVIC_InitStructure;
// TIM_ICInitTypeDef TIM2_ICInitStructure;
/* 设置TIM3CLK 为 72MHZ */
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
/* GPIOA and GPIOB clock enable */
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA , ENABLE);
//中断分组初始化
NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn; //TIM4中断
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 2; //先占优先级2级
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 2; //从优先级0级
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //IRQ通道被使能
NVIC_Init(&NVIC_InitStructure); //根据NVIC_InitStruct中指定的参数初始化外设NVIC寄存器
/*GPIOA Configuration: TIM2 channel 1 and 2 as alternate function push-pull */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING; // 浮空输入模式
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
//初始化定时器2 TIM2
TIM_TimeBaseStructure.TIM_Period = 10000; //设定计数器自动重装值
TIM_TimeBaseStructure.TIM_Prescaler = 0x0; //预分频器
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_div1; //设置时钟分割:TDTS = Tck_tim
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; //TIM向上计数模式
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure); //根据TIM_TimeBaseInitStruct中指定的参数初始化TIMx的时间基数单位
//初始化TIM4输入捕获参数
// TIM2_ICInitStructure.TIM_Channel = TIM_Channel_1; //CC1S=01 选择输入端 IC1映射到TI1上
// TIM2_ICInitStructure.TIM_ICPolarity = TIM_ICPolarity_Rising; //上升沿捕获
// TIM2_ICInitStructure.TIM_ICSelection = TIM_ICSelection_DirectTI; //映射到TI1上
// TIM2_ICInitStructure.TIM_ICPrescaler = TIM_ICPSC_div1; //配置输入分频,不分频
// TIM2_ICInitStructure.TIM_ICFilter = 6;//IC1F=0000 配置输入滤波器 不滤波
// TIM_ICInit(TIM2, &TIM2_ICInitStructure);
//
TIM_EncoderInterfaceConfig(TIM2,TIM_EncoderMode_TI12,TIM_ICPolarity_Rising, TIM_ICPolarity_Rising);//编码器模式,中断里计算圈数
TIM_ClearFlag(TIM2, TIM_FLAG_Update);
TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE);
TIM_SetCounter(TIM2, 0);
TIM_Cmd(TIM2, ENABLE);
}
*********************************/
void TIM2_IRQHandler(void) //TIM2中断
{
if (TIM_GetITStatus(TIM2, TIM_IT_Update) != RESET) //检查指定的TIM中断发生与否:TIM 中断源
{
if((TIM2 -> CNT) == 10000)
Zhouqi2--;
else if((TIM2 -> CNT) == 0)
Zhouqi2 ++;
TIM_ClearITPendingBit(TIM2, TIM_IT_Update ); //清除TIMx的中断待处理位:TIM 中断源
}
}
最小值减一为最大值。0 减一后 为 65535,不过65535的二进制形式如果理解为负数,因为负数是补码表示的,-1的补码二进制和65535的二进制是一样的,都是 0xFFFF
是不是这个补码存在CNT计数器里面呢?然后发生下溢,CNT计数器更新为ARR的重载值?然后继续向下计数?