【C51】基於51單片機的簡易頻率計(附代碼、無需外設、小白簡單易上手)

基於51單片機的簡易頻率計(無需外設、小白簡單易上手)


  代碼較爲簡單,大概思路是通過定時器單位時間內外部中斷上升沿觸發的次數來計算實際頻率。

/基於51單片機的簡易頻率計

#include<reg51.h>
#include<intrins.h>
#include <math.h>
#define uchar unsigned char
#define uint unsigned int

sbit P11=P1^1;
uchar code table[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90};    //七段顯示0到9
/////////////////////// 0    1   2    3   4     5    6    7    8   9 	     //無小數點
uchar code LEDcode01[]={0x40,0x79,0x24,0x30,0x19,0x12,0x02,0x78,0x00,0x10}; 	 //七段顯示0到9
///////////////////////////// 0    1   2    3   4     5    6    7    8   9 	    //有小數點
uchar date1=0,date2=0,date3=0,date4=0;
uint count=0,time_count=0,sum=0;

  int H,L;
void aaa(void);
 void delay(n);
 void initial();
 void delayms(uint t)
{
	uint a;
	for(;t>0;t--)
		for(a=0;a<200;a++);		  //延時函數
}
  

  

void initial()			   //定時器初始化
{
 TMOD |=0x12;					  //使用模式2,16位定時器
 TH0=0x06;				//	 0.25ms
 TL0=0x06;
 EA=1;            //總中斷打開
 ET0=1;           //定時器中斷打開
 TR0=1;           //定時器開關打開  
 EX0 = 1;
 IT0 = 1;

	H=0Xfe;
	L=0X14;
//	TMOD |= 0x01;	  //使用模式1,16位定時器,使用"|"符號可以在使用多個定時器時不受影響		     
	TH1=0xfe;			//重新賦值,方式1是16位計數器,不能硬件重裝初始值
    TL1=0x14;			    //定時0.01ms
//	EA=1;            //總中斷打開
	ET1=1;           //定時器中斷打開
	TR1=1;           //定時器開關打開
	EX1=1;
	IT1=0;
//	PX0=1;
//	PX1=1;
}
  void input() interrupt 0
{
	  count++;

	}


 void timer0() interrupt 1
{
	time_count++;
	if(time_count==4000)
	{
		sum=count;
		time_count=0;
		count=0;
	}
}
 void Timer0_isr(void) interrupt 3 using 1
{
	TH1=H;		  //重新賦值,方式1是16位計數器,不能硬件重裝初始值
	TL1=L;
	P11=!P11;	 
}	 
  void Key_INT1(void) interrupt 2 using 2
{
	 delayms(800);
	 H=H;
	 L=L+10;
/*	 if(L<256)
	 {    
  		H=H;
		L=L+10;
	}
	else if(L>256)
	{
		H=0xff;
		L=L-256+10;
	}
	else if(H=0xff  && L>0x14)
	  {
	  	H=0xfe;
		L=0x14;
	  }	*/


}

 

void aaa(void)			                  //共陽極數碼管顯示函數,注意小數點使用table1數組
{	
	char qian,shi,ge,bai;
	qian=sum/1000;
	bai=(sum%1000)/100;
	shi=(sum%100)/10;
	ge=(sum%10);		   //取百分位
	P2=0x17;			                  //片選
	P0=table[ge];
	delay(1);			  
	P0=0xff;			                 //段選

	P2=0x1b;
	P0=table[shi];
	delay(1);
	P0=0xff;

	P2=0x1d;
	P0=table[bai];
	delay(1);
	P0=0xff;

	  P2=0x1e;
	P0=table[qian];
	delay(1);
	P0=0xff;
		
}
 void delay(int n)			                  //延時函數,大概1ms左右
{
int m,d;
for(m=92;m>0;m--)
for(d=n;d>0;d--);
}	
  main()
{	 
initial()	;
  	while(1)
	{
	   
	   aaa()	;
	
	}

  }
//阿汪先生的博客.ws
發佈了21 篇原創文章 · 獲贊 76 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章