"The scope" - Frequency/period measure (Square signal) 8051

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <stdio.h>
#include <reg66x.h>
#include <DISPPORT.h>
void tinit(void); //timer 0 init function
float puls_measure(void); //pulse width measure function
void delay(unsigned int t); //delay function
void main()
{float puls, frq, per; //define variables
init_display(); //init display
tinit(); //init timer 0
while(1)
{
puls = puls_measure(); //measure pulse
per = puls*2*0.00054244; //calculate the period
frq = 1000/per; //calculate the frequency
printf("%.5f ms %.0f Hz",per,frq); //show period and frequency
cursor(2,1); //go to second line
printf("%.0f",puls); //show the pulse width count
delay(30000); //wait for a second
cld(); //clear the display
}}
void tinit(void) //timer init fuction
{TMOD=0x09; //set timer 0 to mode 1 and gate 0
}
float puls_measure(void) //pulse measure function
{float p; //set the pulse variable
TH0=0; //set higher timer reg to 0
TL0=0; //set lower timer reg to 0
while(INT0); // wait for last pulse to pass
while(!INT0); //wait for rising edge
TR0=1; //start timer
while(INT0); //wait while pulse
TR0=0; //stop timer
p=(TH0<<8|TL0); //get timer reg values
return p;} //return the pulse width
void delay(unsigned int t)
{unsigned int i;
for (i=0;i<t;i++);
}