普通IO模拟i2c总线

2019-04-15 12:13发布

            相关文章:                  一 .   i2c总线协议                  二.   普通IO模拟i2c总线                  三.   简单i2c设备驱动实例   下面简单的单片机程序,理解之后会让你对I2c总线有更深的认识, 思路 1.向EEPROM中通过I2C总线写入一个字节 2.通过I2C总线读出写入的字节 3.如果写入和读出成功点亮发光二极管 运行结果:D1亮,     程序:   1 #include 2 3 #define uchar unsigned char 4 #define uint unsigned int 5 6 void init(); 7 void start(); 8 void stop(); 9 void write(uchar byte); 10 void write_add(uchar byte,uchar address);//向指定地址中写入字节 11 void delay1(uchar x); 12 uchar read_add(uchar address); 13 uchar read();//从指定地址中读出字节 14 15 void delay() 16 {;;} 17 18 sbit led = P0^0; 19 sbit sck = P2^0; 20 sbit sad = P2^1; 21 22 void main() 23 { 24 uchar test = 0; 25 init(); 26 write_add(0x01,0xaf); 27 delay1(100); 28 29 test =read_add(0xaf); 30 if(test == 0x01) 31 led = 0; 32 while(1); 33 } 34 35 void init() 36 { 37 sck = 1; 38 delay(); 39 sad = 1;//数据线和信号线都空闲 40 delay(); 41 led = 1; 42 } 43 //起始信号 44 void start() 45 { 46 sad = 1; 47 delay(); 48 sck = 1; 49 delay(); 50 sad = 0; 51 delay(); 52 } 53 //停止信号 54 void stop() 55 { 56 sad = 0; 57 delay(); 58 sck = 1; 59 delay(); 60 sad = 1; 61 delay(); 62 } 63 //等待回应 64 void response() 65 { 66 uchar i = 0; 67 sck = 1; 68 delay(); 69 while((sad == 1) && (i < 250)) 70 i++; 71 sck = 0; 72 delay(); 73 } 74 //向指定地址写入一个字节 75 void write(uchar byte) 76 { 77 uchar i = 0; 78 uchar temp = byte; 79 80 for(; i < 8; i++) 81 { 82 temp = temp << 1;//temp左移一位 83 sck = 0; 84 delay(); 85 sad = CY; 86 delay(); 87 sck = 1; 88 delay(); 89 } 90 sck = 0; 91 delay();//这样就不会产生开始信号或结束信号 92 sad = 1; 93 delay(); 94 } 95 //从指定地址读取一个字符 96 uchar read() 97 { 98 uchar i,k; 99 sck = 0; 100 delay(); 101 sad = 1; 102 delay(); 103 for(; i < 8; i++) 104 { 105 sck = 1; 106 delay(); 107 k = (k << 1) | sad; 108 sck = 0; 109 delay(); 110 } 111 return k; 112 } 113 //写入一个字节 114 void write_add(uchar byte,uchar address) 115 { 116 start(); 117 write(0xa0); 118 response(); 119 write(address); 120 response(); 121 write(byte); 122 response(); 123 stop(); 124 } 125 //读出写入的字节 126 uchar read_add(uchar address) 127 { 128 uchar result; 129 start(); 130 write(0xa0); 131 response(); 132 write(address); 133 response(); 134 start(); 135 write(0xa1); 136 response(); 137 result = read(); 138 stop(); 139 return result; 140 } 141 void delay1(uchar x) 142 { 143 uchar a,b; 144 for(a=x;a>0;a--) 145 for(b=100;b>0;b--); 146 }