-
Notifications
You must be signed in to change notification settings - Fork 1
daplink_flash: Add DAPLink Flash driver for I2C bridge to W25Q64JV. #164
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
01482f9
daplink_flash: Add DAPLink Flash driver for I2C bridge to W25Q64JV.
nedseb 465bb76
daplink_flash: Fix str.ljust() not available in MicroPython.
nedseb c4266e0
daplink_flash: Add read_sector and read methods.
nedseb 98440b1
daplink_flash: Fix read_sector timing for DMA response.
nedseb 2466e63
daplink_flash: Add usage examples for write, read and info.
nedseb d71cc0e
daplink_flash: Add sensor logging example with statistics.
nedseb e722f69
daplink_flash: Add erase flash example.
nedseb a0c2c30
daplink_flash: Address Copilot review on PR #164.
nedseb b44452f
tests: Add hardware scenarios for page boundary and multi-sector reads.
nedseb 6395c90
daplink_flash: Enforce ASCII filenames and handle zero-length reads.
nedseb File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
File renamed without changes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| from .device import DaplinkFlash | ||
|
|
||
| __all__ = ["DaplinkFlash"] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,35 @@ | ||
| from micropython import const | ||
|
|
||
| # I2C address (7-bit) — 0x76 in 8-bit (CODAL convention) | ||
| DAPLINK_FLASH_DEFAULT_ADDR = const(0x3B) | ||
|
|
||
| # WHO_AM_I expected value | ||
| DAPLINK_FLASH_WHO_AM_I_VAL = const(0x4C) | ||
|
|
||
| # Commands | ||
| CMD_WHO_AM_I = const(0x01) | ||
| CMD_SET_FILENAME = const(0x03) | ||
| CMD_GET_FILENAME = const(0x04) | ||
| CMD_CLEAR_FLASH = const(0x10) | ||
| CMD_WRITE_DATA = const(0x11) | ||
| CMD_READ_SECTOR = const(0x20) | ||
|
|
||
| # Registers | ||
| REG_STATUS = const(0x80) | ||
| REG_ERROR = const(0x81) | ||
|
|
||
| # Status register bits | ||
| STATUS_BUSY = const(0x80) | ||
|
|
||
| # Error register bits | ||
| ERROR_BAD_PARAM = const(0x01) | ||
| ERROR_FILE_FULL = const(0x20) | ||
| ERROR_BAD_FILENAME = const(0x40) | ||
| ERROR_CMD_FAILED = const(0x80) | ||
|
|
||
| # Protocol limits | ||
| MAX_WRITE_CHUNK = const(30) | ||
| SECTOR_SIZE = const(256) | ||
| MAX_SECTORS = const(32768) | ||
| FILENAME_LEN = const(8) | ||
| EXT_LEN = const(3) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,173 @@ | ||
| from time import sleep_ms | ||
|
|
||
| from daplink_flash.const import * | ||
|
|
||
|
|
||
| class DaplinkFlash(object): | ||
| """MicroPython driver for the DAPLink Flash bridge (STM32F103 → W25Q64JV).""" | ||
|
|
||
| def __init__(self, i2c, address=DAPLINK_FLASH_DEFAULT_ADDR): | ||
| self.i2c = i2c | ||
| self.address = address | ||
| self._buffer_1 = bytearray(1) | ||
|
|
||
| # -------------------------------------------------- | ||
| # Low level I2C | ||
| # -------------------------------------------------- | ||
|
|
||
| def _read_reg(self, reg, n=1): | ||
| """Read n bytes from register.""" | ||
| if n == 1: | ||
| self.i2c.readfrom_mem_into(self.address, reg, self._buffer_1) | ||
| return self._buffer_1[0] | ||
| return self.i2c.readfrom_mem(self.address, reg, n) | ||
|
|
||
| def _write_reg(self, reg, data): | ||
| """Write data bytes to register.""" | ||
| self.i2c.writeto_mem(self.address, reg, data) | ||
|
|
||
| def _write_cmd(self, cmd): | ||
| """Write a single command byte (no payload).""" | ||
| self._buffer_1[0] = cmd | ||
| self.i2c.writeto(self.address, self._buffer_1) | ||
|
|
||
| # -------------------------------------------------- | ||
| # Device identification | ||
| # -------------------------------------------------- | ||
|
|
||
| def device_id(self): | ||
| """Read WHO_AM_I register. Expected: 0x4C.""" | ||
| return self._read_reg(CMD_WHO_AM_I) | ||
|
|
||
| # -------------------------------------------------- | ||
| # Status and error registers | ||
| # -------------------------------------------------- | ||
|
|
||
| def _status(self): | ||
| """Read raw status register.""" | ||
| return self._read_reg(REG_STATUS) | ||
|
|
||
| def _error(self): | ||
| """Read raw error register.""" | ||
| return self._read_reg(REG_ERROR) | ||
|
|
||
| def busy(self): | ||
| """Return True if flash is busy.""" | ||
| return bool(self._status() & STATUS_BUSY) | ||
|
|
||
| def _wait_busy(self, timeout_ms=30000): | ||
| """Poll busy bit until clear. Raises OSError on timeout.""" | ||
| elapsed = 0 | ||
| while self.busy(): | ||
| sleep_ms(5) | ||
| elapsed += 5 | ||
| if elapsed >= timeout_ms: | ||
| raise OSError("DAPLink Flash busy timeout") | ||
|
|
||
| # -------------------------------------------------- | ||
| # Filename management | ||
| # -------------------------------------------------- | ||
|
|
||
| def set_filename(self, name, ext): | ||
| """Set 8.3 filename. name: max 8 chars, ext: max 3 chars.""" | ||
| self._wait_busy() | ||
| n = name.upper().encode("ascii")[:FILENAME_LEN] | ||
| e = ext.upper().encode("ascii")[:EXT_LEN] | ||
| padded = n + b" " * (FILENAME_LEN - len(n)) + e + b" " * (EXT_LEN - len(e)) | ||
| self._write_reg(CMD_SET_FILENAME, padded) | ||
|
|
||
| def get_filename(self): | ||
| """Read current filename. Returns (name, ext) tuple, stripped.""" | ||
| self._wait_busy() | ||
| raw = self._read_reg(CMD_GET_FILENAME, FILENAME_LEN + EXT_LEN) | ||
| name = bytes(raw[:FILENAME_LEN]).decode().rstrip() | ||
| ext = bytes(raw[FILENAME_LEN:]).decode().rstrip() | ||
| return (name, ext) | ||
|
|
||
| # -------------------------------------------------- | ||
| # Flash operations | ||
| # -------------------------------------------------- | ||
|
|
||
| def clear_flash(self): | ||
| """Erase entire flash memory.""" | ||
| self._wait_busy() | ||
| self._write_cmd(CMD_CLEAR_FLASH) | ||
|
|
||
| def write(self, data): | ||
| """Append data to current file. data: bytes or str. | ||
|
|
||
| Returns the number of bytes written. | ||
| """ | ||
| if isinstance(data, str): | ||
| data = data.encode() | ||
| offset = 0 | ||
| length = len(data) | ||
| buf = bytearray(MAX_WRITE_CHUNK + 2) | ||
| buf[0] = CMD_WRITE_DATA | ||
| while offset < length: | ||
| self._wait_busy() | ||
| chunk_len = min(MAX_WRITE_CHUNK, length - offset) | ||
| buf[1] = chunk_len | ||
| buf[2 : 2 + chunk_len] = data[offset : offset + chunk_len] | ||
| # Zero-pad remainder | ||
| for i in range(2 + chunk_len, len(buf)): | ||
| buf[i] = 0 | ||
| self.i2c.writeto(self.address, buf) | ||
| offset += chunk_len | ||
| self._wait_busy() | ||
| err = self._error() | ||
| if err: | ||
| raise OSError("DAPLink Flash write error: 0x{:02X}".format(err)) | ||
| return length | ||
|
|
||
| def write_line(self, text): | ||
| """Append text + newline to current file.""" | ||
| return self.write(text + "\n") | ||
|
|
||
| # -------------------------------------------------- | ||
| # Read operations | ||
| # -------------------------------------------------- | ||
|
|
||
| def read_sector(self, sector): | ||
| """Read a 256-byte sector from flash. | ||
|
|
||
| Args: | ||
| sector: sector number (0-32767). | ||
|
|
||
| Returns: | ||
| bytes: 256 bytes of data. | ||
| """ | ||
| self._wait_busy() | ||
| self._write_reg(CMD_READ_SECTOR, bytes([sector >> 8, sector & 0xFF])) | ||
| # F103 processes the command in its 30ms hook, then sets up DMA. | ||
| # After DMA setup, the F103 is no longer in listen mode — only | ||
| # a plain readfrom() will work (no register-based status poll). | ||
| sleep_ms(200) | ||
| return self.i2c.readfrom(self.address, SECTOR_SIZE) | ||
|
|
||
| def read(self, length=None): | ||
| """Read file content from flash. | ||
|
|
||
| Args: | ||
| length: max bytes to read. If None, reads until first 0xFF. | ||
|
|
||
| Returns: | ||
| bytes: file content. | ||
| """ | ||
| if length is not None and length <= 0: | ||
| return b"" | ||
| result = bytearray() | ||
| sector = 0 | ||
| while sector < MAX_SECTORS: | ||
| data = self.read_sector(sector) | ||
| for i in range(SECTOR_SIZE): | ||
| if length is not None: | ||
| result.append(data[i]) | ||
| if len(result) >= length: | ||
|
nedseb marked this conversation as resolved.
|
||
| return bytes(result) | ||
| else: | ||
| if data[i] == 0xFF: | ||
| return bytes(result) | ||
| result.append(data[i]) | ||
| sector += 1 | ||
| return bytes(result) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,18 @@ | ||
| """Erase all data from the flash memory.""" | ||
|
|
||
| from machine import I2C | ||
| from time import sleep_ms | ||
| from daplink_flash import DaplinkFlash | ||
|
|
||
| i2c = I2C(1) | ||
| flash = DaplinkFlash(i2c) | ||
|
|
||
| name, ext = flash.get_filename() | ||
| print("Current file: {}.{}".format(name, ext)) | ||
|
|
||
| print("Erasing flash...") | ||
| flash.clear_flash() | ||
| sleep_ms(1000) | ||
|
|
||
| print("Done. Flash is empty.") | ||
| print("ERROR: 0x{:02X}".format(flash._error())) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| """Display DAPLink Flash bridge status and filename.""" | ||
|
|
||
| from machine import I2C | ||
| from daplink_flash import DaplinkFlash | ||
|
|
||
| i2c = I2C(1) | ||
| flash = DaplinkFlash(i2c) | ||
|
|
||
| print("=== DAPLink Flash Info ===") | ||
| print("WHO_AM_I: 0x{:02X}".format(flash.device_id())) | ||
| print("STATUS: 0x{:02X}".format(flash._status())) | ||
| print("ERROR: 0x{:02X}".format(flash._error())) | ||
| print("Busy: ", flash.busy()) | ||
|
|
||
| name, ext = flash.get_filename() | ||
| print("Filename: {}.{}".format(name, ext)) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| """Read and display the current file stored on flash.""" | ||
|
|
||
| from machine import I2C | ||
| from daplink_flash import DaplinkFlash | ||
|
|
||
| i2c = I2C(1) | ||
| flash = DaplinkFlash(i2c) | ||
|
|
||
| name, ext = flash.get_filename() | ||
| print("Reading file: {}.{}".format(name, ext)) | ||
| print() | ||
|
|
||
| content = flash.read() | ||
| if len(content) == 0: | ||
| print("(empty)") | ||
| else: | ||
| print(content.decode()) | ||
| print("---") | ||
| print("{} bytes".format(len(content))) |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.