📄 eeprom.c
字号:
#include "hpa449lib.h"
#include "eeprom.h"
/*
******************************************************************************
** [function]
** EEPromWrite
** [puropse]
** writes data to a Microchip 24LC256 EEPROM
** [parameters]
** EEPromAddress - lower address bit of the EEPROM
** StartAddress - Startaddress where to read from
** Length - Number of bytes to write
** Buffer - Start address of the buffer that contains the data
** [returns]
** success
*/
int EEPromWrite(int EEPromAddress, unsigned int StartAddress,
unsigned int Length, char * Buffer)
{
int i, fOK;
I2C_Start();
// send command byte
fOK = I2C_SendByte(MCP24LC256_FIXED_ADDRESS | (EEPromAddress & 0x0f));
// eventually, we need to brake up transfers, if they span multiple pages
while (Length > 0 && fOK)
{
// determine how many bytes we have to a page boundary
int nThisBytes = 64 -StartAddress % 64;
if (nThisBytes > Length)
nThisBytes = Length;
// now nThisBytes contains the number of bytes within one page
// send address byte high byte
if (fOK)
{
fOK = I2C_SendByte((StartAddress >> 8) & 0xff);
}
// send address low byte
if (fOK)
{
fOK = I2C_SendByte((StartAddress) & 0xff);
}
for (i=0; i< nThisBytes && fOK; i++)
{
fOK &= I2C_SendByte(*Buffer++);
}
// do the stop condition this will trigger the write process
I2C_Stop();
// adjust Length and Startaddress
Length -= nThisBytes;
StartAddress += nThisBytes;
// wait for the write to complete
i = 1000; // limit the number of tries
do
{
I2C_Start();
// send command byte
fOK = I2C_SendByte(MCP24LC256_FIXED_ADDRESS | (EEPromAddress & 0x0f));
} while (!fOK && (i-- > 0));
}
// end with a stop condition to put the bus into an idle state
I2C_Stop();
return fOK;
}
/*
******************************************************************************
** [function]
** EEPromRead
** [puropse]
** reads from an Microchip 24LC256 EEPROM
** [parameters]
** Site - Site on the HPA449
** EEPromAddress - lower address bit of the EEPROM
** StartAddress - Startaddress where to read from
** Length - Number of bytes to read
** Buffer - Start address of the buffer that receives the data, must be
** at least <Length> bytes long
** [returns]
** success
*/
int EEPromRead(int EEPromAddress, unsigned int StartAddress,
unsigned int Length, char * Buffer)
{
int i, fOK;
I2C_Start();
// send command byte
fOK = I2C_SendByte(MCP24LC256_FIXED_ADDRESS | (EEPromAddress & 0x0f));
// send address byte high byte
if (fOK)
{
fOK = I2C_SendByte((StartAddress >> 8) & 0xff);
}
// send address low byte
if (fOK)
{
fOK = I2C_SendByte((StartAddress) & 0xff);
}
// repeated start condition
if (fOK)
{
I2C_Start();
fOK = I2C_SendByte(MCP24LC256_FIXED_ADDRESS | (EEPromAddress & 0x0f) | 0x01);
}
if (fOK)
{
for (i=0; i< Length; i++)
{
// receive the bytes NACK when the last byte was received
*Buffer++ = I2C_ReceiveByte(i != Length-1);
}
}
// do the stop condition
I2C_Stop();
return fOK;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -