MSP430F149模拟IIC读写24C02程序
扫描二维码
随时随地手机看文章
板子上设置了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"//实际上需要包含延时#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起始状态*/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停止状态*/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写字节*/voidiic_write(unsignedchardata){SDA_OUT;unsignedchari,temp;for(i=0;i<8;i++){SDA_OUT;temp=data&0x80;if(temp==0x80)SDA_1;//判断发送位,送数据到数据线上elseSDA_0;delay_us(10);SCL_1;//置时钟信号为高电平,使数据有效delay_us(5);SCL_0;delay_us(10);data=data<<1;}SDA_IN;delay_us(5);}/**IIC读字节*/unsignedchariic_read(void){unsignedchari,tmp;unsignedcharbyte=0;SDA_IN;//置数为输入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写数据*输入:start_addr起始地址*n_bytes写入字节数*dest_date写入的数据源*输出:无*/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