#define F_CPU 8000000UL
#define SCL_CLOCK 100000L
#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>
#define I2C_WRITE 0
#define I2C_READ 1
#define START 0x08
#define MT_SLA_ACK 0x18
#define MT_DATA_ACK 0x28
#define esclavo 0xD0
void i2c_inicio(void);
unsigned char i2c_start(unsigned char address);
unsigned char rep_i2c_start(unsigned char address);
unsigned char i2c_escr(unsigned char dato);
unsigned char i2c_leerAck(void);
unsigned char i2c_leerNack(void);
void i2c_inicio(void)
{
/*inicializar TWPS = 0 => prescaler =1 */
TWSR = 0;
TWBR = ((F_CPU/SCL_CLOCK)-16)/2 ;
}
unsigned char i2c_start (unsigned char address)
{
/*ENVIAR CONDICIÓN START*/
TWCR = /**/ (1<<TWSTA) | (1<<TWEN)| (1<<TWINT);
PORTC = 0x03;
/*ESPERAR SETEO POR WARDWARE DEL FLAG TWINT*/
while (!(TWCR & (1<<TWINT)));
if ((TWSR&0xF8) != START) return 1;
/*mandar dirección de esclavo*/
TWDR = address;
TWCR = (1<<TWINT)|(1<<TWEN);
/*ESPERAR SETEO POR WARDWARE DEL FLAG TWINT*/
while (!(TWCR & (1<<TWINT)));
if ((TWSR&0xF8) != MT_SLA_ACK) return 1;
return 0;
}
/*repetición START*/
unsigned char rep_i2c_start (unsigned char address)
{
return i2c_start(address);
}
unsigned char i2c_escr (unsigned char dato)
{
/*escribir dato después de haber mandado la dirección del esclavo*/
TWDR = dato;
TWCR = (1<<TWINT)|(1<<TWEN);
/*asegurarse del seteo de TWINT*/
while (!(TWCR & (1<<TWINT)));
/* enmascarar y comparar TWSR */
if ((TWSR&0xF8) != MT_DATA_ACK) return 1;
return 0;
}
unsigned char i2c_leerAck(void)
{
TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWEA);
while(!(TWCR & (1<<TWINT)));
return TWDR;
}
unsigned char i2c_leerNack(void)
{
TWCR = (1<<TWINT) | (1<<TWEN) ;
while(!(TWCR & (1<<TWINT)));
return TWDR;
}
void i2c_stop(void)
{
TWCR = (1<<TWINT)|(1<<TWEN)|(1<TWSTO);
}
void main (void)
{
i2c_inicio();
i2c_start(esclavo+I2C_WRITE);
i2c_escr(0x00);/*envío dirección o puntero*/
i2c_escr(0x59); /*segundo*/
i2c_escr(0x35);/*minutos*/
i2c_escr(0x22);/*horas*/
i2c_escr(0x05);/*dia*/
i2c_escr(0x19);/*fecha*/
i2c_escr(0x11);/*mes*/
i2c_escr(0x09);/*año*/
i2c_escr(0x10);/*confuguracion*/
i2c_stop();
}