Storage test of 24LC128 I2C EEPROM. Tested in Mbed OS 5.1

Dependencies:   I2CEeprom

main.cpp

Committer:
skyscraper
Date:
2020-03-28
Revision:
0:a356dc5160aa
Child:
1:95752dbaadf5

File content as of revision 0:a356dc5160aa:


#include "mbed.h"
#include "I2CEeprom.h"
#include <iostream>

namespace {
    
    I2C i2c1(I2C_SDA, I2C_SCL );
    I2CEeprom eeprom(
        i2c1,
        0b10100000, // i2c bus address
        64,         // page size
        16 * 1024,  // memory size in bytes
        5           // write cycle time in ms
    );
}

template <typename T>
bool storage_byte_read_write_test(size_t ee_address,T const & val)
{
    auto numWritten = eeprom.write(ee_address,val);
    if(numWritten != sizeof(val) ){
        std::cout << "failed to write eeprom\n";
        return false;
    }

    T result;
    auto numRead = eeprom.read(ee_address,result);
    if ( numRead != sizeof(val)){
        std::cout << "failed to read eeprom\n";
        return false;
    }
    std::cout << "result = " << result << '\n';
    return true;
}

bool storage_byte_read_write_test(size_t ee_address, const char* str, size_t len)
{
    auto numWritten = eeprom.write(ee_address,str,len);
    if(numWritten != len ){
        std::cout << "failed to write eeprom\n";
        return false;
    }
 
    char* result = new char[len +1];
    
    if (! result){
        std::cout << "malloc failed\n";
        return false;
    }
    memset(result,'X',len);
    result [len] = '\0';
    
    auto numRead = eeprom.read(ee_address,result,len);
    if ( numRead != len){
        std::cout << "failed to read eeprom\n";
        delete [] result;
        return false;
    }
    result [len] = '\0';
    bool match = strncmp(str,result,len) ==0;
    if ( match){
        std::cout << "strings match\n";
    }else{
        std::cout << "strings don't match\n";
    }
    std::cout << "result = " << result << '\n';
    delete [] result;
    
    return true;
}

int main()
{
    ThisThread::sleep_for(100U);
    char val = 'J';
    if ( storage_byte_read_write_test(0x21,val) ){
        std::cout << "char -> Success!\n";
    }
    
    //const char* str = "Hello*World!";
    constexpr char str [] =
    #if 0
    "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod "
    "tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim "
    "veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea "
    "commodo consequat.";
    #else
   
     "But I must explain to you how all this mistaken idea of denouncing "
    "pleasure and praising pain was born and I will give you a complete "
    "account of the system, and expound the actual teachings of the "
    "great explorer of the truth, the master-builder of human happiness.";
    #endif
    
    std::cout << "length of string = " << strlen(str) <<'\n';
    
     if ( storage_byte_read_write_test(0x5,str,strlen(str)+1) ){
        std::cout << "c_string -> Success!\n";
    }
    
    for(;;){;}
    
}