#include "IO.H"
/* #define WRITE 0xA0 ; */
/* #define READ 0xA1 ; */
/* **************************/ void delay ( unsigned int timeM )
{ unsigned int con1;
TH0 = 0x06 ;
TL0 = 0x06 ;
TMOD = 0x02 ;
TF0 = 0 ;
TR0 = 1 ;
for ( ; timeM > 0 ; timeM-- )
{ for ( con1=4 ; con1>0 ; )
if ( TF0 ) { con1-- ;
TF0 = 0;
}
}
}
/* I2C Start */
void startI2C ( void )
{ SDAT = 1 ,SCLK = 1 ;
someNOP() ;
SDAT = 0 ;
someNOP() ;
SCLK = 0 ;
return ; }
/* stop */
void stopI2C ( void )
{ SDAT = 0 ,SCLK = 1 ;
someNOP() ;
SDAT = 1 ;
someNOP() ;
return ;
}
/* answer */
void ackI2C ( bit answer)
{ if ( answer == 0 ) SDAT = 0 ;
else SDAT = 1 ;
SCLK = 1 ; someNOP() ; SCLK = 0 ; return ;
}
/* test ack */
bit testack ( void )
{ bit ack ;
SDAT = 1 ;
SCLK = 1 ;
_nop_() ;
_nop_() ;
if ( SDAT == 1 ) ack = 0 ;
else ack = 1 ;
SCLK = 0 ;
_nop_() ;
_nop_() ;
return ( ack ) ;
}
/* send byte */
void senddata ( unsigned char sdata )
{ unsigned char bitcount ; for ( bitcount = 0 ; bitcount < 8 ; bitcount ++ ) { if ( sdata << bitcount & 0x80 ) SDAT = 1 ; else SDAT = 0 ;
SCLK = 1 ;
someNOP() ;
SCLK = 0 ;
}
return ;
}
/* receive byte */
unsigned char receivedata ()
{ unsigned char bitcount , rdata = 0 ;
for ( bitcount = 0 ; bitcount < 8 ; bitcount ++ ) { SCLK = 0 ; someNOP() ;
SCLK = 1 ;
_nop_() ;
_nop_() ;
if ( SDAT == 1 ) rdata = ( rdata << 1 ) + 1 ;
else rdata <<= 1 ;
_nop_() ;
_nop_() ;
SCLK = 0 ;
}
return ( ( unsigned char ) rdata ) ;
}
/* read data */
void Rreceivedata ( unsigned char headadd , unsigned char N , unsigned char *buf )
{ startI2C () ;
senddata ( 0xa0 ) ;
testack () ; senddata ( headadd ) ;
testack () ;
startI2C () ;
senddata ( 0xa1 ) ;
testack () ;
for ( ; N != 0 ; N -- ) { *buf = receivedata () ;
buf ++ ;
ackI2C ( 0 ) ;
}
ackI2C ( 1 ) ;
stopI2C () ;
return ; }
/* write data */
void Wsenddata ( unsigned char headadd , unsigned char N , unsigned char *buf ) { startI2C () ;
senddata ( 0xa0 ) ;
testack () ;
senddata ( headadd ) ;
testack () ;
for ( ; N != 0 ; N ++ ) { senddata ( *buf ) ;
while ( testack () == 0 )
{ ; }
buf ++ ;
}
stopI2C () ;
delay ( 10 ) ;
return ;
} |