新手入门
- 积分
- 6
- 金钱
- 6
- 注册时间
- 2023-6-14
- 在线时间
- 1 小时
|
2金钱
用定时器2定时1S,测量到的脉冲数,和定时0.1S测到的脉冲数一样,代码如下,求救。
//定时器
//编码
#include"stm32f4xx.h"
#include <stdint.h>// Device header
void Encode_1_INIT(void)
{
//开启时钟
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4 ,ENABLE);
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB,ENABLE);
//配置GPIO
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;//输入
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;//上拉
//GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;//推挽输出
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6|GPIO_Pin_7;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
GPIO_PinAFConfig(GPIOB, GPIO_PinSource6, GPIO_AF_TIM4); //映射复用定时器
GPIO_PinAFConfig(GPIOB, GPIO_PinSource7, GPIO_AF_TIM4);
//TIM_InternalClockConfig(TIM3);//选择内部时钟
//时基单元
TIM_TimeBaseInitTypeDef TIM_TimerBaseInitStructure;
TIM_TimerBaseInitStructure.TIM_ClockDivision=TIM_CKD_DIV1;
//TIM_TimerBaseInitStructure.TIM_CounterMode=TIM_CounterMode_Up; //向上计数,此处由编码器接管
TIM_TimerBaseInitStructure.TIM_Period= 65536-1;//ARR
TIM_TimerBaseInitStructure.TIM_Prescaler= 1-1;//PSC 预分频器不分频 ,编码器时钟直接驱动计数器
TIM_TimerBaseInitStructure.TIM_RepetitionCounter=0;//重复计数器,高级
TIM_TimeBaseInit(TIM4,&TIM_TimerBaseInitStructure);
//初始化输入捕获单元
//仅使用滤波器和极性选择
TIM_ICInitTypeDef TIM_ICInitStructure;
TIM_ICStructInit(&TIM_ICInitStructure);
TIM_ICInitStructure.TIM_Channel = TIM_Channel_1; //选择通道1
TIM_ICInitStructure.TIM_ICFilter = 0XF; //滤波器
TIM_ICInitStructure.TIM_ICPolarity = TIM_ICPolarity_Rising; //极性上升沿 ,此处代表高低电平极性不翻转
//TIM_ICInitStructure.TIM_ICPrescaler = TIM_ICPSC_DIV1; //分频器不分
//TIM_ICInitStructure.TIM_ICSelection = TIM_ICSelection_DirectTI; //选择通道 直连
TIM_ICInit(TIM4,&TIM_ICInitStructure);
TIM_ICInitStructure.TIM_Channel = TIM_Channel_2; //选择通道2
TIM_ICInitStructure.TIM_ICFilter = 0XF; //滤波器
TIM_ICInitStructure.TIM_ICPolarity = TIM_ICPolarity_Rising; //极性上升沿 ,此处代表高低电平极性不翻转
TIM_ICInit(TIM4,&TIM_ICInitStructure);
//定时器编码接口配置(定时器,编码器模式 TI1和TI2都计数,通道1和通道2的电平极性)
TIM_EncoderInterfaceConfig(TIM4,TIM_EncoderMode_TI12,TIM_ICPolarity_Rising,TIM_ICPolarity_Rising);//后两个参数与前面重复
TIM_Cmd(TIM4,ENABLE);
}
int16_t Encode_1_Get(void)
{
int16_t Temp;
//获取CNT
Temp = TIM_GetCounter(TIM4);
//CNT清零
TIM_SetCounter(TIM4,0);
return Temp;//TIM_GetCounter(TIMx) 读取TIMx寄存器CNT中的计数值
}
|
|