arduinoeepromattiny

ATtiny85 eeprom write in the arduino IDE


I have a problem: I can read the EEPROM from my ATtiny, but I can't write something in it.

Here is my code:

#include <EEPROM.h>

int addr = 0;
int val = 2;
    
void setup()
{
}
    
void loop()
{
  EEPROM.write(addr, val);
      
  addr = addr + 1;
  if (addr == 512)
    addr = 0;
}

EDIT

Now my write code is:

#include <EEPROM.h>

int addr = 0;
int val = 2;

void setup()
{
}

void loop()
{
  EEPROM.write(addr, byte(val));
  
  addr = addr + 1;
  if (addr == 512)
    while(1);
}

And my read code:

int address = 0;
byte value;

#include <SoftwareSerial.h>

void setup()
{
  SSerial.begin(9600);
}

void loop()
{
  value = EEPROM.read(address);
  
  SSerial.print(address);
  SSerial.print("\t");
  SSerial.print(value, DEC);
  SSerial.println();
  
  address = address + 1;
  
  if (address == 512){
    address = 0;
    delay(100000000);
  }
}

I always get only teh value 255. On every adress. Now I convert my int to byte. My int won't get over 255 in my case.

And by the way: can I create an int as byte? So I can use it like a normal int, but can write it directly?


Solution

  • You're writing a single byte, whereas an int is two bytes. You can use EEPROM.get() & EEPROM.put() for larger types (read/write only handle a single byte).

    #include <EEPROM.h>
    int addr = 0;
    int val = 2;
    
    void setup(){}
    
    void loop(){
    
      //Write value
      EEPROM.put(addr, val);
    
      //Read value
      EEPROM.get(addr, val);
    
      addr += sizeof(int);  //Increment cursor by two otherwise writes will overlap.
    
      if(addr == EEPROM.length())
        addr = 0;
    }
    

    as Vladimir Tsykunov mentioned, this test code can be bad for your EEPROM as it will loop many times while running. It may be better to stop the loop after one iteration:

      if(addr == EEPROM.length())
        while(1); //Infinite loop