I used I2C routines from I2C tutorial to real time clock pcf 8583 and it not working. It shows 00:00:00 and i don't know why. My device is PIC18f4550 and i use c18 compiler. Can You help me?
This is my code:
- Code: Select all
#include <p18cxxx.h>
#include <stdio.h>
#include <delays.h>
#define SDA TRISAbits.TRISA3
#define SCL TRISAbits.TRISA4
#define SDA_IN PORTAbits.RA3
#define SCL_IN PORTAbits.RA4
void i2c_init (void)
{
SDA = SCL = 1;
SCL_IN = SDA_IN = 0;
}
void i2c_delay (void)
{
Delay10TCYx(1); //delay 10 instruction cycles
}
void i2c_start(void)
{
SDA = 1; // i2c start bit sequence
i2c_delay();
SCL = 1;
i2c_delay();
SDA = 0;
i2c_delay();
SCL = 0;
i2c_delay();
}
void i2c_stop(void)
{
SDA = 0; // i2c stop bit sequence
i2c_delay();
SCL = 1;
i2c_delay();
SDA = 1;
i2c_delay();
}
unsigned char i2c_read (char ack) // 1-ack, 0-nack
{
unsigned char x, d=0;
SDA = 1;
for(x=0; x<8; x++) {
d <<= 1;
do {
SCL = 1;
}
while(SCL_IN==0); // wait for any SCL clock stretching
i2c_delay();
if(SDA_IN) d |= 1;
SCL = 0;
}
if(ack) SDA = 0;
else SDA = 1;
SCL = 1;
i2c_delay(); // send (N)ACK bit
SCL = 0;
SDA = 1;
return d;
}
char i2c_send (unsigned char d)
{
unsigned char x;
for(x=8; x; x--) {
i2c_delay();
if(d&0x80) SDA = 1;
else SDA = 0;
SCL = 1;
i2c_delay();
d <<= 1;
SCL = 0;
}
i2c_delay();
SDA = 1;
SCL = 1;
i2c_delay();
x = SDA_IN;
SCL = 0;
return x;
}
char sec, min, hr, day, mth, year;
void fromi2c (void)
{
i2c_start();
i2c_send(0xA0);
i2c_send(0x02);
i2c_start();
i2c_send(0xA1);
sec=i2c_read(1);
min=i2c_read(1);
hr=i2c_read(1);
day=i2c_read(1);
mth=i2c_read(0);
i2c_stop();
}
void usart(void)
{
TRISCbits.TRISC7=1;
TRISCbits.TRISC6=1;
TXSTA=0b00101110;
RCSTA=0b10010000;
BAUDCON=0;
SPBRG=129; //baud=9600
}
void main(void)
{
while(1)
{
usart();
i2c_init();
odi2c();
printf("\r%02x:%02x:%02x\r", sec, min, godz);
}
}
