3

In my code I have a number of boolean flags that tell me if data has been written to specific places in the EEPROM. I need to save these flags to the EEPROM and recover them on a restart.

Is the following syntax valid to update a single bit in an EEPROM cell?

EEPROM.update (0, EEPROM.read(0)| 0x20);

ie I'm reading cell '0' , putting a '1' into bit 5 and then updating cell; '0' of the EEPROM. There will be several other bits to be updated throughout the running of the programme.

2
  • 3
    how frequently?
    – Juraj
    Commented Jul 24, 2023 at 17:07
  • 1
    perehaps you better first collect all bit changes and update the value only once. Commented Jul 25, 2023 at 11:40

1 Answer 1

2

Yes, your syntax is indeed correct. The | operator is the bitwise OR operator in C and C++, and it's used to set a specific bit in a byte. Here's a breakdown of what your line of code does:

  • EEPROM.read(0) reads the current value of the first byte in the EEPROM.
  • 0x20 is the hexadecimal representation of 32, which is 00100000 in binary. This means that the fifth bit (counting from zero) is set to 1, and all other bits are set to 0.
  • EEPROM.read(0) | 0x20 performs a bitwise OR operation on the current value of the first byte in the EEPROM and 0x20. This will set the fifth bit of the byte to 1, and leave the other bits unchanged.
  • EEPROM.update(0, EEPROM.read(0) | 0x20) updates the first byte in the EEPROM with the new value.

So, your approach to set a specific bit in an EEPROM byte is correct.

Here's a more detailed example:

byte bitToSet = 5; // Bit number to set (0-7)
byte eepromAddress = 0; // EEPROM address (0-1023 for ATmega328)

// Read current value
byte currentValue = EEPROM.read(eepromAddress);

// Create mask for bit to set
byte mask = 1 << bitToSet;

// Update value
byte newValue = currentValue | mask;

// Write updated value back to EEPROM
EEPROM.update(eepromAddress, newValue);

It's worth noting that the EEPROM.update() function is smart enough to only perform a write if the new value is different from the old one. This is important because the EEPROM has a limited number of write cycles. So using EEPROM.update() instead of EEPROM.write() can help extend the life of the EEPROM.

1
  • 2
    Note: unprogrammed eeprom/flash values are 0xFF so if you left it unprogrammed it might not work as intended
    – KIIV
    Commented Jul 24, 2023 at 21:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.