转载自互联网!!!
输入 高低点平即可。
10个脉冲 记一圈, 4位数码管显示
可以更改程序,改成1个脉冲,一圈,或者2个脉冲一圈 等等
- #include <REG52.H>
- #define uchar unsigned char
- #define uint unsigned int
- #define ulong unsigned long
- #define LED_DAT P0
- sbit LED_SEG0 = P2^7;
- sbit LED_SEG1 = P2^6;
- sbit LED_SEG2 = P2^5;
- sbit LED_SEG3 = P2^4;
- #define TIME_CYLC 100 //12M晶振,定时器10ms 中断一次 我们1秒计算一次转速 // 1000ms/10ms = 100
- #define PLUS_PER 10 //码盘的齿数 ,这里假定码盘上有10个齿,即传感器检测到10个脉冲,认为1圈
- #define K 1.65 //校准系数
- unsigned char code table[]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f};
- uchar data Disbuf[4];// 显示缓冲区
- uint Tcounter = 0; //时间计数器
- bit Flag_Fresh = 0; // 刷新标志
- bit Flag_clac = 0; //计算转速标志
- bit Flag_Err = 0; //超量程标志
- void DisplayFresh();//在数码管上显示一个四位数
- void ClacSpeed();//计算转速,并把结果放入数码管缓冲区
- void init_timer();//初始化定时器T0\T1
- void Delay(uint ms);//延时函数
- void it_timer0() interrupt 1 /* interrupt address is 0x000b */
- {
- TF0 = 0; //定时器 T0用于数码管的动态刷新
- TH0 = 0xC0;
- TL0 = 0x00;
- Flag_Fresh = 1;
- Tcounter++;
- if(Tcounter>TIME_CYLC)
- { Flag_clac = 1;//周期到,该重新计算转速了
- }
- }
- void it_timer1() interrupt 3 /* interrupt address is 0x001b */
- {
- TF1 = 0; //定时器T1用于单位时间内收到的脉冲数
- //要速度不是很快,T1永远不会益处
- Flag_Err = 1; //如果速度很高,我们应考虑另外一种测速方法:T测速法
-
- }
- void main(void)
- {
- Disbuf[0] = 0; //开机时,初始化为0000
- Disbuf[1] = 0;
- Disbuf[2] = 0;
- Disbuf[3] = 0;
- init_timer();
- while(1)
- {
- if(Flag_Fresh)
- { Flag_Fresh = 0;
- DisplayFresh(); // 定时刷新数码管显示
- }
- if(Flag_clac)
- { Flag_clac = 0;
- ClacSpeed(); //计算转速,并把结果放入数码管缓冲区
- Tcounter = 0;//周期定时 清零
- TH1=TL1 = 0x00;//脉冲计数清零
-
- }
- if(Flag_Err) //超量程处理
- {
- Disbuf[0] = 0x9e; //开机时,初始化为0000
- Disbuf[1] = 0x9e;
- Disbuf[2] = 0x9e;
- Disbuf[3] = 0x9e;
- while(1)
- { DisplayFresh();//不再测速 等待复位i
- }
- }
- }
- }
- //在数码管上显示一个四位数
- void DisplayFresh()
- {
- P2 |= 0xF0;
- LED_SEG0 = 0;
- LED_DAT = table[Disbuf[0]];
- Delay(1);
- P2 |= 0xF0;
- LED_SEG1 = 0;
- LED_DAT = table[Disbuf[1]];
- Delay(1);
- P2 |= 0xF0;
- LED_SEG2 = 0;
- LED_DAT = table[Disbuf[2]];
- Delay(1);
- P2 |= 0xF0;
- LED_SEG3 = 0;
- LED_DAT = table[Disbuf[3]];
- Delay(1);
- P2 |= 0xF0;
- }
- //计算转速,并把结果放入数码管缓冲区
- void ClacSpeed()
- {
- uint speed ;
- uint PlusCounter;
- PlusCounter = TH1*256 + TL1;
- speed =6*PlusCounter/K; //K是校准系数,如速度不准,调节K的大小
- Disbuf[3] = (speed/1000)%10;
- Disbuf[2] = (speed/100)%10;
- Disbuf[1] = (speed/10)%10;
- Disbuf[0] = speed%10;
- }
-
- void init_timer()//初始化定时器T0\T1
- {
- TMOD=0x51; //定时器0工作于定时方式1,定时器1工作于计数方式
- TH0=(65536-10000)/256;
- TL0=(65536-10000)%256; //TO定时时间为10000个周期即10毫秒
- TH1=0x00;
- TL1=0x00;
- ET0=1; /* enable timer0 interrupt */
- EA=1; /* enable interrupts */
- TR0=1; /* timer0 run */
- ET1=1; /* enable timer1 interrupt */
- EA=1; /* enable interrupts */
- TR1=1;
- }
- //延时函数
- void Delay(uint ms)
- {
- uchar i;
- while(ms--)
- for(i=0;i<100;i++);
- }
复制代码
包含C,汇编程序,HEX
syyyd.com-测速 1T=10.zip
(4.71 KB, 下载次数: 129)
|