24C02读写练习详细(C语言新手细看)#includereg51.h#includeintrins.h#defineOP_READ0xa1//器件地址以及读取操作#defineOP_WRITE0xa0//器件地址以及写入操作#defineMAX_ADDR0x7f//AT24C02最大地址unsignedcharcodedis_code[]={0x7e,0xbd,0xdb,0xe7,0xdb,0xbd,0x7e,0xff};//写入到AT24C01的数据串sbitSDA=P3^4;sbitSCL=P3^3;voidstart();voidstop();unsignedcharshin();bitshout(unsignedcharwrite_data);unsignedcharread_random(unsignedcharrandom_addr);voidwrite_byte(unsignedcharaddr,unsignedcharwrite_data);voidfill_byte(unsignedcharfill_data);voiddelayms(unsignedcharms);main(void){unsignedchari;SDA=1;SCL=1;fill_byte(0xff);//全部填充0xfffor(i=0;i8;i++)//写入显示代码到AT24Cxx{write_byte(i,dis_code[i]);}i=0;while(1){P0=read_random(i);//循环读取24Cxx内容,并输出到P0口i++;i&=0x07;//循环读取范围为0x00~0x07delayms(250);}}voidstart()//开始位{SDA=1;SCL=1;_nop_();_nop_();SDA=0;_nop_();_nop_();_nop_();_nop_();SCL=0;}voidstop()//停止位{SDA=0;_nop_();_nop_();SCL=1;_nop_();_nop_();_nop_();_nop_();SDA=1;}unsignedcharshin()//从AT24Cxx移入数据到MCU{unsignedchari,read_data;for(i=0;i8;i++){SCL=1;read_data=1;read_data|=(unsignedchar)SDA;SCL=0;}return(read_data);}bitshout(unsignedcharwrite_data)//从MCU移出数据到AT24Cxx{unsignedchari;bitack_bit;for(i=0;i8;i++)//循环移入8个位{SDA=(bit)(write_data&0x80);_nop_();SCL=1;_nop_();_nop_();SCL=0;write_data=1;}SDA=1;//读取应答_nop_();_nop_();SCL=1;_nop_();_nop_();_nop_();_nop_();ack_bit=SDA;SCL=0;returnack_bit;//返回AT24Cxx应答位}voidwrite_byte(unsignedcharaddr,unsignedcharwrite_data)//在指定地址addr处写入数据write_data{start();shout(OP_WRITE);shout(addr);shout(write_data);stop();delayms(10);//写入周期}voidfill_byte(unsignedcharfill_data)//填充数据fill_data到EEPROM内{unsignedchari;for(i=0;iMAX_ADDR;i++){write_byte(i,fill_data);}}unsignedcharread_current()//在当前地址读取{unsignedcharread_data;start();shout(OP_READ);read_data=shin();stop();returnread_data;}unsignedcharread_random(unsignedcharrandom_addr)//在指定地址读取{start();shout(OP_WRITE);shout(random_addr);return(read_current());}voiddelayms(unsignedcharms)//延时子程序{unsignedchari;while(ms--){for(i=0;i120;i++);}}