📄 24cxx_twi.h
字号:
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://出错退出
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();//启动主I2C读方式
Wait();
if(TestAck()!=MR_DATA_NOACK) goto re_exit;//ACK MR_DATA_NOACK 0x58
temp=TWDR;// 读取I2C接收的数据
Stop();//I2C停止
_SEI();
return temp;
re_exit://出错退出
Stop();
_SEI();
return 0;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -