项目中用到的,实测OK
C文件
#include "eeprom.h"
// 豪秒延时标准程序
static void Delay(unsigned char time)
{
volatile unsigned char a, b;
for (b = time; b>0; b--) {
for (a = 15; a>0; a--)
{
GCC_CLRWDT();
}
}
}
void IIC_Init()
{
OUT_SDA();
OUT_SCL();
SET_SDA();
SET_SCL();
SDA_PUL();
SCL_PUL();
}
static void Start()
{
SET_SDA();
OUT_SDA();
SET_SCL();
Delay(1);
CLR_SDA();
Delay(1);
CLR_SCL();
Delay(1);
}
static void Stop()//
{
CLR_SCL();
OUT_SDA();
CLR_SDA();
Delay(1);
SET_SCL();
Delay(1);
SET_SDA();
}
static unsigned char ReceiveByte()//
{
unsigned char i;
unsigned char buffer;
buffer = 0;
IN_SDA();
for (i = 0; i < 8; i++) {
CLR_SCL();
Delay(2);
SET_SCL();
Delay(2);
if (SDA()) {
buffer |= 0x01;
}
if (i < 7) {
buffer <<= 1;
}
}
CLR_SCL();
OUT_SDA();
CLR_SDA();
return (buffer);
}
static unsigned char SendByteAndGetNACK(unsigned char dataToSend) //发送数据 没有ACK
{
unsigned char i;
unsigned char ack;
for (i = 0; i < 8; i++) {
CLR_SCL();
Delay(1);
if (dataToSend & 0x80) {
SET_SDA();
}
else {
CLR_SDA();
}
Delay(1);
SET_SCL();
Delay(1);
dataToSend <<= 1;
}
CLR_SCL();
Delay(1);
IN_SDA();
Delay(1);
SET_SCL();
Delay(2);
ack = SDA();
CLR_SCL();
Delay(1);
OUT_SDA();
CLR_SDA();
Delay(1);
return (ack);
}
void Respond(unsigned char ACKSignal) //
{
OUT_SDA();
CLR_SDA();
CLR_SCL();
if (ACKSignal) {
SET_SDA();
}
else {
CLR_SDA();
}
Delay(1);
SET_SCL();
Delay(1);
CLR_SCL();
}
/**********************************************************************************
EEPROM写
***********************************************************************************/
void Eeprom_Write(unsigned char Addr,unsigned char dat)
{
Start();
SendByteAndGetNACK(0xA0); //写地址
SendByteAndGetNACK(Addr);
SendByteAndGetNACK(dat);
Stop();
Delay(250);
}
/**********************************************************************************
EEPROM读
***********************************************************************************/
unsigned char Eeprom_Read(unsigned char Addr)
{
unsigned char dat;
Start();
SendByteAndGetNACK(0xA0); //发送设备地址
SendByteAndGetNACK(Addr);
Start(); //再发送一次开始信号
SendByteAndGetNACK(0xA1);//发送读设备地址
dat= ReceiveByte();//读取数据
Respond(NACK);
Stop();
return dat;
}
H文件
#define NACK 1
#define ACK 0
#define SET_SDA() _pa1=1
#define CLR_SDA() _pa1=0
#define OUT_SDA() _pac1=0
#define IN_SDA() _pac1=1
#define SDA() _pa1
#define SDA_PUL() _papu1=1
#define SET_SCL() _pa3=1
#define CLR_SCL() _pa3=0
#define OUT_SCL() _pac3=0
#define IN_SCL() _pac3=1
#define SCL_PUL() _papu3=1
extern void Eeprom_Write(unsigned char Addr,unsigned char dat);
extern unsigned char Eeprom_Read(unsigned char Addr);