This will get you spot-on 40kHz with a 4MHz oscillator.
Code:
Cycles VAR BYTE
TRISIO.0=0 ' make pin an output first
GOTO Main ' jump over Pulse routine to Main
' @ 4MHz generate Cycles number of 40kHz pulses
asm
_Pulse
bsf GPIO,0 ; change to whatever port pin you have available
goto $+1 ; 2uS per GOTO $+1
goto $+1
goto $+1
goto $+1
goto $+1
bcf GPIO,0
goto $+1
goto $+1
goto $+1
goto $+1
goto $+1
decfsz _Cycles,f
goto _Pulse ; 25uS total for 40kHz carrier
RETLW 0 ; return to CALLing routine
ENDASM
Main:
Cycles = 8 ' number of carrier cycles to generate
CALL Pulse
PAUSEUS 24
GOTO Main
END
Just enter the number of carrier cycles you need to generate in the Cycles var, and
CALL the routine.
Bookmarks