I2C簡單例程
軟件: a. Keil uVision3.0; b. Easy 51Pro v2.0;
實(shí)驗(yàn)電路原理圖:
從原理圖可看出,這次實(shí)驗(yàn)在原51最小系統(tǒng)上擴(kuò)展,通過引腳P0^0,P0^1分別控制AT24C01的兩引腳SCL,SDA。圖左邊加個(gè)4路撥碼開關(guān)可以動(dòng)態(tài)改變AT24C01器件地址和寫保護(hù)WP狀態(tài)。 實(shí)驗(yàn)以路撥碼開關(guān)打開,即A0,A1,A3,WP都為0為例. 測試成功源代碼: 文件1: Delay.c #include "Delay.h" //晶振11.0592 //延時(shí)函數(shù) void Delay() {}
//延時(shí)1ms void Delay1MS(uchar n) { uchar i=110; while(n--) { while(i--); } }
文件2: Delay.h #ifndef _DELAY_H_ #define _DELAY_H_
#ifndef uchar #define uchar unsigned char #endif
#pragma SAVE #pragma REGPARMS void Delay(); //延時(shí)函數(shù) void Delay1MS(uchar); //延時(shí)1MS函數(shù) #pragma RESTORE
#endif
文件3:I2C.c #include <reg51.h> #include "Delay.h" #include "I2C.h"
//init void I2C_Init() { SDA=1; SCL=1; }
//start condition void I2C_Start() { SDA=1; Delay(); SCL=1; Delay(); SDA=0; Delay(); }
//stop condition void I2C_Stop() { SCL=0; Delay(); SDA=0; Delay(); SCL=1; Delay(); SDA=1; Delay(); }
//response bit I2C_ACK() { uchar i=10;
SCL=0; Delay(); SDA=1; //準(zhǔn)備讀 Delay(); SCL=1; Delay();
while(SDA && i--) { Delay(); }
return SDA; }
//write byte void I2C_WriteByte(uchar n) { uchar i=8;
while(i--) { n=n<<1; SCL=0; //數(shù)據(jù)變換 Delay(); SDA=CY; Delay(); SCL=1; //寫數(shù)據(jù) Delay(); } }
//read byte uchar I2C_ReadByte() { uchar n=0; uchar i=8;
SDA=1; Delay();
while(i--) { SCL=0; //數(shù)據(jù)變換 Delay(); n=(n<<1)|SDA; P2 = n; Delay(); SCL=1; //寫數(shù)據(jù) Delay(); } return n; }
文件4:I2C.h #ifndef _I2C_H_ #define _I2C_H_
#ifndef uchar #define uchar unsigned char #endif
sbit SDA=P0^1; //SDA sbit SCL=P0^0; //SCL
#pragma SAVE #pragma REGPARMS void I2C_Init(void); //init void I2C_Start(void); //start condition void I2C_Stop(void); //stop condition bit I2C_ACK(void); //response void I2C_WriteByte(uchar); //write byte bit I2C_ReadBit(void); //read bit uchar I2C_ReadByte(void); //read byte #pragma RESTORE
#endif
文件5:I2Cmain.c #include <reg51.h>
#include "Delay.h" #include "I2C.h"
void main() { Delay1MS(250);
I2C_Init();
I2C_Start(); I2C_WriteByte(0xa0); //Write device address I2C_ACK(); I2C_WriteByte(1); //write address I2C_ACK(); I2C_WriteByte(0x0a); //write da I2C_ACK(); I2C_Stop();
Delay1MS(10);
I2C_Start(); I2C_WriteByte(0xa0); //wirte device address I2C_ACK(); I2C_WriteByte(1); //wirte address for reading I2C_ACK(); I2C_Stop(); Delay1MS(2); I2C_Start(); I2C_WriteByte(0xa1); //write device I2C_ACK(); P2=I2C_ReadByte();//read da I2C_Stop(); Delay1MS(50);
while(1); } |
|