#include "fuses_PIC.h"
#define _XTAL_FREQ 4000000
#define envio_dato 0x00
#define envio_direccion 0x01
#define termino_comuncacion 0x02
#define direccion_PCF8574 0b01000000
#define NO_STOP_COMUNICACION 0b0
#define STOP_COMUNICACION 1
unsigned char volatile address;
unsigned char volatile addres_or_data_or_out = 0x00;
unsigned char volatile data;
void config_pines_botom(){
PORTB = 0x00; // Limpio puerto
//LATB = 0x00;
TRISB = 0b00000001; // pin RB0 como entrada
PORTBbits.RB1 = 1; // prendo un led de encendido pic
}
void config_pines_I2C(){
PORTC = 0x00; // Limpio puerto
TRISCbits.RC4 = 0; // SDA salida
TRISCbits.RC3 = 0; // SCL salida
}
void config_I2C(){
SSPSTATbits.SMP = 1;
SSPCON1 = 0x38; // 3=0011 8=1000
SSPADD = 0x28 ; // para 4Mhz tengo 100khz CLK de I2C
}
void interrupt I2C_VECTOR(){
PIR1bits.SSPIF = 0; // limpio bandera
if((addres_or_data_or_out == envio_direccion) && (SSPCON2bits.PEN == NO_STOP_COMUNICACION)){ // interrupcion nº1 y no stop comunicacion?
SSPBUF = address; // Ingreso direccion del slave
addres_or_data_or_out = envio_dato; // proxima interrup sera de ack para dato
}
if((addres_or_data_or_out == envio_dato) && (SSPCON2bits.PEN == NO_STOP_COMUNICACION)){ // interrupcion nº2 y no stop comunicacion?
SSPBUF = data; // Ingreso dato a enviar
addres_or_data_or_out = termino_comuncacion; // proxima interrup sera de ack para termino comunicacion
SSPCON2bits.PEN = STOP_COMUNICACION;
}
if((addres_or_data_or_out == termino_comuncacion) && (SSPCON2bits.PEN == STOP_COMUNICACION)){ // interrupcion por termino de comunicacion?
addres_or_data_or_out = envio_direccion; // limpio variable para nueva comunicacion
SSPCON2bits.PEN = NO_STOP_COMUNICACION;
}
}
void enviar_dato(){
SSPCON2bits.SEN = 1; // INICIO coomunicacion
}
void config_interrupciones(){
RCONbits.IPEN = 0; // sin prioridad
PIR1bits.SSPIF = 0; // limpio bandera
// IPR1bits.SSPIP = 1; // seteo prioridad
PIE1bits.SSPIE = 1; // habilito interrupcion
INTCONbits.PEIE_GIEL = 1; // habilitar interrupcion periferica
INTCONbits.GIE_GIEH = 1; // habilitar interrupciones globales
}
void main(){
config_pines_I2C();
config_pines_botom();
config_I2C();
config_interrupciones();
while(1){
if(PORTBbits.RB0 == 0){
data = 0b10101101; // dato a enviar
enviar_dato(); // enviar dato
__delay_ms(500);
}
if(PORTBbits.RB0 == 0){
data = 0b01010010; // dato a enviar
enviar_dato(); // enviar dato
__delay_ms(500);
}
}
}