Electronic – problem with using delay functions when using internal oscillator in PIC

microcontrollerpicpic-ccs

I am doing a project that requires having the micro-controller to use the delay_ms() functions (compiler CCS C) to wait for a determined period of time.

I am using PIC 16f628A and while the program ran as intended in Proteus but it ran about 85 times faster that that when I tried it on the board .

I did choose to set the internal oscillator to the minimum possible frequency (48khz) to decrease power consumption and I specified that in the wizard and so the .h file have the line #use delay(internal=48kHz).

What am I doing wrong ?.

Best Answer

Summary:

You need to set OSCF (bit 3) to 0 in the PCON register in your code (i.e. during runtime) when you want the PIC INTOSC (Internal Oscillator) to run at a nominal 48 kHz (actually anywhere between 31.4 kHz and 78.62 kHz) instead of the power-on INTOSC default frequency of 4 MHz.

Details:

I did choose to set the internal oscillator to the minimum possible frequency (48khz) to decrease power consumption and I specified that in the wizard and so the .h file have the line #use delay(internal=48kHz).

The problem is that none of the things you list actually set the INTOSC hardware to 48 kHz. Based on what you said, it seems your software assumes the CPU will run at 48 kHz, but your hardware will still run at the default 4 MHz INTOSC frequency.

the program ran as intended in Proteus but it ran about 85 times faster that that when I tried it on the board .

Yes, that's what I expect.

85 faster x 48 kHz = 4 MHz (approx.)

This result suggests that your MCU was actually still running at the default INTOSC frequency of 4 MHz.

The important point is that you cannot configure that PIC to run at 48 kHz from power-on. If you set the CONFIG BITS (a.k.a. Fuses) to one of the two variants of INTOSC setting, then the MCU will use the internal 4 MHz frequency at power-on.

Then, when you want to switch it to 48 kHz (perhaps at the start of your main() but perhaps elsewhere in your code - it's up to you to choose) you then set OSCF (bit 3) to 0 in the PCON register - that bit is what switches the INTOSC frequency from 4 MHz to 48 kHz (after a short switchover transition).


extract from PIC16F628A datasheet showing OSCF bit in PCON register


See section 14.2.8 "SPECIAL FEATURE: DUAL-SPEED OSCILLATOR MODES" on page 101 of the PIC16F628A datasheet for more details.


extract from PIC16F628A datasheet about switching INTOSC speed


Also note that the datasheet does not specify the accuracy of the 48 kHz clock (only the 4 MHz clock accuracy is specified there). However the PIC16F628A errata shows that the 48 kHz clock can actually vary between 31.4 kHz to 78.62 kHz.


PIC16F628A errata for INTOSC at 48 kHz