Here's a simple but very instructive exercise. It demonstrates how to finely adjust the PIC clock frequency. To make this easy to watch, we'll run the PWM (which is derived from the master PIC clock) at 10 kHz and see what happens.
The internal PIC clock is an RC affair, meaning that its absolute frequency may vary a bit from chip to chip (and also according to temperature). When I ran the exercise, I found that the PWM frequency was centered at 9.6195 kHz.
This is the circuit we'll be using:
Here's what's going on. The potentiometer is monitored by the PIC's ADC. This value is then scaled to be a signed 6-bit number which is then stuffed into the OSCTUNE register, thus tweaking the clock frequency. According to the data sheet, variation of +/- 12.5% is possible.
When I measured things, I got:
- 8.402 kHz, low end
- 9.6195, kHz, center
- 10.838 kHz, high end
This ends up being about +/- 12.66%. Not bad!
Be sure to note how the use of three PIC Micro Pascal library units make short work of the source code.
Click to get the source code.
Click to get the schematic PDF.
Next Project: Nonvolatile Memory Demo