Why not using the internal PWM module instead?  it will run in background and you don't need to care about latency etc etc.
use something like this...
	Code:
	DEFINE OSC 20
TRISC=0
duty var word
duty = 250                                  ' duty value for 50% duty cycle
PR2 = 124                                   ' period for 40KHZ
T2CON = %00000100                           ' timer2 on, prescale 1:1
CCPR1L = duty>>2                            ' eight MSB of duty cycle value
CCP1CON = (duty.lowbyte&3)<<5 | %00001100   ' store  2 LSB of duty 
                                            '  & set PWM mode
START:
      PAUSE 1
      GOTO START
 and look what happen on PORTC.2 pin.
Need to start it and stop it ?  here's something using PORTB.0 as trigger source
	Code:
	DEFINE OSC 20
TRISC=0
duty        var word
PWMMode     var byte
StartStop   var bit
duty = 250                                  ' duty value for 50% duty cycle
PR2 = 124                                   ' period for 40KHZ
T2CON = %00000100                           ' timer2 on, prescale 1:1
CCPR1L = duty>>2                            ' eight MSB of duty cycle value
PWMMode = (duty.lowbyte&3)<<5 | %00001100   ' store  2 LSB of duty 
                                            '    & set PWM mode
START:
    IF PORTB.0=0 then            ' 
        startstop=startstop ^ 1  ' toggle between start/stop
        if startstop=1 then      '
            CCP1CON=PWMMODE      ' Start PWM
            ELSE                 '
                CCP1CON=0        ' Stop PWM
                PORTC.2=0        ' make sure the pin is low   
            ENDIF                '
        WHILE PORTB.0=0 : WEND   ' wait until trigger release
        PAUSE 100                ' debounce delay 
        ENDIF
    GOTO START
 How to calculate those value easy?  PicMultiCalc software available bellow for FREE
http://mister-e.org/pages/utilitiespag.html
ScreenShot
<img src="http://www.picbasic.co.uk/forum/attachment.php?attachmentid=1280&stc=1&d=116639098  4">
HTH
				
			
Bookmarks