1
\$\begingroup\$

I have a PIC16F688 running on 4MHz (intosc) and I need a delay for about 1 second. Using this for-loop:

for (unsigned long n = 0; n < 219300; n++) {}

yields this result in the stopwatch function in the simulator:

Stopwatch cleared. Stopwatch cycle count = 0 (0 ns)
Target halted. Stopwatch cycle count = 4038340 (1.009585 s)

That's perfectly fine for my application.

But when I run the code in an actual chip, the delay takes about 10-12 seconds instead of 1. This made me think that the chip is running on a way lower frequency than 4MHz, but I've double checked and it is in fact running at 4MHz. The simulator is also setup to run at 4MHz, so no mismatch here.

Other than a too low frequency I cannot think of any other error that makes this delay way off. Interrupts are turned off (INTCON = 0).

Any clue as to why this happens? Why doesn't the stopwatch value match reality?

enter image description here

\$\endgroup\$
3
  • 1
    \$\begingroup\$ " I've double checked and it is in fact running at 4MHz", how did you check? \$\endgroup\$
    – pipe
    Commented Oct 26, 2017 at 9:46
  • 1
    \$\begingroup\$ This is an 8-bit PIC. You're confusing the Clock Frequency with the Instruction Frequency and thinking they're the same. They're not. The Instruction Frequency is 1/4 the Clock Frequency. \$\endgroup\$
    – brhans
    Commented Oct 26, 2017 at 11:40
  • \$\begingroup\$ Trap for beginners. I did the same thing when I first started with the PICs \$\endgroup\$
    – DerStrom8
    Commented Oct 26, 2017 at 13:02

2 Answers 2

2
\$\begingroup\$

I think the Rc oscillator frequency( which is the internal Rc frequency) is what you should use in your calculation and not the instruction frequency. seeing that (4 MHz/250 KHz) == 16, your code lagging by 12 seconds can be attributed to this mismatch.

\$\endgroup\$
-1
\$\begingroup\$

Divide value by 4. The simulator shows Mcycles/sec not Fclock which is 4 times faster.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.