📄 24c02.c
字号:
#include <reg52.h>
#include <intrins.h>
#define OP_READ 0xa1 // 器件地址以及读取操作
#define OP_WRITE 0xa0 // 器件地址以及写入操作
sbit SDA = P3^4;
sbit SCL = P3^3;
extern void delay(unsigned int ms);
void start()
// 开始位
{
SDA = 1;
_nop_();
SCL = 1;
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
SDA = 0;
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
SCL = 0;
_nop_();
_nop_();
}
void stop()
// 停止位
{
SDA = 0;
_nop_();
_nop_();
SCL = 1;
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
SDA = 1;
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
}
////////////////////////////////////////////////////////////////////////
// 接收数据从AT24Cxx/////////////////////////
unsigned char RcvByte()
{
unsigned char i,receive_data;
SDA=1;
for(i = 0; i < 8; i++)
{
_nop_();
SCL = 0;
_nop_();
_nop_();
_nop_();
_nop_();
SCL=1;
_nop_();
_nop_();
receive_data <<= 1;
receive_data |= (unsigned char)SDA;
_nop_();
_nop_();
}
SCL=0;
_nop_();
_nop_();
return(receive_data);
}
/////////////////////////////////////////////////////////////////////////
// 发送write_data数据到AT24Cxx//////////////////////////////////////////////////
void SentByte(unsigned char write_data)
{
unsigned char i;
for(i = 0; i < 8; i++) // 循环移入8个位
{
SDA = (bit)(write_data & 0x80);
_nop_();
SCL = 1;
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
SCL = 0;
write_data <<= 1;
}
_nop_();
SDA = 1; // 读取应答
_nop_();
_nop_();
SCL = 1;
_nop_();
_nop_();
_nop_();
_nop_();
// ack=~SDA; // ack=1为应答成功
SCL = 0;
_nop_();
_nop_();
}
///////////////////////////////////////////////////////////////////////
// 在指定地址addr处写入数据write_data
void write_appoint(unsigned char addr, unsigned char write_data)
{
start();
SentByte(OP_WRITE); // 器件地址及写操作
SentByte(addr);
SentByte(write_data);
stop();
delay(10);
}
////////////////////////////////////////////////////////////////////////////
// 在当前地址读取//////////////////////
unsigned char read_current()
{
unsigned char receive_data;
start();
SentByte(OP_READ); // 器件地址及读操作
receive_data = RcvByte();
stop();
return receive_data;
}
////////////////////////////////////////////////////////////////////////////
// 在指定地址读取/////////////////
unsigned char read_appoint(unsigned char appoint_addr)
{
start();
SentByte(OP_WRITE); // 空写操作
SentByte(appoint_addr);
return(read_current());
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -