A Real Time clock (Digital Clock) can be made easily by using Timer 1 of a PIC Microcontroller.
The Timer1 module exists in most of the series of PIC, this module can be used to easily implement a real-timeΒ clock. Instead of an external real-time clock device like aΒ DS1307, an inexpensive 32.768 kHz watch crystal and twoΒ 33 pF capacitors are used to complete the circuit.
In this application, Timer1 is clocked by an external crystal (32.768 kHz) connected across RC0 (T1OSO) andΒ RC1Β (T1OSI).
Timer TMR1 module is a 16-bit timer/counter, which means that it consists of two registers (TMR1L and TMR1H).Β
It can count up 65.535 pulses in a single cycle before the counting starts from zero.
These registers can be read or written to at any moment.Β
In case an overflow occurs, an interrupt is generated if enabled.
Circuit Diagram
As shown on the circuit diagram above on figure 1, an external 32.768 kHz watch crystal and two 33 pF capacitorsΒ are connected to Timer1 on PORTC, RC0 (T1OSO) and RC1 (T1OSI).Β
The PIC uses an internal oscillator and the MCLR is disabled. If an external oscillator is needed, it can be connectedΒ to pins 9 (OSC1) and 10 (OSC2) and if the MCLR is needed to reset the PIC, it can be connected to positive supplyΒ via a 10K resisitor.
Time and Date are read from a Personal Computer (PC) via a serial connection. A MAX232 IC is used to convert the voltage logics from the PIC to RS232 standard and vice versa. To learn more on serial connection, please refer to the article:Β PIC Microcontroller Communication: The RS232.Β
When power is switched on, a message will be sent to the PC to set the date and the time.Β
A 16 x 2 lines LCD display is connected to PORT B. refer to theΒ Interfacing LCD Display with PIC microcontrollerΒ article to learn more.
LED D1 flashes each second as the clock isΒ running.
MPLAB XC8 compiler is used to write the code.Β
The PIC18 Peripheral Library found inside the installation folder of CX8 compiler contains a full description ofΒ Real-Time Clock and Calendar (RTCC) function simulated using Timer1.Β
Open_RTCC():Β Configures Timer1 to work as clock source for RTCC, enables Timer1 interrupts, and writes a valueΒ into TMR1H & TMR1L registers to get 1second interrupt.
update_RTCC():Β checks for the TMR1 interrupt flag, refreshes TMR1H if interrupt has occurred and returns theΒ state of TMR1IFΒ
For more detail: Digital Clock using PIC Microcontroller Interrupt β XC8