Error in Writing and reading an external EEPROM using Arduino Mega 2560

I am trying to write to an external 24C04 4kbit Serial I2C bus EEPROM from my Arduino Mega 2560. The circuit is attached. This is the code I am using:

#include <Wire.h>    
 
#define disk1 0x50    // Address of 24C04 eeprom chip
 
void setup() {
  
    Serial.begin(19200);
    Wire.begin();  
 
    unsigned int address = 1;
 
    writeEEPROM(disk1, address, 0x23);
    readEEPROM(disk1, address);
}


void loop(){}


/**
* Write data to the specified EEPROM.
*/
void writeEEPROM(int deviceaddress, unsigned int eeaddress, byte data ) {

    Wire.beginTransmission(deviceaddress);
    Wire.write((int)(eeaddress >> 8));   // MSB
    Wire.write((int)(eeaddress & 0xFF)); // LSB
    Wire.write(data);
    Serial.println(Wire.endTransmission());
 
    delay(20);
}


/**
* Read data from the EEPROM.
*/
void readEEPROM(int deviceaddress, unsigned int eeaddress ) {
 
    Wire.beginTransmission(deviceaddress);
    Wire.write((int)(eeaddress >> 8));   // MSB
    Wire.write((int)(eeaddress & 0xFF)); // LSB
    Serial.println(Wire.endTransmission());
 
    Wire.requestFrom(deviceaddress,1);
 
    if (Wire.available() > 0){
        Serial.println(Wire.read(), HEX);
    } else {
        Serial.println("No data");
    }
}

This code is available on this website; I modified it a bit.

This is the output I get:

0
0
No data

It means that Wire.endTransmission() returns successful, but still no data is available for reading.

Any idea how I can fix this?

Shouldn't you connect pullup resistors (10 kΩ) to SDA and SCL?

Erik_Baas:
Shouldn't you connect pullup resistors (10 kΩ) to SDA and SCL?

Did not know I pull-up resistors were needed. I modified the circuit. Please click here for the new diagram. But I still get:

0
0
No data

By the way, does this forum not allow uploading photos to replies to a thread? It seems there is no option to post an image.

I saw some code where delay(5); was inserted after Wire.endTransmission();. The comment was "5 ms is the max guaranteed time for a write cycle". Can you try that?

Erik_Baas:
I saw some code where delay(5); was inserted after Wire.endTransmission();. The comment was "5 ms is the max guaranteed time for a write cycle". Can you try that?

Thanks a lot! Adding delay(5); after Wire.endTransmission() in the readEEPROM() function solved the problem. The output was:

0
0
23

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.