板子上設置了EEPROM存儲器,型號為AT24C02。
板子的硬件連接為:SCL--->P2.4,SDA--->P2.5。
直接了當,貼上程序!
========================24cxx.h文件=========================#ifndef_24CXX_H_#define_24CXX_H_#include#defineWRITE_ADDR0xA0//A0A1A2均接地#defineREAD_ADDR0xA1//A0A1A2均接地#defineSDA_BITBIT5#defineSCL_BITBIT4#defineIIC_PORT_DIRP2DIR#defineIIC_PORT_DATAP2OUT#defineSDA_BIT_DATA(P2IN&BIT5)#defineSDA_OUT(IIC_PORT_DIR|=SDA_BIT)#defineSDA_IN(IIC_PORT_DIR&=~SDA_BIT)#defineSDA_1(IIC_PORT_DATA|=SDA_BIT)#defineSDA_0(IIC_PORT_DATA&=~SDA_BIT)#defineSCL_IN(IIC_PORT_DIR&=~SCL_BIT)#defineSCL_OUT(IIC_PORT_DIR|=SCL_BIT)#defineSCL_1(IIC_PORT_DATA|=SCL_BIT)#defineSCL_0(IIC_PORT_DATA&=~SCL_BIT)voidinit_iic(void);voidiic_start(void);voidiic_stop(void);voidiic_ack(void);voidiic_no_ack(void);unsignedchariic_test_ack(void);voidiic_write(unsignedchardata);unsignedchariic_read(void);unsignedchariic_write_data(unsignedcharStartAddress,unsignedchar*date,unsignedcharbytes);unsignedchariic_read_data(unsignedcharStartAddress,unsignedchar*date,unsignedcharbytes);#endif
========================24cxx.c文件=========================#include"24cxx.h"#include"main.h"http://實際上需要包含延時#defineCPU_F((double)8000000)//#definedelay_us(x)__delay_cycles((long)(CPU_F*(double)x/1000000.0))//#definedelay_ms(x)__delay_cycles((long)(CPU_F*(double)x/1000.0))/**IIC端口初始化*/voidinit_iic(void){SCL_OUT;//SCL管腳為輸出SDA_IN;//SDA管腳為輸入SCL_0;iic_stop();}/**IIC起始狀態(tài)*/voidiic_start(void){SDA_OUT;SDA_1;delay_us(5);SCL_1;delay_us(5);SDA_0;delay_us(5);SCL_0;delay_us(5);}/**IIC停止狀態(tài)*/voidiic_stop(void){SDA_OUT;SCL_0;delay_us(5);SDA_0;delay_us(5);SCL_1;delay_us(5);SDA_1;delay_us(5);}/**IIC應答*/voidiic_ack(void){SDA_OUT;SDA_0;delay_us(5);SCL_1;delay_us(5);SCL_0;delay_us(5);SDA_1;}/**IIC無應答*/voidiic_no_ack(void){SDA_OUT;SDA_1;delay_us(5);SCL_1;delay_us(5);SCL_0;delay_us(5);}/**IIC檢測回應*/unsignedchariic_test_ack(void){unsignedchartmp;SDA_IN;//設為輸入delay_us(5);SCL_1;delay_us(5);tmp=SDA_BIT_DATA>>4;delay_us(5);SCL_0;delay_us(5);return(tmp);}/**IIC寫字節(jié)*/voidiic_write(unsignedchardata){SDA_OUT;unsignedchari,temp;for(i=0;i<8;i++){SDA_OUT;temp=data&0x80;if(temp==0x80)SDA_1;//判斷發(fā)送位,送數(shù)據(jù)到數(shù)據(jù)線上elseSDA_0;delay_us(10);SCL_1;//置時鐘信號為高電平,使數(shù)據(jù)有效delay_us(5);SCL_0;delay_us(10);data=data<<1;}SDA_IN;delay_us(5);}/**IIC讀字節(jié)*/unsignedchariic_read(void){unsignedchari,tmp;unsignedcharbyte=0;SDA_IN;//置數(shù)為輸入for(i=0;i<8;i++){SCL_1;delay_us(5);byte=byte<<1;SDA_IN;tmp=SDA_BIT_DATA;if(tmp==SDA_BIT)byte=(byte|0x01);delay_us(10);SCL_0;delay_us(10);}return(byte);}/**IIC寫數(shù)據(jù)*輸入:start_addr起始地址*n_bytes寫入字節(jié)數(shù)*dest_date寫入的數(shù)據(jù)源*輸出:無*/unsignedchariic_write_data(unsignedcharstart_addr,unsignedchar*dest_date,unsignedcharn_bytes){unsignedchari=0;iic_start();//啟動IICiic_write(WRITE_ADDR);//寫24C02地址以if(iic_test_ack()!=0)//檢測應答return1;iic_write(start_addr);//寫對24C02操作的地址if(iic_test_ack()!=0)return1;for(i=0;i