⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 e2prom.c

📁 手把手教你单片机
💻 C
字号:
/*
 * E2PROM 读写
*/

#include "e2prom.h"


/**
 * 函数: i2c_start()
 * 功能: 启动i2c
*/
void i2c_start()
{
	SCL = 1;
	nops();
	SDA = 1;
	nops();
	SDA = 0;
	nops();
	SCL = 0;
}

/**
 * 函数: i2c_stop()
 * 功能: 停止i2c
*/
void i2c_stop()
{
	SCL = 0;
	nops();
	SDA = 0;
	nops();
	SCL = 1;
	nops();
	SDA = 1;
	nops();
}

/**
 * 函数: i2c_ACK(bit ck)
 * 功能: ck为1时发送应答信号ACK,
 *       ck为0时不发送ACK
*/
void i2c_ACK(bit ck)
{
    if (ck)
		SDA = 0;
    else
		SDA = 1;
    nops();
    SCL = 1;
    nops();
    SCL = 0;
	nops();
    SDA = 1;
    nops();
}

/**
 * 函数: i2c_waitACK()
 * 功能: 返回为0时收到ACK
 *       返回为1时没收到ACK
*/
bit i2c_waitACK()
{
	SDA = 1;
	nops();
	SCL = 1;
	nops();
	if (SDA)
	{   
		SCL = 0;
		i2c_stop();
		return 1;
	}
	else
	{  
		SCL = 0;
		return 0;
	}
}

/**
 * 函数: i2c_sendbyte(uint8 bt)
 * 功能: 将输入的一字节数据bt发送
*/
void i2c_sendbyte(uint8 bt)
{
    uint8 i;
    
    for(i=0; i<8; i++)
    {  
        if (bt & 0x80) 
			SDA = 1;
        else 
			SDA = 0;
        nops();
        SCL = 1;
        bt <<= 1;
        nops();       
        SCL = 0;
    }
}

/**
 * 函数: i2c_recbyte( )
 * 功能: 从总线上接收1字节数据
*/
uint8 i2c_recbyte()
{
	uint8 dee, i;
	
	for (i=0; i<8; i++)
	{
		SCL = 1;    
		nops();
		dee <<= 1;
		if (SDA) 
			dee = dee | 0x01;
		SCL = 0;
		nops();
	}
	
	return dee;
}

/**
 * 函数: i2c_writebyte
 * 功能: 字节写,在指定的地址(add)
 *       写入一字节数据(dat)
 * 返回值: 0->成功  1->失败
*/
bit i2c_writebyte(uint8 addr, uint8 dat)
{
    i2c_start();
    i2c_sendbyte(SLAVEADDR);  //控制字节
    if (i2c_waitACK())
		return 1;
    i2c_sendbyte(addr);   //地址
    if (i2c_waitACK())
		return 1;
    i2c_sendbyte(dat);   //数据
    if (i2c_waitACK())
		return 1;
    i2c_stop();
    delay(2000);
	return 0;
}

/**
 * 函数: i2c_readbyte
 * 输入: add
 * 返回: hep
 * 功能: 字节读,在指定的地址(add)
 *       读出一字节数据
 * 返回值: 0->成功  1->失败
*/
bit i2c_readbyte(uint8 addr, uint8 *dat)
{	
	i2c_start();
	i2c_sendbyte(SLAVEADDR);    //控制字节
    if (i2c_waitACK())
		return 1;
	i2c_sendbyte(addr);        //地址
    if (i2c_waitACK())
		return 1;
	i2c_start();
	i2c_sendbyte(SLAVEADDR+1); //控制字节
    if (i2c_waitACK())
		return 1;
	*dat = i2c_recbyte();      //读数据
	i2c_ACK(0);                //因为只读一字节数据,不发送ACK信号
	i2c_stop();   
	
	return 0;
}

/*
 * *buf--待写数据,addr--e2prom地址,len--数据长度
*/
bit i2c_write_buf(uint8 *buf, uint8 addr, uint8 len)
{
	while (len--)
	{
		if (i2c_writebyte(addr++, *buf++))
			return 1;
	}
	return 0;
}

/*
 * *buf--读数据,addr--e2prom地址,len--数据长度
*/
bit i2c_read_buf(uint8 *buf, uint8 addr, uint8 len)
{
	while (len--)
	{
		if (i2c_readbyte(addr++, buf++))
			return 1;
	}
	return 0;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -