1
votes

I'm having trouble writing multiple bytes to a 24LC256 EEPROM using an ESP32.

The following functions are what is responsible for reading and writing to the EEPROM. (I understand that page writing is limited to increments of 64 bytes using this EEPROM, this code is just for testing)

EEPROM write function

esp_err_t eeprom_write(uint8_t deviceaddress, uint16_t eeaddress, uint8_t* data, size_t size) {
    i2c_cmd_handle_t cmd = i2c_cmd_link_create();
    i2c_master_start(cmd);
    i2c_master_write_byte(cmd, (deviceaddress << 1) | EEPROM_WRITE_ADDR, 1);
    i2c_master_write_byte(cmd, eeaddress>>8, 1);
    i2c_master_write_byte(cmd, eeaddress&0xFF, 1);

    i2c_master_write(cmd, data, size, 1);   // Start page write

    i2c_master_stop(cmd);    // Call stop command
    esp_err_t ret = i2c_master_cmd_begin(I2C_NUM_1, cmd, 1000/portTICK_PERIOD_MS);
    i2c_cmd_link_delete(cmd);
    return ret;
}

EEPROM read function

esp_err_t eeprom_read(uint8_t deviceaddress, uint16_t eeaddress, uint8_t* data, size_t size) {
    i2c_cmd_handle_t cmd = i2c_cmd_link_create();
    i2c_master_start(cmd);
    i2c_master_write_byte(cmd, (deviceaddress<<1)|EEPROM_WRITE_ADDR, 1);
    i2c_master_write_byte(cmd, eeaddress<<8, 1);
    i2c_master_write_byte(cmd, eeaddress&0xFF, 1);
    i2c_master_start(cmd);
    i2c_master_write_byte(cmd, (deviceaddress<<1)|EEPROM_READ_ADDR, 1);

    // Sequential read support
    if (size > 1) {
        i2c_master_read(cmd, data, size-1, 0);  // Send ack for these bytes
                                            // as part of a sequential read
    }
    i2c_master_read_byte(cmd, data+size-1, 1);  // Do not ack the last byte
    i2c_master_stop(cmd);
    esp_err_t ret = i2c_master_cmd_begin(I2C_NUM_1, cmd, 1000/portTICK_PERIOD_MS);
    i2c_cmd_link_delete(cmd);
    return ret;
}

The odd thing is that I am able to write 13 bytes to the EEPROM and everything seems to be fine.

eeprom_write(0x50, 0x0000, data_wr, 13);   // Returns ESP_OK
eeprom_read(0x50, 0x0000, data_rd, 64);    // Returns ESP_OK

However, when writing more than 13 bytes to the EEPROM, the sequential read function screws up.

eeprom_write(0x50, 0x0000, data_wr, 14);   // Returns ESP_OK
eeprom_read(0x50, 0x0000, data_rd, 64);    // Return ESP_FAIL

I'm sure that everything I'm doing follows the rules of read and writes according to the 24LC256 datasheet. Is there something that I'm missing?

1

1 Answers

1
votes

Apparently all that was needed between the two calls was a short delay. The EEPROM needed some time to write the page buffer to the memory cells before another call was made from the ESP32.

eeprom_write(0x50, 0x0000, data_wr, 64);   // ESP_OK
vTaskDelay(20/portTICK_PERIOD_MS);
eeprom_read(0x50, 0x0000, data_rd, 64);    // ESP_OK

Everything is working just fine now.