The names of functions are in Slovenian language, but I added some comments
.
EEprom must be bigger then 2K, because addres is 16Bit. All three chip-select pin connect to GND.
Code: Select all
void I2CInit(void) //Initializes I2C
{
TRISB=TRISB | 0x03;
SSPSTAT=0x80;
SSPADD=0x0A;
SSPCON2=0;
SSPCON1=0x28;
PIR1.F3=0;
PIR2.F3=0;
}
void I2C_Koncaj(void) //Issues STOP signal
{
PIR1.F3=0;
SSPCON2.F2=1;
while (PIR1.f3==0){}
}
void I2C_Zacni(void) //Issues START signal
{
PIR1.F3=0;
SSPCON2.F0=1;
while (PIR1.F3==0){}
}
void I2C_Obnovi(void) //Issues repeated START signal
{
PIR1.F3=0;
SSPCON2.F1=1;
while (PIR1.F3==0){}
}
void I2C_ZapisiPodatek(char hex) //Write data
{
PIR1.F3=0;
SSPBUF=hex;
while (PIR1.F3==0){}
}
char I2C_PreberiPodatek(void) //Read data
{
char _podatek;
PIR1.F3=0;
SSPCON2.F3=1;
while (PIR1.F3==0){}
_podatek=SSPBUF;
PIR1.F3=0;
SSPCON2.F4=1;
while (PIR1.F3==0){}
return _podatek;
}
void I2C_ZacniPosiljanje(unsigned int address) // Start send data
{
I2C_Zacni();
I2C_ZapisiPodatek(0xA0);
I2C_ZapisiPodatek(Hi(address));
I2C_ZapisiPodatek(Lo(address));
}
void I2C_ZacniBranje(unsigned int address) // Start read data
{
I2C_Zacni();
I2C_ZapisiPodatek(0xA0);
I2C_ZapisiPodatek(Hi(address));
I2C_ZapisiPodatek(Lo(address));
I2C_Obnovi();
I2C_ZapisiPodatek(0xA1);
SSPCON2.F5=1;
}
//****************************************************************************//
//**********************Main function for I2C*********************************//
void I2C_Zapisi(unsigned int addr, unsigned char pod) //Write
{
I2C_ZacniPosiljanje(addr);
I2C_ZapisiPodatek(pod);
I2C_Koncaj();
Delay_ms(5);
}
unsigned char I2C_Preberi(unsigned int addr) //Read
{
unsigned char podatek;
I2C_ZacniBranje(addr);
podatek=I2C_PreberiPodatek();
I2C_Koncaj();
return podatek;
}
Simple example:
Code: Select all
/***************************************
Project name: Test I2C
Done by: Jan & Jure Medvesek, 23.09.2005
Description:
Write some data to EEPROM 24FC512,
then reads it and displays it on PORTC.
A0,A1,A2--->connect to GND
Test configuration:
MCU: P18F2550
Dev.Board: EasyPIC3
Oscillator: XT, 48.0000MHz
Modules: EEPROM (24C512)
SW: mikroC v2.1
**************************************/
void main()
{
unsigned int addr=0;
unsigned char data=55;
ADCON1 = 0x0c; // Set pins as digital I/O
trisc = 0x00; // Set portc as outputs
trisb = 0x00; // Set portb as outputs
portb = 0;
latb = 0;
latc = 0;
I2CInit(); // I2C init
Delay_ms(1000);
I2C_Zapisi(addr,data); // Write data(55) to address(0)
data = 0;
data = I2C_Preberi(addr); // Read data(55) from address(0)
POTRC = data;
}
Jan