Is there a simple way to generate a square wave (short burst 8 pulses) at 40 KHz using a PIC12F509 and PicBasic Pro?
Is there a simple way to generate a square wave (short burst 8 pulses) at 40 KHz using a PIC12F509 and PicBasic Pro?
Exactly 40Khz or thereabouts?
40Khz has a period of 25uS which means you have a 12.5uS window per half cycle... hard to achieve using 1uS timing intervals at 4MHz Clock... at 8MHz Clock you can do it... but here we go... give it a shot and see how close you get with a scope...
For CounterA=1 to 16
Toggle PulsePin
@NOP
@NOP
@NOP
@NOP
@NOP
@NOP
@NOP
@NOP
@NOP
@NOP
Next CounterA
I've made some assumptions... you're running at 4MHz and that the FOR/NEXT takes 1uS and the TOGGLE takes 1uS, so there's ten 1uS Delays...
Now if you can't get close enough to 40kHz by adding or subtracting @NOP's try this one...
For CounterA=1 to 8
High PulsePin
@NOP
@NOP
@NOP
@NOP
@NOP
@NOP
@NOP
@NOP
@NOP
@NOP
@NOP
Low PulsePin
@NOP
@NOP
@NOP
@NOP
@NOP
@NOP
@NOP
@NOP
@NOP
@NOP
@NOP
Next CounterA
If removing a NOP, try it from BOTH sections, but in the end you might find that you have one less NOP in one or other section... you may end up with an assymetric waveform, but it will be 40kHz.
It's play time...
Thanks for your response, I did try, but something very odd happens, I changed it to an infinite loop to produce a frequency that I can measure:
Loop:
Toggle PulsePin
@NOP
@NOP
@NOP
@NOP
@NOP
@NOP
@NOP
@NOP
@NOP
@NOP
GOTO Loop
But for some reason, no matter how many @NOP I add, the frequency does not change and stays at 62.5 KHz
Any Ideas?
This will get you spot-on 40kHz with a 4MHz oscillator.
Just enter the number of carrier cycles you need to generate in the Cycles var, andCode: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
CALL the routine.
Thank you both a million for your help, I had done it with ASM and ENDASM but not as elegant as Bruce did, I just coded the delay using NOPs and the the eight pulses hard coded.
Bookmarks