DS1307 Interface with PIC16F887 microcontroller – CCS C compiler

This article shows how to build a simple real time clock/calendar using PIC16F887 and DS1307 RTC chip.
The DS1307 is an 8-pin integrated circuit uses I2C communication protocol to communicate with master device which is in our case the PIC16F887 microcontroller.
The PIC16F887 microcontroller has an I2C (IIC) module with two pins are used for data transfer. These are the RC3/SCK/SCL pin, which is the clock (SCL), and the RC4/SDI/SDA pin, which is the data (SDA).
The DS1307 can count seconds, minutes, hours, day, date, month and year with leap-year up to year 2100.

The DS1307 receives and transfers data (clock data and calendar data) as BCD format, so after receiving data we have to convert these data into decimal data, and before writing data to the DS1307 we have to convert this data from decimal to BCD format. For example we have the BCD number 33, converting this number into decimal gives 21.

In the CCS C code I used the following line to covert a number ‘x’ from BCD to decimal:
x = (x >> 4) * 10 + (x & 0x0F);
And to go from decimal to BCD I used this line:
x = ((x / 10) << 4) + (x % 10);

Hardware Required:

  • PIC16F887 Microcontroller
  • DS1307 RTC (datasheet)
  • 16×2 LCD screen
  • 32.768 KHz crystal
  • 10K potentiometer or variable resistor
  • 2 x 10K ohm resistors
  • 3V Coin cell battery
  • 0.1µF Ceramic capacitor (optional)
  • 5V Power supply source
  • Breadboard
  • Jumper wires

DS1307 Interfacing with PIC16F887 circuit:
The circuit diagram of the example is given below.

PIC16F887 DS1307 real time clock with buttons circuit

In this example the PIC16F887 MCU uses its internal oscillator and MCLR pin function is disabled.
SCL pin of PIC16F887 (pin number 18) is connected to the SCL pin of the DS1307 (pin number 6) and SDA pin of PIC16F887 (pin number 23) is connected to the SDA pin of the DS1307 (pin number 5).
The 3V cell battery is used to keep the time running if the main power is off.
The two resistors R1 & R2 are pull-up resistors, they are necessary for the I2C protocol.
In the circuit there are two buttons to set time and calendar. The button B1 selects time or calendar parameter (minutes, hours, date, month and year) and B2 increments the selected parameter.

DS1307 Interfacing with PIC16F887 CCS PIC C compiler code:
The code below can display time and calendar where their parameters such as minutes using two push buttons.
This code is tested with version 5.051.

The following video shows project simulation with Proteus:

Simulation file can be downloaded from this link:
DS1307 + PIC16F887 Simulation

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.