本帖最后由 zhaosr19 于 2011-9-5 19:53 编辑
使用内部晶振16MHz,由于硬件上设计的问题
现在可以使用21脚,INT中断,读取Timer1的值算频率,但算出的来的很不准,输入27Hz的占空比13%方波,测出的频率什么值都有,太怪了
测量原理是:Timer1一直在跑,int脚(21脚)在方波下降沿读取timer1的值,第一次不计算频率,第二次中断后开始,每次减掉前面一次的值,算频率g_fFreq
请问:1)这种方法测量频率有问题?我的频率范围在0-200Hz
2)帮忙看看代码有问题?
#include <htc.h>
#ifndef _XTAL_FREQ
#define _XTAL_FREQ 16000000/* 内部晶振16MHz */
#endif
#define _XTAL_FREQ_1_16 1000000/* 1/16 * _XTAL_FREQ */
#define _TIMER1_FREQ 500000.0 /* 1/4 Focs,8分频 */
volatile unsigned short long g_uslT1 =0;
volatile unsigned short long g_uslT2 =0,g_uslT3=0;
unsigned char ucFlagTemp1 =0, ucFlagTemp2 =0, g_fFreq = 0;
void Init(void)
{
TRISB = 0b00100001;
ANSELB = 0x00;
WPUB = 0b00100001;/* 1 pull-up enabled */
/* portb电平变化中断
IOCB = 0b00100001;/* 1 = Interrupt-on-change enabled */
/* timer1 */
T1CON = 0b00110101;/* 1/4 *Fosc ,预分频8*/
T1GCON = 0x00;
/* interrupt */
INTCON = 0b10100000; /* T0IE =1,T0IF = 0 */
//RBIE = 1;
INTE = 1;
INTF = 0;
T0IE = 0;
__delay_us(1000);/*1000us*/
}
void interrupt my_isr(void)
{
if (INTF == 1 && INTE == 1)
{
ucFlagTemp1 =TMR1H;
ucFlagTemp2 =TMR1L;
INTF = 0;
if (0 != g_uslT1)
{
g_uslT2 = ucFlagTemp1*256+ucFlagTemp2;
//g_uslT2 = TMR1H;
//g_uslT2 = g_uslT2<<8+TMR1L;
if (g_uslT2 > g_uslT1)
{
g_uslT3 = g_uslT2 - g_uslT1;
}
else/* 溢出处理 */
{
g_uslT3 = g_uslT2 +65535- g_uslT1;
}
}
g_uslT1 = ucFlagTemp1*256+ucFlagTemp2;
//g_uslT1 = TMR1H;
//g_uslT1 = g_uslT1<<8 + TMR1L;
}
}
void main(void)
{
unsigned char ucAdValInit = 0;
volatile unsigned char ucAdVal = 0;
volatile unsigned short long uslT1 =0;
volatile unsigned short long uslT2 =0;
volatile float fFreq = 0;
unsigned char ucAngle = 0;
unsigned char ucTemp = 0;
unsigned char i = 0 ,j = 0;
//ubFlagBit.ucFlag = 0b11000000;
Init();
while(1)
{
//Light_LAMP();
/*
ubFlagBit.uOutFlag = 0;
ubFlagBit.bFlag = 0;
ubFlagBit.ucFlagNorOrHigh =0;
*/
ucAngle = 0;
if (0 != g_uslT3)
{
g_fFreq = _TIMER1_FREQ/g_uslT3;/* 计算频率 */
g_uslT3 = 0;
}
}
return;
} |