|
#define uchar unsigned char #define addr_x 0xae // 寫(xiě) #define addr_d 0xaf // 讀 sbit sda = P2^1; //數(shù)據(jù)管腳 sbit scl = P2^0; //時(shí)鐘管腳 bit ack; void DelayUs2x(unsigned char t) //延時(shí)1 { while(--t); } void DelayMs(unsigned char t) //延時(shí)2 { while(t--) { //大致延時(shí)1mS DelayUs2x(245); DelayUs2x(245); } } void delay() //延時(shí)大于4μs {;;} void i2_qs() //起始信號(hào) { sda = 1; //拉高數(shù)據(jù) scl = 1; //拉高時(shí)鐘 delay(); //延時(shí)大于 4μs sda = 0; //拉低數(shù)據(jù)產(chǎn)生起始信號(hào)(下降沿) delay(); //延時(shí)大于 4μs scl = 0; //拉低時(shí)鐘 delay(); //延時(shí)大于 4μs } void i2_tz() //停止信號(hào) { sda = 0; //拉低數(shù)據(jù) scl = 1; //拉高時(shí)鐘 delay(); //延時(shí)大于 4μs sda = 1; //拉高時(shí)鐘產(chǎn)生結(jié)束信號(hào)(上升沿) delay(); //延時(shí)大于 4μs } void i2_ack(bit _ack) //入口產(chǎn)生 0 ack 1 nak { sda = _ack; //ack或者nak scl = 1; //拉高時(shí)鐘 delay(); //延時(shí)大于 4μs scl = 0; //拉低時(shí)鐘 delay(); //延時(shí)大于 4μs } void i2_fs(uchar Data) //發(fā)送8位數(shù)據(jù) { uchar i; for(i=0;i<8;i++) //8位計(jì)數(shù) { Data <<= 1; //把最高位移送到進(jìn)制標(biāo)志位中(CY) sda = CY; //把進(jìn)制位中的數(shù)據(jù)賦值給數(shù)據(jù)線 scl = 1; //拉高時(shí)鐘 delay(); //延時(shí)大于 4μs scl = 0; //拉低時(shí)鐘 //這里 } //下面代碼是接收ACK的代碼 delay();//延時(shí)大于 4μs sda = 1; //拉高數(shù)據(jù)準(zhǔn)備接收ACK scl = 1; //拉高時(shí)鐘產(chǎn)生穩(wěn)定的有效的數(shù)據(jù)(相對(duì)的) if(sda==1) //確認(rèn)接收的是ACK還是NAK ack = 0;//ack else ack = 1;//nak scl = 0; //拉低時(shí)鐘 delay(); //延時(shí)大于 4us } uchar i2_js() //接收8位數(shù)據(jù) { uchar i,Data = 0; sda = 1; //使能內(nèi)部上拉,準(zhǔn)備讀取數(shù)據(jù) for(i=0;i<8;i++) //8位計(jì)數(shù)器 { Data <<= 1; //移出數(shù)據(jù)的最高位 scl = 1; //拉高時(shí)鐘 delay(); //延時(shí)大于 4us Data |= sda;//接收數(shù)據(jù) scl = 0; //拉低時(shí)鐘 delay(); //延時(shí)大于 4us } return Data; } void i2_sj_x(uchar addr,uchar Data) //往設(shè)備內(nèi)寫(xiě)入數(shù)據(jù)(參數(shù) 1、寄存器地址 2、寫(xiě)入的數(shù)據(jù)) { i2_qs(); //起始信號(hào) i2_fs(addr_x); //設(shè)備地址+寫(xiě)信號(hào) i2_fs(addr); //寄存器內(nèi)部地址 i2_fs(Data); //寫(xiě)入設(shè)備的數(shù)據(jù) i2_tz(); //停止信號(hào) } uchar i2_sj_d(uchar addr) //讀取數(shù)據(jù)(參數(shù) 寄存器地址) { uchar Data; i2_qs(); //起始信號(hào) i2_fs(addr_x); //設(shè)備地址+寫(xiě)信號(hào) i2_fs(addr); //寄存器內(nèi)部地址 i2_qs(); //起始信號(hào) i2_fs(addr_d); //設(shè)備地址+讀信號(hào) Data = i2_js(); //讀取數(shù)據(jù) i2_ack(0); //ACK應(yīng)答 i2_tz(); //停止信號(hào) return Data; //返回讀取的數(shù)據(jù) } void main(void) { uchar dat; i2_sj_x(3,0x0f); //數(shù)據(jù)寫(xiě)入24c02 DelayMs(50); dat = i2_sj_d(3); //從24c02中讀取數(shù)據(jù) P1 = dat; //使用8個(gè)LED顯示讀出的數(shù)據(jù) while(1) { ; } } 以上代碼只是簡(jiǎn)單的實(shí)現(xiàn)I2C總線的讀寫(xiě)
|
|
|
來(lái)自: 月光下的幽會(huì) > 《單片機(jī)》