Supplier photo of an assembled infinity mirror light cube illuminated on a dark background.
Supplier photo
Temu affiliate offer · Project idea

Build an infinity light cube

Listing specifies 5-volt direct current. Soldering required; battery and glue not included.

View kit on Temu

Tricky Circuit may earn a commission through these links. Product ideas have not been bench-tested by Tricky Circuit and are not verified lesson parts lists.

24LC256 Settings Store: Two Records and a Commit Marker

Saving a setting is not the same as making an update indivisible. A device can lose power between receiving a value and finishing the internal write. This experiment stores a sample interval in seconds and deliberately keeps a previous valid record until the replacement has been written and checked.

Pico GP4/GP5 bus connects to 24LC256-I/P pins 5/6 with 4.7 kΩ pullups; pins 1–4 and WP7 go to ground, VCC8 to 3.3 V with 100 nF bypass. Separate pages hold record and commit.
Original Tricky Circuit connection diagram. Labels identify physical pins and supply rails; this is a locally reviewed design, not a measured prototype. Open full-size schematic

Memory with a different job from working RAM

EEPROM expands to Electrically Erasable Programmable Read-Only Memory: electrically writable storage that retains data without power. Unlike ordinary working memory, it has finite write endurance and a nonzero programming time. The exact Microchip 24LC256-I/P provides 32768 bytes, not 256 kilobytes: its 256-kilobit name counts eight bits per byte. PDIP describes the through-hole package used here.

Use the LC device’s documented 2.5–5.5 V operating range; 3.3 V suits both it and Pico. Do not transfer the AA variant’s lower supply rating to the LC part. I²C, Inter-Integrated Circuit, moves data on SDA and clock on SCL. Address 0x50 selects this physical device, while a separate 16-bit memory address selects a byte inside it.

Parts and equipment

  • Original Pico RP2040 with MicroPython 1.26.0; Microchip 24LC256-I/P in an eight-pin plastic dual in-line package (PDIP).
  • Two 4.7 kΩ resistors, one 100 nF ceramic bypass capacitor, short wires and a breadboard. Use a regulated 3.3 V rail from the Pico.

Every connection

Pin or partConnection and purpose
SupplyPin 8 VCC → Pico 3V3 OUT 36; pin 4 VSS → GND 38. 100 nF between pins 8 and 4.
Address strapsPins 1/2/3 A0/A1/A2 → ground, giving 7-bit device address 0x50.
Data and clockPin 5 SDA → GP4 physical 6; pin 6 SCL → GP5 physical 7. One 4.7 kΩ pullup from each bus line to 3.3 V.
Write protectionPin 7 WP → ground for this writing experiment. A high WP inhibits writes; it is not a chip-select input.

Why a page boundary matters

The chip groups writes into 64-byte pages. A write starting at byte 62 with five bytes must be split into two bytes at 62 and three at 64. Sending all five in one page transaction can wrap within the original page and overwrite unrelated positions. The helper computes the remaining space as 64 − (address modulo 64) before each transaction.

After each transaction the code waits 10 ms, longer than the datasheet’s 5 ms maximum write-cycle specification under its stated conditions, and reads the bytes back. This is a deliberately simple bounded wait, not acknowledgement polling. A protected chip may accept bus traffic without changing memory; comparing readback prevents us from calling that a successful save. A disconnected chip raises an error instead of being interpreted as blank memory.

Separate payload from permission to use it

Slot A uses address 0 for its eleven-byte record and 64 for its one-byte commit marker. Slot B uses 128 and 192. Thus a marker update uses a different physical page from its payload. The record contains two identifying bytes, format version 1, a four-byte sequence number, a two-byte interval and a two-byte cyclic redundancy check (CRC). A CRC is an error-detecting calculation, not encryption and not proof against every possible corruption.

The chosen CRC-16 uses polynomial 0x1021, initial value 0xFFFF and no reflection or final exclusive-or. On reading, the marker must equal 0xA5, the format and length must match, the interval must be 1–3600 seconds and the CRC must agree. Of the valid records, the larger sequence wins. A sequence overflow is rejected before writing; the example does not attempt an ambiguous counter rollover policy.

To update, choose the inactive slot, write and verify an invalid marker, write and verify the new payload, then write and verify the valid marker. The older slot remains intact throughout those steps. Saving the same setting again does nothing, reducing wear. On completely blank memory, loading returns None; there is no fabricated historical setting.

Complete program

"""Pico / MicroPython 1.26.0. Two records, separate commit pages."""
def crc16(data):
    crc = 0xffff
    for b in data:
        crc ^= b << 8
        for _ in range(8):
            crc = ((crc << 1) ^ 0x1021) & 0xffff if crc & 0x8000 else (crc << 1) & 0xffff
    return crc

def encode(seq, seconds):
    if not 0 <= seq <= 0xffffffff or not 1 <= seconds <= 3600:
        raise ValueError('record range')
    p = b'TC' + b'\x01' + seq.to_bytes(4, 'big') + seconds.to_bytes(2, 'big')
    return p + crc16(p).to_bytes(2, 'big')

def decode(data, marker):
    if marker != b'\xa5' or len(data) != 11 or data[:3] != b'TC\x01':
        return None
    if crc16(data[:9]) != int.from_bytes(data[9:], 'big'):
        return None
    seq = int.from_bytes(data[3:7], 'big')
    val = int.from_bytes(data[7:9], 'big')
    return (seq, val) if 1 <= val <= 3600 else None

