/script>/******************************************************************* 公司名稱(chēng): 模塊名稱(chēng):IIC.c 功 能 IIC驅(qū)動(dòng)模塊 芯片型號(hào):24C01 說(shuō) 明:隨機(jī)連續(xù)讀寫(xiě)iic 程序設(shè)計(jì):FANZENGTING 設(shè)計(jì)時(shí)間:2004.10.30 版 本 號(hào): 20041030 *******************************************************************/ #define SDA RC4 #define SCL RC3 #define SDA_IO TRISC4 #define SCL_IO TRISC3 #define no_ask 10/*無(wú)應(yīng)答超時(shí)時(shí)間*/ unsigned char write[5];/*待寫(xiě)入數(shù)緩存*/ unsigned char read[5];/*讀出數(shù)緩存*/ bit err_flag;/*iic工作是否正常標(biāo)志(為1不正常;為0正常)*/ void iic_read(unsigned char start_address,unsigned char count); void iic_write(unsigned char start_address,unsigned char count); /************************************************* start_address 需操作iic的首地址 count 需讀寫(xiě)個(gè)數(shù) **************************************************/ void dlay(void) { #asm nop; nop; nop; nop; #endasm } /*************************************************/ void tx(unsigned char k)/*向iic里寫(xiě)數(shù)據(jù)*/ { unsigned char temp=8,err_count=0; while(temp--) { SCL_IO=0; SDA_IO=0; dlay( ); if((k&0b10000000)) { SDA=1; } else { SDA=0; } SCL=1; dlay( ); SCL=0; k<<=1; } SCL=1; SDA_IO=1; while(SDA)/*ASK*/ { dlay( ); SCL=0; dlay( ); SCL=1; dlay( ); err_count++; if(err_count>no_ask) { err_flag=1;/*無(wú)應(yīng)答超時(shí)*/ return; } } SCL=0; } /*************************************************/ void start(void)/*啟動(dòng)iic*/ { SCL_IO=0; SDA_IO=0; dlay( ); SDA=1; SCL=1; dlay( ); SDA=0; dlay( ); SCL=0; return; } /*************************************************/ void stop(void)/*停止iic*/ { dlay( ); SCL_IO=0; SDA_IO=0; dlay( ); SDA=0; SCL=1; dlay( ); SDA=1; dlay( ); SCL=0; return; } /*************************************************/ unsigned char rx(void)/*從iic里讀出數(shù)據(jù)*/ { unsigned char temp=8,buf; SDA_IO=1; dlay( ); while(temp--) { SCL=1; buf=(buf<<1)|SDA; SCL=0; } return(buf); } /*************************************************/ void iic_write(unsigned char start_address,unsigned char count) { err_flag=0; start( ); tx(0xa0); tx(start_address); while(count--) { tx(write[count]); } stop( ); } /*************************************************/ void iic_read(unsigned char start_address,unsigned char count) { err_flag=0; start( ); tx(0xa0); tx(start_address); start( ); tx(0xa1); while(count--) { read[count]=rx( ); SCL_IO=0; SDA_IO=0; dlay( ); SDA=0; dlay( ); SCL=1; dlay( ); SCL=0; } read[count]=rx( );/*再讀一次以便停止*/ dlay( ); SDA=1; SCL=0; dlay( ); SCL=1; stop( ); } /****************************************************************/ //void main( ) //{ //while(1) //{ //iic_write(0,5);/*首地址為0;連續(xù)寫(xiě)入5個(gè)數(shù)*/ //dlay_task( );/*兩次操作iic之間必須要有一段延時(shí)*/ //iic_read(0,5);/*首地址為0;連續(xù)讀出5個(gè)數(shù)*/ //dlay_task( ); //if(err_flag) //{ //err_task( );/*出錯(cuò)處理*/ //} //} //} /****************************************************************/ |
|