how to calculate the frequency of a pulse train in 8051

Thread Starter

mantsali

Joined Oct 20, 2009
7
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.
 

Papabravo

Joined Feb 24, 2006
21,225
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.
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:
Rich (BB code):
1 / f (the frequency) = T(the period)
1 / 40,000 = 25 x 10^-6 or 25 microseconds
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.
 

Arm_n_Legs

Joined Mar 7, 2007
186
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;
}
 
Top