我的STM32H730 搭配 M24C64 进行项目开发。使用HAL_I2C_Mem_Write从 EEPROM 读取数据。
现在连续快速调用HAL_I2C_Mem_Write或者HAL_I2C_Mem_Read时,读出的数据是错误的。
我已经在每次读写操作后加入 1ms 延时,但测试发现需要延长至大约 10ms 才能稳定工作,这会严重影响性能。
调试过程中如果使用调试器单步慢速执行,读写完全正常;全速运行缺少足够延时就出错。
void persistent_memory_i2c_eeprom::erase_all(void) {
clear_block(0, mem_size);
}
/**
* @brief Writes a byte to i2c_eeprom memory
*/
void persistent_memory_i2c_eeprom::write_val(uint32_t offset, uint8_t val) {
HAL_StatusTypeDef res = HAL_I2C_Mem_Write(hi2c, DevAddress, mem_base_address + offset, I2C_MEMADD_SIZE_16BIT, &val, 1, 100);
HAL_Delay(1);
}
/**
* @brief Reads a byte from i2c_eeprom memory
*/
uint8_t persistent_memory_i2c_eeprom::read_val(uint32_t offset) {
uint8_t data;
HAL_StatusTypeDef res = HAL_I2C_Mem_Read(hi2c, DevAddress, mem_base_address + offset, I2C_MEMADD_SIZE_16BIT, &data, 1, 100);
HAL_Delay(1);
return data;
}
/**
* @brief Writes a block of data to i2c_eeprom memory
*/
void persistent_memory_i2c_eeprom::write_block(uint32_t offset, uint8_t * vals, uint32_t size) {
uint32_t write_remaining = size;
uint32_t mem_addr = mem_base_address + offset;
uint32_t incr = 0;
while(write_remaining > 0){
uint16_t block_portion = 32 - (mem_addr % 32);
if(block_portion > write_remaining){
block_portion = write_remaining;
}
HAL_StatusTypeDef res = HAL_I2C_Mem_Write(hi2c, DevAddress, mem_addr, I2C_MEMADD_SIZE_16BIT, &vals[incr], block_portion, 100);
mem_addr += block_portion;
write_remaining -= block_portion;
incr += block_portion;
HAL_Delay(1);
}
}
/**
* @brief Reads a block of data from i2c_eeprom memory
*/
void persistent_memory_i2c_eeprom::read_block(uint32_t offset, uint8_t * vals, uint32_t size) {
HAL_StatusTypeDef res = HAL_I2C_Mem_Read(hi2c, DevAddress, mem_base_address + offset, I2C_MEMADD_SIZE_16BIT, vals, size, 100);
HAL_Delay(1);
}
void persistent_memory_i2c_eeprom::clear_block( uint32_t offset, uint32_t size ) {
uint8_t vals[32] = {};
uint32_t write_remaining = size;
uint32_t mem_addr = mem_base_address + offset;
uint32_t incr = 0;
while(write_remaining > 0){
uint16_t block_portion = 32 - (mem_addr % 32);
if(block_portion > write_remaining){
block_portion = write_remaining;
}
HAL_StatusTypeDef res = HAL_I2C_Mem_Write(hi2c, DevAddress, mem_addr, I2C_MEMADD_SIZE_16BIT, &vals[incr], block_portion, 100);
mem_addr += block_portion;
write_remaining -= block_portion;
incr += block_portion;
HAL_Delay(1);
}
}
目前最奇怪的一点是即便读出 / 写入的数据是错误的,所有读写函数依然返回 HAL_OK。
有没有别的函数可以调用,用来等待 EEPROM 真正就绪、能够接收新的通信指令?
|