#include "intrins.h" #include "comm.h"
#define uchar unsigned char #define uint unsigned int
#define OP_READ 0xa1 #define OP_WRITER 0xa0 extern void Delay(unsigned int n); sbit SDA_24CXX =P2^5; sbit SCL_24CXX =P2^6;
void start_i2c(void) { SDA_24CXX = 1; SCL_24CXX = 1; _nop_(); _nop_(); SDA_24CXX = 0; _nop_(); _nop_(); SCL_24CXX = 0; } void stop_i2c(void) { SDA_24CXX = 0; SCL_24CXX = 1; _nop_(); _nop_(); SDA_24CXX = 1; _nop_(); _nop_(); _nop_(); _nop_(); _nop_(); _nop_(); _nop_(); _nop_();
}
bit send_byte_24cxx(uchar str) { uchar BitCnt; uchar ack;
for(BitCnt=0;BitCnt<8;BitCnt++) { if((str<<BitCnt)&0x80) SDA_24CXX = 1; else SDA_24CXX = 0; SCL_24CXX = 1; _nop_(); _nop_(); _nop_(); _nop_(); SCL_24CXX = 0; } SDA_24CXX = 1;
SCL_24CXX = 1; _nop_(); _nop_(); _nop_(); _nop_(); ack = SDA_24CXX; SCL_24CXX = 0; return ack; }
uchar rcv_byte_24cxx(void) { uchar retc; uchar BitCnt; retc=0; SDA_24CXX = 1; for(BitCnt=0;BitCnt<8;BitCnt++) { SCL_24CXX = 0; _nop_(); _nop_(); _nop_(); _nop_(); SCL_24CXX = 1; retc=retc<<1; if(SDA_24CXX == 1)retc=retc+1; } SCL_24CXX = 0; return(retc); }
void ack_i2c(bit a) { if(a==0)SDA_24CXX = 0; else SDA_24CXX = 1; SCL_24CXX = 1; _nop_(); _nop_(); _nop_(); _nop_(); SCL_24CXX = 0; }
unsigned char read_byte(unsigned char add) {uchar temp; start_i2c(); if(send_byte_24cxx(OP_WRITER) != 0) return 0; if(send_byte_24cxx(add) != 0) return 0; start_i2c(); if(send_byte_24cxx(OP_READ) != 0) return 0; temp = rcv_byte_24cxx();
ack_i2c(1); stop_i2c();
return temp; }
unsigned char write_byte(unsigned char add,unsigned char str) { start_i2c(); if(send_byte_24cxx(OP_WRITER) != 0) return 1; if(send_byte_24cxx(add) != 0) return 1; if(send_byte_24cxx(str) != 0) return 1; stop_i2c(); return 0; }
|