#include <htc.h>
__CONFIG(LVP_OFF & BOREN_OFF & PWRTE_ON & WDTE_OFF & FOSC_HS);
#define _XTAL_FREQ 20000000
#define SDATA RC4
#define SCLK RC3
void InitI2C(),I2C_start(void),I2C_write(char x), I2cSTOP(void);
void i2c_Wait(void);
unsigned char DISP[3];
unsigned char Time[] = {01, 0x11 ,0x3, 0x22 , 0x10, 0x4, 0x15};
unsigned char digits[] = { 0b00010000,0b01111101,0b00100010,0b00101000,0b01001101,0b10001000,
0b10000000, 0b00111101,0X00,0b00001000};
void InitI2C()
{
TRISC3=1;
TRISC4=1;
SSPCON=0b00101000;
SSPCON2=0;
SSPSTAT=0b10000000;
SSPADD=50; //20000/(4*100); //Fosc/(4*baud)
SSPIF=0;
BCLIF=0;
}
void WaitSSP()
{
while(SSPIF==0);
SSPIF=0;
}
void SendStart()
{
SEN=1;
WaitSSP();
}
void SendStop()
{
PEN=1;
WaitSSP();
}
void SendRestart()
{
RSEN=1;
WaitSSP();
}
char SendByte(char Byte)
{
SSPBUF=Byte;
WaitSSP();
return(!ACKSTAT);
}
char ReceiveByte()
{
RCEN=1; // get byte
WaitSSP();
return(SSPBUF);
}
void SendNack()
{
ACKDT=1; // Not Acknowledge
ACKEN=1;
WaitSSP();
}
void SendAck()
{
ACKDT=0; // Acknowledge
ACKEN=1;
WaitSSP();
}
void SendID(char DeviceID)
{
SendStart();
if(SendByte(DeviceID)==1) // Send ID until accepted..
return;
do
{
SendRestart();
}while(SendByte(DeviceID)==0);
}
//Write a byte to The RTC
char WriteRTC(char Address, char Byte)
{
SendID(0b11010000); // Send 0xD0
if(SendByte(Address&0xff)==0) // Send address
return(0);
if(SendByte(Byte)==0) // Send byte
return(0);
SendStop(); // All done
return(1);
}
char ReadRTC(char Address)
{
char Byte;
SendID(0b11010000); // Send 0xD0
if(SendByte(Address&0xff)==0) // Send address
return(0);
SendRestart(); // Re-start
if(SendByte(0b11010001)==0) // Read 0xD1
return(0);
Byte=ReceiveByte(); // Get byte
SendNack(); // No more
SendStop(); // Stop bus
return(Byte); // All done
}
void WriteClock(char *array) // Not used
{
char x;
int tmp;
for(x=0;x<7;x++)
{
WriteRTC(x,array[x]);
}
}
void ReadClock(char *array)
{
char x;
for(x=0;x<7;x++)
array[x] = ReadRTC(x); // No need to BCD-BIN
}
void main(void)
{
unsigned char ch=0;
unsigned char i=0;
int idx;
unsigned char DIGIT; // A temporary store for manipulation
ANSELH = 0;
TRISC3=1; //direction to input have be changed
TRISC4=1;
RD0=0;
RD1=0;
RD2=0;
RD3=0;
TRISB=0X00;
TRISD=0X00;
PORTB=0B00000000;
TRISC = 0; // portc tris bits
TRISD = 0; // portd tris bits
InitI2C();
WriteClock(&Time[0]);
while(1)
{
ReadClock(&Time[0]);
__delay_ms(250);
DISP[2] = Time[1] & 0xf;
DISP[1] = Time[0]>>4; DISP[0] = Time[0] & 0xf;
PORTD = 1;
PORTB = digits[DISP[0]]; // retrive 7 seg code
__delay_ms(250);
PORTD = 2;
PORTB = digits[DISP[1]]; // retrive 7 seg code
__delay_ms(250);
PORTD = 4;
PORTB = digits[DISP[2]]; // retrive 7 seg code
__delay_ms(250);
}
}