PIC16F628A : Using delays for PIC16F628A @ 4MHz
by Nicolae
(City)
Hi, I have a PIC16F628A set on internal clock (4MHz). I tried with an external 4MHz clock with the same result.
I use the compiler PICC-Lite from Hi_Tech. I intend to generate a 40kHz train of pulses for an ultrasonic application. Therefore I need a 25us period, which split in half gives 13us and 12us.
I tried using various methods, but each one seems to be worse than the other ones. First I tried using DelayUs(13) and Delay(12), which gives me a delay or about 18us and 13us. The code is extremely simple, all I have is:
main()
{
TRISA = 0b00000000;
TRISB = 0b00000000;
PORTA = 0;
PORTB = 0;
PORTA = 0b00000000;
while(1)
{
PORTA = 0b11111111;
DelayUs(12); //takes 10us
PORTA = 0b00000000;
DelayUs(13); //takes 13us
}
}
Now, the strange thing is about these delays:
If I set first delay to DelayUs(10), I get 5us of delay, for DelayUs(11), I get 10us, for DelayUs(12) I get 18us.
If I set the second delay to DelayUs(6 to 10), I get 13us. What is worse, the value set in one delay seems to affect both delays!
I tried using assembly i.e. asm("nop") - because I am within the while() loop. But when I have assembly in the code, the 12us delay takes about 300ms. I turned on all the optimisations I could find, but no luck.
For the delay, I got some code generated by http://www.piclist.com/cgi-bin/delay.exe
Delay
;9 cycles
goto $+1
goto $+1
goto $+1
goto $+1
nop
;4 cycles (including call)
return
Unfortunately, I've been unable to embed it into my program - if I embed it, I get a delay hundreds of times longer than I expect!
Could you please explain how to embed the above code within a C project?
Regards,
Nicolae