51单片机定时器2捕获模式测脉冲频率

来源:互联网 发布:淘宝店铺怎么提升流量 编辑:程序博客网 时间:2024/05/21 09:51

常规方法测量脉冲的频率,利用51单片机的两个定时器来测量,一个定时器来定时,一个定时器作为计数方式;能不能有一个更好的方法,不使用这么多硬件,只使用一个定时器就可以满足需求? 当然可以的,定时器2有输入捕获功能,P1.1接外部脉冲,当来一个脉冲,定时2就进入中断服务程序中断一次,同时也有定时功能。下面是主要的程序:

#include<reg52.h>
#define uint unsigned int
#define uchar unsigned char
#define ulong unsigned long 
uint timer2_count;
uint cap_count;
uchar code dispbit[]={0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80}; // 定义位选  从第二个数码开始
uchar code dispcode[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90,0xff,0xbf};//定义段码
uchar dispbuf[8]={0,0,0,0,0,0,10,10}; //显示缓冲
uchar temp[8];
uchar dispcount;
uint x;
bit flag;
sbit L1 = P0^7;
//sbit L2 = P0^1;
sbit W1=P1^2;
sbit W2=P1^3;
sbit W3=P1^4;
sbit W4=P1^5;
sbit W5=P1^6;
sbit W6=P1^7;

void display_wei(uchar dipcount)
{
 switch (dipcount){
 case 0: W1=1;W2=W3=W4=W5=W6=0;
   break;
 case 1: {W2=1;W1=W3=W4=W5=W6=0;}
   break;
 case 2: {W3=1;W2=W1=W4=W5=W6=0;}
   break;
 case 3: {W4=1;W2=W3=W1=W5=W6=0;}
   break;
 case 5: {W5=1;W2=W3=W4=W1=W6=0;}
   break;
 case 6: {W6=1;W2=W3=W4=W5=W1=0;}
   break;
 }
}
void timer2_init()
{
 ET2=1;       // 开定时器2
   T2CON=0X09;  //设置T2为捕获模式,下降沿则产生中断
   TH2=(65535-5000)/256;
   TL2=(65535-5000)%256;

   EA=1;        //打开中断
   TR2=1;       //启动计数器
}

void main()
{
  timer2_init();
  while(1)
  {
   uchar i;
 if(flag==1)
 {
  flag=0;
  x=cap_count;   //频率公式  一秒钟测量的脉冲数
  //x= x*563;
  //x=x/10;
  for(i=0;i<8;i++)
  {
   temp[i]=0;     //数组清零
  }
  i=0;   
  //x=123456;
  while(x/10)
  {
   temp[i]=x%10;
   x=x/10;
   i++;
  }
  temp[i]=x;
  for(i=0;i<6;i++)
  {
   dispbuf[i]=temp[i];   //显示6位频率数(缓存)
  }
  
  cap_count=0;
  TR2=1; 
 }
  }
}

void timer2_interrupt(void) interrupt 5 using 1 //中断服务程序
{
  if(EXF2) //捕获的中断
  {
    //L1=!L1;
 cap_count++;
        EXF2=0;
  }

  if(TF2)
  {
    TH2=(65535-5000)/256;
   TL2=(65535-5000)%256;
 timer2_count++;
 if(timer2_count==400)
 {
  //L2=!L2;
  flag=1;
  timer2_count=0;
  TR2=0;//停止计数
    }
 TF2=0;
 P0=dispcode[dispbuf[dispcount]]; //显示数据
 
 //P1 = ((P1&0x02)|dispbit[dispcount+2]);          //位选
 display_wei(dispcount);
 dispcount++;
 if(dispcount==6)
 {
  dispcount=0;
 }
  }
}

 

原创粉丝点击