?? fm_s.c
字號:
#include <stdio.h>
#include <conio.h>
#include <dos.h>
#define ESC 27
/*Constants definition:*/
#define N 65536
#define F_CLK 5000000
#define BASE 0x240
/*Global virables:*/
unsigned char started=0;
unsigned int overflow_cnt=0;
float frq=0.0;
unsigned int cnt_old,cnt_new;
void init_cnter(){/*使用counter0作為計數器,用fout0作為clk*/
disable();/*關閉中斷*/
outportb(BASE +03,0x36); /*寫8254chip 1的控制字,值為:0011 0110 binary.
作用為:
選擇fout0 , mod3 ,先讀寫LSB然后MSB.16進制計數 */
/*設置fout0頻率為5MHz*/
outportb(BASE +00,0x02);//write LSB
outportb(BASE +00,0x00);//write MSB ,這兩句向fout0中寫入2,就是2分頻,晶體振蕩器頻率是10m,所以輸出為10/2=5mhz
outportb(BASE +24,0x01); /*open fout0*/
outportb(BASE +18,0x02); /*初始化counter0的時鐘模式為以fout0作為clk*/
outportb(BASE +11,0x30);/*初始化counter0*/
/*寫8254chip 3的控制字,值為:0011 0000 binary.
作用為:
選擇counter0, mod0 ,先讀寫LSB然后MSB.16進制計數 */
outportb(BASE +8,0xff); /*counter0 =65535*/
outportb(BASE +8,0xff);
enable();/*開中斷*/
}
unsigned int read_counter(){
/*向8254chip3的控制寄存器寫入0000 **** binary code
作用為:
選擇counter0, latch
*/
unsigned int c1,c2;
outportb(BASE +11,0x00);
c1=inportb(BASE +8);
c2=inportb(BASE +8);
return c2*256+c1;
}
void reload_counter(){
outportb(BASE +8,0xff);/*寫LSB*/
outportb(BASE +8,0xff);/*寫MSB*/
/*使用的是mode0,計數從新的值65535開始*/
}
void init_frq_measure(){
started=0;
overflow_cnt=0;
cnt_old=0xffff;
init_cnter();/*把8254的方式定為mod0,裝入ffffh。等待閘門信號進行counter0減計數。*/
}
/*
程序用來更新frq的值
如果frq的值被更新了,則返回值1,否則返回0;
*/
int update_frequency (void) {
cnt_new=read_counter();
if(cnt_old ==cnt_new){
if(started){/*說明計數結束了
計算頻率值;*/
frq=F_CLK /(float)((overflow_cnt+1)*N-cnt_new);
cnt_old=0xffff;
started=0;
overflow_cnt=0;
reload_counter();/*counter的值重置為0xffff;*/
return 1;
}
}else{/*不相等*/
started=1;
if(cnt_old <cnt_new){
overflow_cnt++;/*溢出次數加上1*/
}
}
cnt_old=cnt_new;/*把cnt_old更新(下一次的old就是本次的new),為下一次查詢做準備*/
return 0;
}
void main(){
clrscr();/*清除屏幕,tc庫函數*/
init_frq_measure();/*初始化測頻*/
do{
if (update_frequency()){/*如果更新了頻率,就輸出新的值*/
printf("frequency=%f\r",frq);
}
if(kbhit())
if(getch()==ESC)
break;/*這句表示按下ESC就退出,否則什么也不做*/
}while(1);
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -