www.pudn.com > EEPROM__430C.zip > EEPROM__430C.txt, change:2013-08-19,size:2926b


#include"msp430g2553.h" 
#include"intrinsics.h" 
 
#define uchar unsigned char 
#define uint unsigned short int 
 
#define I2C_SDAHI P2OUT|=BIT0 
#define I2C_SDALO P2OUT&=~BIT0 
#define I2C_SCLHI P2OUT|=BIT1 
#define I2C_SCLLO P2OUT&=~BIT1 
 
unsigned char aa[2]={0x01,0x01}; 
unsigned char bb[2]={0,0}; 
 
uchar ACK=1; 
 
void delay_nus(unsigned int n)       //n us延时函数,误差0.5us左右,如n=5时,延时5.46us;注意n>=3 
{ 
    unsigned int i; 
    for(i=2;i<n;i++)                              //注意并非从i=0开始,已经调试 
	__delay_cycles(8); 
} 
void delay_nms(unsigned int n) 
{ 
    unsigned int i; 
    for (i=0;i<n;i++) 
    __delay_cycles(8000); 
} 
 
uchar i2c_start() 
{ 
	delay_nus(10); 
	I2C_SCLHI; 
	delay_nus(10); 
	I2C_SDAHI; 
	delay_nus(15); 
	I2C_SDALO; 
	delay_nus(10); 
	I2C_SCLLO; 
	delay_nus(10); 
	return 1; 
} 
 
void i2c_stop() 
{ 
	delay_nus(10); 
	I2C_SDALO; 
	delay_nus(10); 
	I2C_SCLHI; 
	delay_nus(10); 
	I2C_SDAHI; 
} 
 
void i2c_sentbyte(uchar byt) 
{ 
	uchar i; 
	for(i=0;i<8;i++) 
	{ 
		delay_nus(6); 
		if(byt&0x80) 
		{ 
			I2C_SDAHI; 
		} 
		else 
		{ 
			I2C_SDALO; 
		} 
		delay_nus(6); 
		I2C_SCLHI; 
		delay_nus(6); 
		I2C_SCLLO; 
		byt<<=1; 
	} 
	delay_nus(5); 
	I2C_SDAHI; 
	delay_nus(10); 
	I2C_SCLHI; 
	delay_nus(10); 
	I2C_SCLLO; 
} 
 
uchar i2c_rcvbyte(uchar ack_chack) 
{ 
	uchar i, temp=0; 
	delay_nus(5); 
	I2C_SDAHI;          //拉高了数据线 
	P2DIR&=~BIT0;       //最低位改为输入模式 
	delay_nus(5); 
	for(i=0;i<8;i++) 
	{ 
		temp<<=1; 
		delay_nus(5); 
		I2C_SCLHI; 
		delay_nus(5); 
		if(P2IN&0x01)temp++; 
		I2C_SCLLO; 
	} 
	delay_nus(5); 
	P2DIR|=BIT0; 
	delay_nus(5); 
	I2C_SDAHI; 
	if(ack_chack) 
	{ 
		I2C_SDALO; 
	} 
	delay_nus(5); 
	I2C_SCLHI; 
	delay_nus(5); 
	I2C_SCLLO; 
	return (temp); 
} 
void at24c64_wr(uchar *dat,unsigned long int address,uint cont) 
{ 
	if(cont!=0) 
	{ 
		i2c_start(); 
		i2c_sentbyte(0xa0); 
		i2c_sentbyte(address / 0x100); 
		i2c_sentbyte(address % 0x100); 
 
		while(cont--) 
		{ 
			i2c_sentbyte(*dat); 
			dat++; 
			address++; 
			if(!(address&0x001f)&&(cont!=0)) 
			{ 
				i2c_stop(); 
				delay_nms(10); 
				i2c_start(); 
				i2c_sentbyte(0xa0); 
				i2c_sentbyte(address / 0x100); 
				i2c_sentbyte(address % 0x100); 
			} 
		} 
		i2c_stop(); 
		delay_nms(10); 
	} 
} 
void at24c64_rd(uchar *dat,unsigned long int address,uint cont) 
{ 
	if(cont!=0) 
	{ 
		 i2c_start(); 
		 i2c_sentbyte(0xa0); 
		 i2c_sentbyte(address / 0x100); 
		 i2c_sentbyte(address % 0x100); 
		 i2c_start(); 
		 i2c_sentbyte(0xa1); 
		 cont--; 
		 while(cont--) 
		 { 
			 *dat=i2c_rcvbyte(1); 
			 dat++; 
		 } 
		 *dat=i2c_rcvbyte(0); 
		 i2c_stop(); 
	} 
} 
 
 
 
void main(void) 
{ 
	WDTCTL = WDTPW + WDTHOLD;            //关闭看门狗 
	BCSCTL1 = CALBC1_1MHZ;               // 主时钟设置为1M 
	DCOCTL = CALDCO_1MHZ; 
	BCSCTL2 &= ~(DIVS_3); 
	P2DIR|=0x03; 
 
 
	at24c64_wr(aa, 0x2222, 2); 
	at24c64_rd(bb, 0x2222, 2); 
	P1DIR=0xff; 
	P1OUT=bb[1]; 
 
}