?? e2prom.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 + -