用STM32F101RB8 的PA5采一方波信号,用定时器2作计时,示波器上看波形很好,但采到的方波却差别很大,波峰波谷的值有些不对,我的相关代码如下,请高手指点!
初始化部分:
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_4|GPIO_Pin_5; //输入
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_2MHz; //输入速度2MHz
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU; //输入输出模式GPIO_Mode_IN_FLOATING
// GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING; //输入输出模式GPIO_Mode_IN_FLOATING
GPIO_Init(GPIOA, &GPIO_InitStructure); //A组GPIO初始化
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure; //定时器初始化结构
TIM_TimeBaseStructure.TIM_Period = 0xFFFF; //周期0~FFFF
TIM_TimeBaseStructure.TIM_Prescaler = 35; //时钟36分频,1us一个计数
TIM_TimeBaseStructure.TIM_ClockDivision = 0; //时钟分割
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;//模式
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure); //基本初始化
EXTI部分:
EXTI_InitTypeDef EXTI_InitStructure; //EXTI初始化结构定义
GPIO_EXTILineConfig(GPIO_PortSourceGPIOA, GPIO_PinSource5);//管脚选择
EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;//事件选择
EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling;//触发模式
EXTI_InitStructure.EXTI_Line = EXTI_Line5 ; //线路选择
EXTI_InitStructure.EXTI_LineCmd = ENABLE;//启动中断
EXTI_Init(&EXTI_InitStructure);//初始化
NVIC部分:
NVIC_InitStructure.NVIC_IRQChannel = EXTI9_5_IRQChannel; //通道
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0; //优先级
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; //响应级
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //启动
NVIC_Init(&NVIC_InitStructure); //初始化
中断部分:
if ((EXTI->PR & EXTI_Line5) == EXTI_Line5)
{
...
if (g_i==0)
{
TIM2->CNT=0;
TIM_Cmd(TIM2,ENABLE);
while (GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_5)==0);
g_recvcode[0]=TIM2->CNT;
if (g_recvcode[0]>350)//有用信号
{
TIM2->CNT=0;
for (i=1;i<25;i++)
{
do
{
while(GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_5)==1);
g_recvcode[i]=TIM2->CNT;
}
while(g_recvcode[i]<350);//如果小于350可认为是干扰,重新采样,最大值可达1800
TIM2->CNT=0;
if (g_recvcode[i]>3000)break;
i++;
while(GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_5)==0);
g_recvcode[i]=TIM2->CNT;
TIM2->CNT=0;
if (g_recvcode[i]>3000)break;
}
...
} |