class EEPROM:
    def __init__(self, bus, sleep_ms):
        self.bus, self.sleep_ms = bus, sleep_ms
    def read(self, addr, n):
        return self.bus.readfrom_mem(0x50, addr, n, addrsize=16)
    def write(self, addr, data):
        if addr < 0 or addr + len(data) > 32768:
            raise ValueError('address outside memory')
        offset = 0
        while offset < len(data):
            n = min(64 - (addr % 64), len(data) - offset)
            self.bus.writeto_mem(0x50, addr, data[offset:offset+n], addrsize=16)
            # Datasheet maximum cycle is 5 ms at its specified conditions.
            # A 10 ms pause is simple and bounded, not ACK polling.
            self.sleep_ms(10)
            if self.read(addr, n) != data[offset:offset+n]:
                raise OSError('EEPROM verify failed / check WP and power')
            addr += n; offset += n

def newest(e):
    valid = []
    for slot in (0, 128):
        record = decode(e.read(slot, 11), e.read(slot+64, 1))
        if record is not None:
            valid.append((record[0], record[1], slot))
    return max(valid) if valid else None

def save(e, seconds):
    old = newest(e)  # bus failures propagate; they are not an empty memory
    if old is not None and old[1] == seconds:
        return old
    seq = 0 if old is None else old[0]+1
    payload = encode(seq, seconds)  # refuses counter overflow before any write
    target = 0 if old is None or old[2] == 128 else 128
    e.write(target+64, b'\x00')  # invalidate inactive slot first
    e.write(target, payload)
    e.write(target+64, b'\xa5')  # commit only after verified data
    result = newest(e)
    if result != (seq, seconds, target):
        raise OSError('record not committed')
    return result

def main():
    from machine import Pin, SoftI2C
    from time import sleep_ms
    bus = SoftI2C(sda=Pin(4), scl=Pin(5), freq=100000, timeout=20000)
    e = EEPROM(bus, sleep_ms)
    try:
        print('loaded:', newest(e))
        command = input('Type seconds 1..3600 to save, or Enter for read-only: ').strip()
        if command:
            print('saved:', save(e, int(command)))
    except (OSError, ValueError) as exc:
        print('NOT SAVED / inspect bus or value:', exc)
if __name__ == '__main__':
    main()

A controlled experience before random power cuts

  1. Wire the chip with power off and install MicroPython 1.26.0 on an original Pico. Save the listing as main.py. The console offers a read-only run: press Enter without typing a number.
  2. On a blank device, confirm loaded: None. Run again, type 30 and inspect the saved sequence, value and slot. Restart and use read-only mode; the setting should remain 30.
  3. Save 60. It should use the other slot with a higher sequence. Save 60 again; the sequence should not increase.
  4. For a deterministic interrupted-update demonstration, after the initial saves of 30 and 60, recreate the memory helper using the console listing below. Invalidate slot A and write a candidate payload there without committing it. Loading must still select slot B (sequence 1, value 60). This is a software-injected incomplete update, not a brownout experiment.
  5. Power off, move WP to 3.3 V, restart and request a different setting. Expect a verification error. Restore WP to ground with power disconnected.

After the program exits, run this console example only with the two initial saves above completed. If you have already made additional saves, inspect newest(e) and choose the inactive slot instead; do not overwrite the active record:

from machine import Pin, SoftI2C
from time import sleep_ms
from main import EEPROM, encode, newest
bus = SoftI2C(sda=Pin(4), scl=Pin(5), freq=100000, timeout=20000)
e = EEPROM(bus, sleep_ms)
assert newest(e) == (1, 60, 128)
e.write(64, bytes([0]))
e.write(0, encode(2, 90))
print(newest(e))  # still (1, 60, 128); candidate 90 has no commit

What this does not guarantee

Two slots protect against an incomplete update to the inactive slot under the tested storage model. Real undervoltage may violate the memory’s operating requirements or upset the controller. Use controlled supply ramps, power supervision and the exact manufacturer’s guidance before relying on recovery through arbitrary brownouts. CRC collisions remain possible; both slots can be corrupted by wiring mistakes, software using the same addresses or electrical damage.

The two marker writes per update concentrate wear. Even a headline endurance number must be interpreted with its test conditions. For illustration only, if a location budget were one million writes and that location were rewritten once per second, the arithmetic gives about 11.6 days, not unlimited life. This program writes only on an explicit changed setting. Continuous logging needs a different allocation strategy and a realistic endurance budget.

The host fault-injection tests cut the update at each modeled byte boundary and verify the old-or-new result. They also check page splitting and readback failure. This circuit has not been physically tested; neither those tests nor a successful console print certifies power-fail robustness in hardware.

Challenge: why not write the marker first?

A valid marker could expose a partly replaced payload as current. Invalidate and verify first, then verify payload, then commit. The checksum adds another check but does not replace ordering.

Sources and related lessons

Continue with why a voltage divider drops under load, measuring current through a resistor with a voltmeter, and the interactive circuit lessons.

📡Broadcast the signal — amplify the connection.

Leave a Reply

Temu affiliate offers

Find your next electronics project

Explore these do-it-yourself project kits. Check the selected option, included parts and instructions on each offer.

Tricky Circuit may earn a commission if you buy through these Temu affiliate links. These are product ideas; they have not been bench-tested by Tricky Circuit and are not verified lesson parts lists.

Supplier photo of a breadboard, jumper wires and assorted electronic components in a plastic storage case.

Supplier product photo

Try breadboard experiments

Breadboard, wires and assorted parts. Arduino controller board not included.

View kit on Temu

Supplier photo of an assembled blue surface-mount soldering practice board with a circular ring of small lights.

Supplier product photo

Solder a chasing-light board

Surface-mount soldering practice. Battery and battery holder not included.

View kit on Temu

Supplier photo of an assembled two-wheeled line-following car with a blue circuit board, two motors and an empty battery holder.

Supplier product photo

Build a line-following car

Soldering and assembly required. Check battery and track requirements before buying.

View kit on Temu