?? 24cxx_twi.h
字號(hào):
typedef unsigned char uint8;
typedef unsigned int uint16;
typedef union reccnt
{
uint16 rcnt;
uint8 rcntl[2];
}LngToChar;
#define wr_24c64_cmd 0xA0
#define rd_24c64_cmd 0xA1
#define START 0x08
#define RE_START 0x10
#define MT_SLA_ACK 0x18
//#define MT_SLA_ACK 0x38
#define MT_SLA_NOACK 0x20
#define MT_DATA_ACK 0x28
#define MT_DATA_NOACK 0x30
#define MR_SLA_ACK 0x40
#define MR_SLA_NOACK 0x48
#define MR_DATA_ACK 0x50
#define MR_DATA_NOACK 0x58
#define Start() (TWCR=(1<<TWINT)|(1<<TWSTA)|(1<<TWEN))
#define Stop() (TWCR=(1<<TWINT)|(1<<TWSTO)|(1<<TWEN))
#define Wait() {while(!(TWCR&(1<<TWINT)));}
#define TestAck() (TWSR&0xf8)
#define SetAck() (TWCR|=(1<<TWEA))
#define SetNoAck() (TWCR&=~(1<<TWEA))
#define Twi() (TWCR=(1<<TWINT)|(1<<TWEN))
#define Write8Bit(x) {TWDR=(x);TWCR=(1<<TWINT)|(1<<TWEN);}
uint8 WriteByte(uint16 RomAddress,uint8 Wdata);
uint8 ReadByte(uint16 RomAddress);
//******************************************
uint8 WriteByte(uint16 RomAddress,uint8 Wdata)
{
LngToChar ltg;
ltg.rcnt=RomAddress;
_CLI();
Start();//twi
Wait();
if(TestAck()!=START) goto wr_exit;//ACK 0x08
Write8Bit(wr_24c64_cmd);//
Wait();
if(TestAck()!=MT_SLA_ACK) goto wr_exit;//ACK MT_SLA_ACK 0x18
Write8Bit(ltg.rcntl[1]); //寫操作單元的高8位地址
Wait();
if(TestAck()!=MT_DATA_ACK) goto wr_exit;//ACK
Write8Bit(ltg.rcntl[0]); //寫操作單元的低8位地址
Wait();
if(TestAck()!=MT_DATA_ACK) goto wr_exit;//ACK
Write8Bit(Wdata);//
Wait();
if(TestAck()!=MT_DATA_ACK) goto wr_exit;//ACK
Stop();//
delay_ms(30);//
_SEI();
return 0;
wr_exit://出錯(cuò)退出
Stop();//
_SEI();
return 1;
}
//******************************************
uint8 ReadByte(uint16 RomAddress)
{
uint8 temp;
LngToChar ltg;
_CLI();
ltg.rcnt=RomAddress;
Start();
Wait();
if (TestAck()!=START) goto re_exit;//ACK
Write8Bit(wr_24c64_cmd);//
Wait();
if (TestAck()!=MT_SLA_ACK) goto re_exit;//ACK
Write8Bit(ltg.rcntl[1]); //寫操作單元的高8位地址
Wait();
if (TestAck()!=MT_DATA_ACK) goto re_exit;
Write8Bit(ltg.rcntl[0]); //寫操作單元的低8位地址
Wait();
if (TestAck()!=MT_DATA_ACK) goto re_exit;
Start();//twi
Wait();
if (TestAck()!=RE_START) goto re_exit;
Write8Bit(rd_24c64_cmd);//
Wait();
if(TestAck()!=MR_SLA_ACK) goto re_exit;//ACK
Twi();//啟動(dòng)主I2C讀方式
Wait();
if(TestAck()!=MR_DATA_NOACK) goto re_exit;//ACK MR_DATA_NOACK 0x58
temp=TWDR;// 讀取I2C接收的數(shù)據(jù)
Stop();//I2C停止
_SEI();
return temp;
re_exit://出錯(cuò)退出
Stop();
_SEI();
return 0;
}
?? 快捷鍵說明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號(hào)
Ctrl + =
減小字號(hào)
Ctrl + -