All microcontrollers require a clock or oscillator to guide a program through its paces. It’s the duty of such a module to indicate when an instruction should be fetched from program memory, decoded and acted upon. Actually, even the simplest instruction is made up of a number of operations that must be sequenced in just the right order and at just the right moment. The clock, then, is like the conductor of an orchestra, coordinating all of the parts that make up the whole.
Since the clock is so important, PIC microcontrollers offer a broad range of options to choose from for your own applications. You can have clocks that run rapidly when a lot has to happen in a short span of time, or ones that consume negligible power for battery operated rigs. Maybe synchronizing the PIC to a stable realtime clock is important to you. In fact, there are eight or more clock options for the typical PIC. But if you grab the data sheet and try to sort out all the possibilities you’ll quickly come to rue that old phrase, “can’t see the forest for the trees.” Data sheets for PICs run in the hundreds of pages and aren’t necessarily organized for best learning. And of course, the occasional error works its way in making it even harder for the newcomer to get up to speed.
As someone who has spent his entire adult life in teaching, I’ve always intuitively valued the importance of a well organized presentation. You begin with the “forest” and only approach the “trees” afterwards. That’s what we’ll do here, getting the big picture in mind first and then tackling the details when they’re finally needed.
So, if you’ve been dismayed in the past at how complicated the clock options for PIC microcontrollers seem to be, tag along now and see how the right approach can make all the difference. And to turn this into an active learning experience, let’s conclude with some actual experiments you can conduct on the breadboard. By the end of our session together, you should be all set to start using PIC clocks with confidence.
To keep things concrete, I’ll focus on the PIC16F88 which is one of the most popular of all microcontrollers among DIY-ers. However, other PICs will sport many of the same options, even the smaller 8-pin chips.
The first concept to nail down is that the PIC can run either on a primary clock or a secondary clock. The former accounts for most situations. In particular, a typical project contains a single clock guiding the microcontroller along and that’s the end of the matter. But in more advanced applications we may want a secondary clock to kick in whenever the primary clock is out of the scene. There are several reasons for desiring such redundancy, and we’ll explore them in just a bit.
For now, let’s focus on the primary clock which is all we need for most projects. Refer to the following figure which shows what’s available. You can click on it to expand it for better reading.
This tree diagram organizes the types of primary clocks available within the PIC16F88 in a top-down fashion. To begin, look at the first branches of the tree diagram. A clock can be an internal RC affair, or if you prefer you can supply your own resistor and capacitor and end up with an external RC arrangement. For situations that demand more precision, an external crystal or ceramic resonator can be employed. Lastly, if you’d like, you can also drive the PIC with an existing external clock.
Adding a bit more detail now, the branches of the tree split again showing the eight individual modes. Each has an abbreviated name given it by the Microchip company, and these are worth learning now to simplify reading the data sheet later on. Let’s scan these specific modes from left to right. The first is INTRC which stands for internal RC oscillator. Running at an approximate 31.25 kHz, this is a low speed affair built inside the PIC. While that’s pretty slow by any standards, it does have the advantage of being simple and consuming very little current.
The next mode is INTOSC. Like INTRC this is internal, requiring no outboard components, but can run at seven different speeds all the way up to 8 MHz. In some of the PICs, INTRC and INTOSC are truly independent, but not so in the PIC16F88 we’re examining. For this reason, in the data sheet the writers sometimes use INTRC to mean INTRC only and at other times to signify either INTRC or INTOSC. That only adds to the confusion, so I’m going to keep the names separate here.
In either of these modes, port line A.6 can be configured to follow the clock divided by four if desired. This is symbolized φ/4, read “phi divided by four.” Use this output if you’d like to synchronize some external gear to the microcontroller. The data sheet calls this mode INTIO1, if you’re curious. Otherwise, you can optionally free up pin A.6 for ordinary digital I/O, referred to as INTIO2 mode.
Moving to the external RC modes, the first is simply called RC. In this case an external resistor and capacitor on pin A.7 start things going. Assuming a +5V power supply, the resistor should lie between 3k and 100k, while the cap should be greater than 20pF. With the smallest values the clock will max out at around 4 MHz. Like we saw with the internal clocks, if desired A.6 can be caused to follow φ/4 (that’s RC mode) or else be free for ordinary use (that’s RCIO). Incidentally, the resistor could be a potentiometer wired as a rheostat which would give you a variable clock.
Crystals and ceramic resonators are attractive since they’re much more accurate both in the short term and long term, and also with respect to tolerances and temperature. There are three modes here. The first, LP which stands for low power, is meant to be used with a 32.768 kHz tuning fork type crystal. These pop up commonly in wristwatches and realtime clocks. The crystal and associated load capacitors connect to pins A.6 and A.7. The next mode, called XT, is similar but meant for use with higher frequency crystals and resonators up to about 4 MHz. The last mode is HS, standing for high speed, and is needed for crystals or resonators cranking above 4 Mhz. Just so you know, the upper limit for the PIC16F88 is 20 MHz. What’s neat about these three modes is that the chip automatically selects the correct gain of the internal driver to the crystal based on whether you specify LP, XT or HS.
The last mode is ECIO which simply lets you pump in an external clock signal on pin A.7. This could come from any sort of clock circuit that puts out square pulses swinging from ground to the supply voltage.
If you peek ahead to the experiments, below, you'll see the hardware arrangements involved with some real-world values given for the components. We’ll get there in a moment, but first let’s take a quick look at the secondary clock options.
The figure below shows a branching tree diagram for the available secondary clocks. Recall that any of these can take over duties from the primary clock under certain circumstances. The data sheet likes to group these into the categories RC_RUN and SEC_RUN, but both really do indicate secondary clocking.
There are two choices for RC_RUN. Either the INTRC or INTOSC internal clocks described earlier can be used, the difference really only being rate of oscillation.
Or if desired, you can attach the 32.768 kHz crystal and load capacitors to B.6 and B.7. What so cool about this is that the watch crystal always runs, even when you put the chip into what’s known as sleep mode. This mode, designated T1OSC, is ideal for realtime clock applications. (Normally the PIC will shut down unused clocks when going to sleep). Observe that primary clocks use A.6 and A.7 in various combinations, but secondary clocks do not, at least for the PIC16F88. We'll see an actual schematic in just a moment (for one of the experiments coming up) that explains what’s involved.
And with that we’ve concluded our overview of the primary and secondary clocks. Why not take a few moments to study these first two figures once more to really fix the distinctions and details in your mind before proceeding.
How to Make Your Selection
So, you’ve decided what kind of clock you want. Now how do you express your wishes to the PIC? The answer lies in the configuration bits and three special registers. The configuration bits are set during the burning (flashing or programming) phase, while the register bits are accessible during runtime. Here’s the scoop.
The following figure illustrates the two sets of configuration bits within the PIC16F88. (Simpler PICs only have one set).
Yes, there’s a lot there, but when it comes to setting up the clock, only a handful need concern us. For example, the three bits labeled FOSC designate the primary oscillator as described earlier. In other words, these establish the default behavior on power-up.
In the second set of configuration bits you’ll find two that govern what will happen when you switch over from the primary to secondary clocks, or vice-versa. We’ll save that for the next section.
Once a program is running, you can manipulate the clock or clocks in various ways by modifying registers OSCON, OSCTUNE and T1CON. These are shown in in the next figure. Let’s ponder the details.
Perhaps the most important bits in OSCON are the ones labeled IRCF, which stands for internal RC oscillator frequency. As the name suggests, these bits select the desired clock rate of the internal oscillator(s). Next up are the two bits labeled SCS, denoting system clock select. Here you can choose to use the primary or secondary clocks.
It’s no big surprise that the register OSCTUNE lets you fine-tune the INTRC or INTOSC clock frequency. (On some PICs only INTOSC is affected.) A six-bit two’s-complement number is all it takes. Negative numbers slow the clock down while positive ones speed it up. Tuning over a range of ±12.5% is possible.
The register T1CON concerns itself with controlling Timer 1. Now Timer 1 is typically clocked by an external 32.768 kHz crystal, which can also do double-duty as the system clock. You might remember this as T1OSC mode referred to earlier The important flag here is T1OSCEN which enables the Timer 1 crystal oscillator.
At this point we’ve hit the fundamentals of clocking the PIC microcontroller for most common situations. Let’s finish up by taking a brief look at the secondary clocks and what they’re good for.
The day may come when you’ll want to go beyond just turning on a primary clock and letting it do its thing. If so, then you’ll need to know a little bit about clock switching. The next diagram gives the big picture.
Essentially you can manually switch between primary and secondary clocks, or do so automatically under certain conditions.
To manually switch from one to another, you’re back to what was mentioned above and simply need to alter a few bits in the three registers described there. For example, to change from INTRC to INTOSC, you’d adjust bits IRCF0 through IRCF2 as required. Or to go from a crystal oscillator, say, to INTOSC head to SCS0 and SCS1 which let you flip back and forth from primary to secondary. You get the idea; manually switching oscillators is just a matter of bit-twiddling in your program.
But what about automatic switchovers? Well, there are two situations in which it’s handy to have one clock take over for another. The first is the failsafe mechanism. Imagine you’re designing a circuit to operate in a critical environment, say in medicine or industrial safety monitoring. Now if the primary oscillator was a crystal, for instance, and it failed for some reason then the PIC would simply come to a standstill. Not good! But with a secondary clock in the wings, the chip could switch over to it almost seamlessly and still keep operating until the original fault could be attended to. As the figure above shows, the failsafe feature can check for problems with any of the four crystal modes (LP, XT, HS or T1OSC). It’s enabled via the FCMEN bit in CONFIG2.
If avoiding delays is a concern, then the two-speed wake-up option might prove useful. Here’s the basic idea. Suppose you were operating the circuit on a crystal. As you probably know, crystal oscillators take a moment or two to warm up. The PIC understands this and patiently waits a bit before letting the clock start shooting the instructions through the pipeline. In other words, your project is just sitting there doing nothing for a few moments. On the other hand, the internal oscillators INTRC and INTOSC are essentially put in gear instantaneously. So why not choose one of these to serve as a secondary clock. Now the sequence will be that the internal oscillator handles everything (possibly at a slower rate, but a least it’s moving!) until the crystal is ready to assume the mantel of system clock. The switchover is automatic and there’s no dead time where nothing is happening.
When is this needed? As intimated earlier, PIC microcontrollers support a sleep command. When executed, the power hungry stuff is shut down and the chip idles in a very low current state. In particular, any crystal being used as a primary clock is halted. Various signals like a reset, an interrupt or something called the watchdog timer can wake the chip up again. If you want some instant action while the crystal revs up, then consider the two-speed wake-up just described. To enable this response, go to the IESO bit in CONFIG2.
With that we’ve covered the essentials of clocking the PIC microcontroller. There are other niceties you can worry about later, and that’s what the data sheet is for. But at this point you’ll at least (a) be able to handle most common situations, and (b) be in much better shape to actually read that dang thing! To really cement what you’ve learned in place, you’re encouraged to try the baker’s dozen of experiments described next. You will literally learn by doing.
You can all of the needed code in the following download package. It's been organized within thirteen folders, and the source for each includes plenty of info on how to set up the experiments. But here's just a brief description of each, to give you a feel for it all.
The first four experiments utilize this schematic. You will be moving the LED from pin 6 to pin 15 for two of them.
Experiment 1: Using INTRC, with pin A.6 free
Experiment 2: Using INTRC, with A.6 following φ/4
Experiment 3: Using INTOSC, with pin A.6 free
Experiment 4: Using INTOSC, with A.6 following φ/4
The next two exercises follow this schematic, along with the previous. Again, you will be moving the LED for the second of the two.
Experiment 5: Using RCIO, with pin A.6 free
Experiment 6: Using RC, with A.6 following φ/4
The next three experiments set up a primary clock with a crystal. Use this schematic, and see the component values specified in the PMP source code.
Experiment 7: LP, low power, 32.768 kHz crystal
Experiment 8: XT, medium power, 4 MHz crystal
Experiment 9: HS, high speed, 19.6608 MHz crystal
Here's the schematic for the next experiment:
Experiment 10: ECIO, using an external clock
The next is an interesting one. You'll set up a crystal clock as in Experiment 8, and then deliberately yank it from the breadboard just to see the failsafe mechanism kick in and switch over to the internal oscillator.
Experiment 11: Demo of the failsafe mechanism
For the next demonstration, use the same schematic as in Experiment 1.
Experiment 12: Demo of manual clock switching
And finally, here's the circuit for the last experiment:
Once again, be sure to study the source code. Not only does it provide details on the experiments, but you'll also learn some great ways to manipulate the registers with PIC Micro Pascal, a very cool language indeed!
Next Tutorial: Hardware PWM