#include "at24c64.h"
#include "i2c.h"
#define AT24CXX_ADDR_READ 0xA1
#define AT24CXX_ADDR_WRITE 0xA0
#define PAGE_SIZE 32
/**
* [url=home.php?mod=space&uid=247401]@brief[/url] AT24C64任意地址连续读多个字节数据
* @param addr —— 读数据的地址(0-65535)
* @param dat —— 存放读出数据的地址
* @retval 成功 —— HAL_OK
*/
uint8_t At24cxx_Read_Amount_Byte(uint16_t addr, uint8_t* recv_buf, uint16_t size)
{
return HAL_I2C_Mem_Read(&hi2c2, AT24CXX_ADDR_READ, addr, I2C_MEMADD_SIZE_16BIT, recv_buf, size, 0xFFFFFFFF);
}
/**
* @brief AT24C64任意地址连续写多个字节数据
* @param addr —— 写数据的地址(0-65535)
* @param dat —— 存放写入数据的地址
* @retval 成功 —— HAL_OK
*/
uint8_t At24cxx_Write_Amount_Byte(uint16_t addr, uint8_t* dat, uint16_t size)
{
uint8_t i = 0;
uint16_t cnt = 0; //写入字节计数
/* 对于起始地址,有两种情况,分别判断 */
if(0 == addr % PAGE_SIZE )
{
/* 起始地址刚好是页开始地址 */
/* 对于写入的字节数,有两种情况,分别判断 */
if(size <= PAGE_SIZE)
{
//写入的字节数不大于一页,直接写入
return HAL_I2C_Mem_Write(&hi2c2, AT24CXX_ADDR_WRITE, addr, I2C_MEMADD_SIZE_16BIT, dat, size, 0xFFFFFFFF);
}
else
{
//写入的字节数大于一页,先将整页循环写入
for(i = 0;i < size/PAGE_SIZE; i++)
{
HAL_I2C_Mem_Write(&hi2c2, AT24CXX_ADDR_WRITE, addr, I2C_MEMADD_SIZE_16BIT, &dat[cnt], PAGE_SIZE, 0xFFFFFFFF);
HAL_Delay(3);
addr += PAGE_SIZE;
cnt += PAGE_SIZE;
}
//将剩余的字节写入
return HAL_I2C_Mem_Write(&hi2c2, AT24CXX_ADDR_WRITE, addr, I2C_MEMADD_SIZE_16BIT, &dat[cnt], size - cnt, 0xFFFFFFFF);
}
}
else
{
/* 起始地址偏离页开始地址 */
/* 对于写入的字节数,有两种情况,分别判断 */
if(size <= (PAGE_SIZE - addr%PAGE_SIZE))
{
/* 在该页可以写完 */
return HAL_I2C_Mem_Write(&hi2c2, AT24CXX_ADDR_WRITE, addr, I2C_MEMADD_SIZE_16BIT, dat, size, 0xFFFFFFFF);
}
else
{
/* 该页写不完 */
//先将该页写完
cnt += PAGE_SIZE - addr%PAGE_SIZE;
HAL_I2C_Mem_Write(&hi2c2, AT24CXX_ADDR_WRITE, addr, I2C_MEMADD_SIZE_16BIT, dat, cnt, 0xFFFFFFFF);
addr += cnt;
HAL_Delay(3);
//循环写整页数据
for(i = 0;i < (size - cnt)/PAGE_SIZE; i++)
{
HAL_I2C_Mem_Write(&hi2c2, AT24CXX_ADDR_WRITE, addr, I2C_MEMADD_SIZE_16BIT, &dat[cnt], PAGE_SIZE, 0xFFFFFFFF);
HAL_Delay(3);
addr += PAGE_SIZE;
cnt += PAGE_SIZE;
}
//将剩下的字节写入
return HAL_I2C_Mem_Write(&hi2c2, AT24CXX_ADDR_WRITE, addr, I2C_MEMADD_SIZE_16BIT, &dat[cnt], size - cnt, 0xFFFFFFFF);
}
}
}