www.pudn.com > e041tcpipc51.rar > 24c02.c


#include 
#include 
// ¶Ô24C02µÄ¶Á¡¢Ð´
// extern void read24c02(unsigned char *RamAddress,unsigned char RomAddress,unsigned char bytes);
// extern void write24c02(unsigned char *RamAddress,unsigned char RomAddress,unsigned char bytes);

/***************for 24c02************************************************************/
#define	WriteDeviceAddress 0xa0
#define	ReadDviceAddress 0xa1
#define NOP5() _nop_();_nop_();_nop_();_nop_();_nop_()
/***************************************************************************/
sbit	SCL=P1^6;
sbit	SDA=P1^7;
/***************************************************************************/
void delay_ms(unsigned char number);	
/***************************************************************************/
void Start() {
	SDA=1;
	NOP5();
	SCL=1;
	NOP5();
	SDA=0;
	NOP5();
	SCL=0;
	NOP5();
}

/***************************************************************************/
void Stop() {
	SDA=0;
	NOP5();
	SCL=1;
	NOP5();
	SDA=1;
	NOP5();
	SCL=0;
	NOP5();
}

/***************************************************************************/
void Ack() {
	SDA=0;
	NOP5();
	SCL=1;
	NOP5();
	SCL=0;
	NOP5();
	SDA=1;
}

/***************************************************************************/
void NoAck()
{
	SDA=1;
	NOP5();
	SCL=1;
	NOP5();
	SCL=0;
	NOP5();
}

/***************************************************************************/
bit TestAck(void) {
	bit ErrorBit;
	SDA=1;
	NOP5();
	SCL=1;
	NOP5();
	ErrorBit=SDA;
	NOP5();
	SCL=0;
	return(ErrorBit);
}

/***************************************************************************/
void Write8Bit(unsigned char input) {
	unsigned char temp;
	for(temp=8;temp!=0;temp--) {
		SDA=(bit)(input&0x80);
		NOP5();
		SCL=1;
		NOP5();
		SCL=0;
		NOP5();
		input=input<<1;
	}
}

/***************************************************************************/

void write24c02(unsigned char *Wdata,unsigned char RomAddress,unsigned char number) {
	Start();
	Write8Bit(WriteDeviceAddress);
	TestAck();
	Write8Bit(RomAddress);
	TestAck();
	for(;number!=0;number--) {
		Write8Bit(*Wdata);
		TestAck();
		Wdata++;
	}
	Stop();
	delay_ms(10);
}

/***************************************************************************/
unsigned char Read8Bit() {
	unsigned char temp,rbyte=0;
	for(temp=8;temp!=0;temp--) {
		SCL=1;
		rbyte=rbyte<<1;
		rbyte=rbyte|((unsigned char)(SDA));
		SCL=0;
	}
	return(rbyte);
}

/***************************************************************************/
void read24c02(unsigned char *RamAddress,unsigned char RomAddress,unsigned char bytes) {
	Start();
	Write8Bit(WriteDeviceAddress);
	TestAck();
	Write8Bit(RomAddress);
	TestAck();
	Start();
	Write8Bit(ReadDviceAddress);
	TestAck();
	while(bytes!=1) {
	*RamAddress=Read8Bit();
	Ack();
	RamAddress++;
	bytes--;
	}
	*RamAddress=Read8Bit();
	NoAck();
	Stop();
}

/***************************************************************************/