#include <iom128v.h>
#include <macros.h>
#define uchar unsigned char
#define uint unsigned int
#define START 0x08
#define RE_START 0x10
#define SLA_W_ACK 0x18
#define SLA_W_NACK 0x20
#define DATA_W_ACK 0x28
#define DATA_W_NACK 0x30
#define SLA_R_ACK 0x40
#define SLA_R_NACK 0x48
#define TM_Start() {TWCR=(1<<TWINT)|(1<<TWSTA)|(1<<TWEN);}
#define TM_ReStart() {TWCR=(1<<TWINT)|(1<<TWSTA)|(1<<TWEN);}
#define TM_WriteByte() {TWCR=(1<<TWINT)|(1<<TWEN);}
#define TM_Stop() {TWCR=(1<<TWINT)|(1<<TWEN)|(1<<TWSTO);}
static uchar tab[]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f};
uchar *p=tab;
volatile uint ct,ct1;
volatile uint i,j,k;
void delay_us()
{
for(i=32;i>0;i--){;}
}
void delay_ms()
{
for(k=1000;k>0;k--)
for(j=1000;j>0;j--){;}
}
unsigned char IICWriteOne(unsigned char DevSel,unsigned char Addr,unsigned char *Data)
{
TM_Start();
delay_us();
while(TWCR!=0xA4);
if(TWSR!=0x08)
{
return 0;
}
TWDR=DevSel&0xFE;
TM_WriteByte();
delay_us();
while(TWCR!=0x84);
if(TWSR!=0x18)
{
return 0;
}
TWDR=Addr;
TM_WriteByte();
delay_us();
while(TWCR!=0x84);
if(TWSR!=0x28)
{
return 0;
}
for(ct=10;ct>0;ct--)
{
TWDR=*Data;
TM_WriteByte();
delay_us();
while(TWCR!=0x84);
if(TWSR!=0x28)
{
return 0;
}
Data++;
}
TM_Stop();
return 1;
}
unsigned char IICReadOne(unsigned char DevSel,unsigned char Addr)
{
unsigned char retdata;
TM_Start();
delay_us();
while(TWCR!=0xA4);
if(TWSR!=0x08)
{
return 0;
}
TWDR=DevSel&0xFE;
TM_WriteByte();
delay_us();
while(TWCR!=0x84);
if(TWSR!=0x18)
{
return 0;
}
TWDR=Addr;
TM_WriteByte();
delay_us();
while(TWCR!=0x84);
if(TWSR!=0x28)
{
return 0;
}
TM_ReStart();
delay_us();
while(TWCR!=0xA4);
if(TWSR!=0x10)
{
return 0;
}
TWDR=DevSel|0x01;
TM_WriteByte();
delay_us();
while(TWCR!=0x84);
if(TWSR!=0x40)
{
return 0;
}
// for(ct1=3;ct1>0;ct1--)
{
TM_WriteByte();
delay_us();
while(TWCR!=0x84);
if(TWSR!=0x58)
{
return 0;
}
retdata=TWDR;
}
TM_Stop();
return retdata;
}
void IICInit(unsigned char rate,unsigned char mul)
{
TWBR=rate;
TWSR&=~0x03;
TWSR|=(mul&0x03);
}
void main()
{
DDRB=0xff;
DDRA=0xff;
DDRC=0xff;
PORTC=0xfe;
IICInit(0x00,0x00);
IICWriteOne(0xA2,0x04,tab);
delay_ms();
PORTA=IICReadOne(0xA2,0x05);
while(1)
{
;
}
}