Creating a Clock in a Microchip PIC18F

Engineering is full of these little exercises. A set of numbers that must be arranged to achieve the desired result. In this case I need to keep time in a microcontroller, as there are events that I wish to occur every few seconds.

If you are using a crystal oscillator with the microcontroller, the frequency is reasonably accurate, about 50ppm at 25°C. As long as your application does not require high precision time, the result is a decent clock. Some form of clock or timekeeping is a very typical function in many microcontroller projects.

To do this I have a standard set of subroutines that I simply import into each microcontroller project. Well tested and used for years, requiring little effort to set up each time. The routines count seconds, minutes, hours, and even days and months if needed. This time is different… I am using a PIC18F25K80 in place of the PIC16’s I have used for decades. A newer processor, little differences in the hardware and instruction set… I need to rewrite the code.

PIC18F Timer
The layout of timer 2 in the PIC18F25K80 microcontroller

Timer 2 on the PIC18F25K80 is typical of timers found in both the PIC16 and PIC18 family. There are always a handful of timers in any microcontroller, usually with different arrangements for different tasks. At least one will be set up much like this one, with a comparator to provide a repeating fixed and timed interval.

Continue reading “Creating a Clock in a Microchip PIC18F”