#include<lpc214x.h>
#include "i2c.h"
unsigned char status;
unsigned char flag;
unsigned char data;
void delay(unsigned char msec)
{
int i,j;
for(i=0;i<10000;i++)
for(j=0;j<msec;j++);
}
void start()
{
I2C0CONSET=0x20;
}
void stop()
{
I2C0CONSET=0x10;
}
unsigned char state(unsigned char number)
{
while(flag==0);
flag=0;
//txu0(status);
if(status!=number)
{
return 1;
}
else
{
return 0;
}
}void inituart()
{
U0LCR=0x83;
U0DLL=0x61;
U0DLM=0x00;
U0LCR=0x03;
}
void txu0(unsigned char a) //Transmit a byte of data through UART1
{
while(!(U0LSR & 0x20)); // Wait until UART1 ready to send character
U0THR = a;
}
void str(unsigned char *p)
{
while(1)
{
if(*p=='\0') break;
txu0(*p++);
}
}
void __irq intt(void)
{
flag=0xFF; //update status flag
status=I2C0STAT; //Read Status byte
I2C0CONCLR=0x28;
VICVectAddr = 0x00; //Acknowledge Interrupt
}
void initi2c()
{
PINSEL0&=0xFFFFFF0F;
PINSEL0|=0x00000050;
I2C0CONCLR=0x6C;
I2C0CONSET=0x40;
I2C0SCLH=80;
I2C0SCLL=70;
VICIntSelect = 0x00000000; // Setting all interrupts as IRQ(Vectored)
VICVectCntl1 = 0x20 | 9; // Assigning Highest Priority Slot to I2C0 and enabling this slot
VICVectAddr1 = (unsigned long)intt; // Storing vector address of I2C0
VICIntEnable = (1<<9);
}
unsigned char read(unsigned char place1)
{
start();
if(state(0x08))
{
str("08 fail");
return 1;
}
I2C0DAT=0x38;
if(state(0x18))
{
str("18 fail");
return 1;
}
I2C0DAT=place1;
if(state(0x28))
{
str("register fail");
return 1;
}
start();
if(state(0x10))
{
str("repeated start");
return 1;
}
I2C0DAT=0x39;
if(state(0x40))
{
str("SLA+R");
return 1;
}
I2C0CONCLR=0x04;
if(state(0x58))
{
str("58 fail");
return 1;
}
data=I2C0DAT;
stop();
return 0;
}
unsigned char write(unsigned char place,unsigned char text)
{
start();
if(state(0x08))
{
return 1;
}
I2C0DAT=0x38;
if(state(0x18))
{
str("18 fail");
txu0(status);
return 1;
}
I2C0DAT=place;
if(state(0x28))
{
return 1;
}
I2C0DAT=text;
if(state(0x28))
{
return 1;
}
stop();
return 0;
}
void i2cperform()
{
PINSEL0|=0x00000005;
PINSEL1|= 0x20000000;
PINSEL2|=0x00000000;
inituart();
initi2c();
write(0x2A,0x18);
write(0x15,0x78);
write(0x17,0x15);
write(0x18,0x0A);
write(0x2D,0x04);
write(0x2E,0x04);
data=read(0x2A);
data|=0x01;
write(0x2A,data);
}