# how to calculate the frequency of a pulse train in 8051

Discussion in 'Embedded Systems and Microcontrollers' started by mantsali, Oct 28, 2009.

1. ### mantsali Thread Starter New Member

Joined:
Oct 20, 2009
7
0
how does one generate a 40khz pulse on the two pins of a 12mhz 8051 microcontroller in code. im using c but asm is welcome. even when using time delays, i wouldn't know how long a delay have to be to generate a desired frequency.

2. ### Papabravo AAC Fanatic!

Joined:
Feb 24, 2006
8,853
1,390
If I tell you that the period of a waveform is the reciprocal of the frequency, would that be helpful to you. In this case:
Code ( (Unknown Language)):
1.
2. 1 / f (the frequency) = T(the period)
3. 1 / 40,000 = 25 x 10^-6 or 25 microseconds
4.
On an 8051 you could set a port pin to one, insert a few NOP instructions, set the port pin to 0, insert a few NOP instructions, and branch back to the beginning. The duty cycle would not be 50% since that would require a delay of 12.5 microseconds. So it might be high for 13 and low for 12, or high for 12 and low for 13, or any other combination you little heart desires.

3. ### Arm_n_Legs Active Member

Joined:
Mar 7, 2007
183
10
Use the 8051 timer to perform the timing.

For 40KHz waveform means the signal alternate every 12.5 usec. Use the timer to time for 12.5 us. Oop... if running on 12 MHz, you can't get a resolution of 0.5 us.

TMOD = 0x01;
TR0 = 1;
TF0=0;
for(;{
TH1 = 0xff;
TL1 = 0xf3;
while(TF0==0);
P0 = ~P0;
TF0=0;
}