Table of Contents
1.0 Introduction
In a previous forum discussion post, I asked the question “Who still uses Firmata (and the Johnny Five library)” and one of the replies mentioned using Arduino Firmata with micro:BIT.
I was curious and since I had an original micro:BIT, I couldn’t resist flashing my new Zephyr Firmata onto this micro:BIT and start playing with it. Then thanks to Codex AI in VSCode, I was able to build a fancy new web UI to play with.

The web page looks pretty impressive (in my opinion) and I saw no reason to change it.
Except, I noticed a problem when using the webUI app. If I clicked the LED’s marked 0 to 13 the equivalent LED on the micro:BIT would turn on and if I clicked the same number it would turn off (as expected), but if I clicked on LED 14, LED 0 on the micro:BIT would turn on instead and vice versa (this was unexpected behaviour).
So, was the problem with the webUI, with comms, or with the micro:BIT firmware, and like any problem it takes data and insight to find the solution. And, of course, this often starts with an oscilloscope and/or a logic analyser to “see” what is going on, as demonstrated in this video:
And then the "fun" starts with lots of manual calculations and measurement to laboriously determine timings to see if it reveals anything.
Well now there is an alternative.
2.0 Pairing the Codex AI Agent in VS Code with the ADALM2000
[acknowledgement: this section of the blog was primarily generated by Gemini AI]
Creating a physical AI test bench pairing using the Analog Devices ADALM2000 (M2K) and OpenAI Codex inside VS Code proved rather straightforward thanks to the Analog Digital's libm2k Python library and my very own custom Model Context Protocol (MCP) server for Codex.
For those who don't know, the ADALM2000 is a pocket-sized USB-powered software-defined lab instrument for embedded hardware debugging. Unlike bench-top lab instruments, this handy device needs to be connected to your laptop or PC through the USB connection to control the device (with the Scopy GUI) and to view output data from it. In terms of features, it exposes:
- A 2-channel, 100 MSPS USB oscilloscope (
M2kAnalogIn) for inspecting analogue voltage levels, signal integrity, rise times, and power-rail behaviour. - A 16-channel, 100 MSPS digital logic analyser and pattern generator (
M2kDigital) for capturing multi-pin timing, PWM/multiplexed waveforms, and serial protocols. - A spectrum analyser (noise floor, SFDR, SNR, THD, etc.) and a network analyser (for Bode, Nyquist, Nichols transfer diagrams)
- A 2-channel arbitrary waveform generator, and a programmable power supply.
The ADALM2000 is also application developer friendly.
For example, it is possible to write scripts in Javascript for Scopy, giving you the possibility of automating instrument tasks for different types of applications (i.e control loops). To active you call Scopy via the command line (e.g. scopy --script my_script.js). The other option, which I will be using, is the libm2k library. This allows you to write C++/C#/Python applications that capture and generate data from the host PC. With libm2k, it is also possible to pair the M2K with an AI agent, such as Codex inside VS Code, which opens up all sorts of new automation opportunities, such as debugging real-world physical hardware problems.
You do not need an MCP just to use libm2k, because any local Python script can import libm2k and talk to the ADALM2000 directly.
#!/usr/bin/env python3
import os
import shutil
import subprocess
import tempfile
import libm2k
from fastmcp import FastMCP
mcp = FastMCP("adalm2000-logic")
TRIGGER_MODES = {
"rising": libm2k.RISING_EDGE_DIGITAL,
"falling": libm2k.FALLING_EDGE_DIGITAL,
"any": libm2k.ANY_EDGE_DIGITAL,
"high": libm2k.HIGH_LEVEL_DIGITAL,
"low": libm2k.LOW_LEVEL_DIGITAL,
}
def _parse_dio_index(val: int | str) -> int | None:
if isinstance(val, int) and 0 <= val <= 15:
return val
if isinstance(val, str):
s = val.strip().upper()
if s.startswith("DIO") and s[3:].isdigit():
idx = int(s[3:])
return idx if 0 <= idx <= 15 else None
if s.isdigit():
idx = int(s)
return idx if 0 <= idx <= 15 else None
return None
def _decode_with_sigrok(
raw: list[int],
ordered_channels: list[int],
sample_rate_hz: int | float,
protocol: str,
protocol_options: dict[str, str | int] | None,
annotations: str | None,
) -> list[str]:
if shutil.which("sigrok-cli") is None:
raise RuntimeError(
"sigrok-cli is not installed. Run: sudo apt install -y sigrok-cli"
)
# Build sigrok -P argument: e.g. i2c:scl=DIO0:sda=DIO1
decoder_parts = [protocol.strip()]
if protocol_options:
for k, v in protocol_options.items():
dio_idx = _parse_dio_index(v)
# Normalize bare pin numbers (e.g. scl=0) to CSV header names (DIO0)
formatted_val = (
f"DIO{dio_idx}"
if dio_idx is not None
and k.lower()
in {
"scl",
"sda",
"clk",
"sck",
"mosi",
"miso",
"cs",
"rx",
"tx",
"data",
"d0",
"d1",
}
else str(v)
)
decoder_parts.append(f"{k}={formatted_val}")
decoder_spec = ":".join(decoder_parts)
with tempfile.NamedTemporaryFile("w", suffix=".csv", delete=False) as tmp:
tmp_path = tmp.name
tmp.write(",".join(f"DIO{ch}" for ch in ordered_channels) + "\n")
for sample in raw:
s = int(sample)
tmp.write(
",".join("1" if (s >> ch) & 1 else "0" for ch in ordered_channels)
+ "\n"
)
try:
cmd = [
"sigrok-cli",
"-I",
f"csv:header=yes:column_formats=*l:samplerate={sample_rate_hz}",
"-i",
tmp_path,
"-P",
decoder_spec,
]
if annotations:
cmd.extend(["-A", annotations])
proc = subprocess.run(cmd, capture_output=True, text=True, check=False)
if proc.returncode != 0:
raise RuntimeError(
f"sigrok-cli failed ({proc.returncode}): {proc.stderr.strip()}"
)
return [line for line in proc.stdout.splitlines() if line.strip()]
finally:
if os.path.exists(tmp_path):
os.remove(tmp_path)
@mcp.tool()
def capture_logic_trace(
channels: list[int] | None = None,
sample_rate_hz: int = 1_000_000,
num_samples: int = 16384,
trigger_channel: int | None = None,
trigger_edge: str = "falling",
pretrigger_samples: int = 0,
timeout_ms: int = 3000,
protocol: str | None = None,
protocol_options: dict[str, str | int] | None = None,
protocol_annotations: str | None = None,
) -> dict:
"""
Capture digital logic from an ADALM2000 and optionally decode I2C, SPI, UART, or other
sigrok protocols.
Args:
channels: DIO pin indices to monitor (0-15). Auto-populated from protocol_options if omitted.
sample_rate_hz: Sampling rate in Hz (e.g., 1000000 for 1 MSPS, up to 100000000).
num_samples: Number of samples to acquire (default 16384).
trigger_channel: Optional DIO pin (0-15) to trigger acquisition on.
trigger_edge: 'rising', 'falling', 'any', 'high', or 'low'.
pretrigger_samples: Samples to retain before the trigger (0-8192). Requires
trigger_channel and must be smaller than num_samples.
timeout_ms: USB acquisition timeout in milliseconds.
protocol: Optional sigrok decoder ID: 'i2c', 'spi', 'uart', 'onewire_link', etc.
protocol_options: Key/value options for the decoder, e.g.:
- I2C: {"scl": "DIO0", "sda": "DIO1"}
- SPI: {"clk": "DIO0", "mosi": "DIO1", "miso": "DIO2", "cs": "DIO3", "cpol": 0, "cpha": 0}
- UART: {"rx": "DIO0", "baudrate": 115200}
protocol_annotations: Optional sigrok -A filter (e.g., "i2c=address-write:data-write:data-read").
"""
if sample_rate_hz <= 0:
raise ValueError("sample_rate_hz must be greater than zero.")
if num_samples <= 0:
raise ValueError("num_samples must be greater than zero.")
if timeout_ms <= 0:
raise ValueError("timeout_ms must be greater than zero.")
if pretrigger_samples < 0 or pretrigger_samples > 8192:
raise ValueError("pretrigger_samples must be between 0 and 8192.")
if pretrigger_samples and trigger_channel is None:
raise ValueError("pretrigger_samples requires trigger_channel.")
if pretrigger_samples >= num_samples:
raise ValueError("pretrigger_samples must be smaller than num_samples.")
active_channels = set(channels or [])
if protocol_options:
for k, v in protocol_options.items():
if k.lower() in {
"scl",
"sda",
"clk",
"sck",
"mosi",
"miso",
"cs",
"rx",
"tx",
"data",
"d0",
"d1",
}:
idx = _parse_dio_index(v)
if idx is not None:
active_channels.add(idx)
if trigger_channel is not None:
active_channels.add(trigger_channel)
if not active_channels or any(ch < 0 or ch > 15 for ch in active_channels):
raise ValueError(
"Provide valid DIO channels (0-15) via 'channels' or 'protocol_options'."
)
ordered_channels = sorted(active_channels)
ctx = libm2k.m2kOpen()
if ctx is None:
raise RuntimeError("No ADALM2000 found. Check USB connection and close Scopy.")
try:
ctx.setTimeout(timeout_ms)
dig = ctx.getDigital()
dig.reset()
dig.setSampleRateIn(sample_rate_hz)
actual_sample_rate_hz = float(dig.getSampleRateIn())
if actual_sample_rate_hz <= 0:
raise RuntimeError(
f"ADALM2000 returned an invalid sample rate: {actual_sample_rate_hz}"
)
watch_mask = 0
for ch in ordered_channels:
dig.setDirection(ch, libm2k.DIO_INPUT)
dig.enableChannel(ch, True)
watch_mask |= 1 << ch
trig = dig.getTrigger()
for ch in range(16):
trig.setDigitalCondition(ch, libm2k.NO_TRIGGER_DIGITAL)
if trigger_channel is not None:
mode = TRIGGER_MODES.get(trigger_edge.lower())
if mode is None:
raise ValueError(
f"Invalid trigger_edge '{trigger_edge}'. Use: {list(TRIGGER_MODES)}"
)
trig.setDigitalSource(libm2k.SRC_NONE)
trig.setDigitalCondition(trigger_channel, mode)
trig.setDigitalDelay(-pretrigger_samples)
raw = dig.getSamples(num_samples)
us_per_sample = 1_000_000.0 / actual_sample_rate_hz
decoded_lines = None
if protocol:
decoded_lines = _decode_with_sigrok(
raw,
ordered_channels,
actual_sample_rate_hz,
protocol,
protocol_options,
protocol_annotations,
)
events = []
prev_state = None
for idx, sample in enumerate(raw):
state = int(sample) & watch_mask
if state != prev_state:
pin_levels = {f"DIO{ch}": (state >> ch) & 1 for ch in ordered_channels}
events.append(
{
"sample": idx,
"time_us": round(idx * us_per_sample, 3),
"time_from_trigger_us": (
round((idx - pretrigger_samples) * us_per_sample, 3)
if trigger_channel is not None
else None
),
"hex": f"0x{state:04X}",
"pins": pin_levels,
}
)
prev_state = state
result = {
"requested_sample_rate_hz": sample_rate_hz,
"sample_rate_hz": actual_sample_rate_hz,
"total_samples": len(raw),
"duration_us": round(len(raw) * us_per_sample, 2),
"state_segment_count": len(events),
"transition_count": max(0, len(events) - 1),
}
if trigger_channel is not None:
result.update(
{
"trigger_channel": trigger_channel,
"trigger_edge": trigger_edge.lower(),
"trigger_sample": pretrigger_samples,
"pretrigger_samples": pretrigger_samples,
}
)
if decoded_lines is not None:
result["protocol"] = protocol
result["decoded_count"] = len(decoded_lines)
result["decoded_frames"] = decoded_lines[:500]
result["decoded_truncated"] = len(decoded_lines) > 500
# Keep raw edge list compact when protocol decoding is active
result["transitions_preview"] = events[:50]
else:
result["transitions"] = events[:500]
result["truncated"] = len(events) > 500
return result
finally:
libm2k.contextClose(ctx)
if __name__ == "__main__":
mcp.run()
However, giving Codex access through a dedicated MCP server (m2k_logic_mcp.py - see code above) is far cleaner and more reliable than having the AI generate temporary scripts on every turn:
- Clean connection between Codex and USB hardware. Codex sends a structured command request, and the local Python process runs the libm2k calls using the host Python environment where the libm2k hardware libraries are already installed.
- Read-only pin safety. Codex can only read digital inputs through capture_logic_trace, so it cannot accidentally drive voltages onto your target board.
- Upfront parameter checks. Invalid sample rates, timeouts, pin numbers, or pre-trigger settings are caught before the USB connection is opened.
- Automatic USB cleanup. Even if a capture times out or fails, the server closes the ADALM2000 connection automatically, even if a capture times out or fails, so the hardware never stays locked.
- Compact summaries instead of raw buffers. Rather than flooding the VS Code chat with thousands of raw 1s and 0s, the server condenses the capture into pin state changes and timestamps.
- Repeatable measurements. Sample rate, capture length, trigger edge, timeout, and active pins are passed as explicit settings rather than relying on hidden menu states.
- Built-in protocol decoding. Captures can optionally be passed to sigrok-cli to decode I2C, SPI, UART, or 1-Wire traffic automatically.
The key is separating control from physical measurement.

In the illustrated setup, the web application and the measurement system use two independent paths.
There's the control path, which requests via the web page a LED state to change. This is then communicated over Firmata to the micro:BIT, which then sets the GPIO high or low. The measurement path, then independently observes the resulting physical GPIO waveforms (as seen in the video) to determine whether the GPIO logic state changed or not.
The goal of the measurement path is to confirm that a successful Firmata packet or updated browser grid actually caused a physical GPIO pin state to change, which then validates what the software intended to do. The browser web-app never communicates with the ADALM2000, and the MCP server never touches the Firmata serial port (/dev/ttyACM0). The Node.js server remains the sole owner of the micro:bit serial link, while the MCP server temporarily claims the ADALM2000 over USB for each capture.
When we introduce AI into the mix, it requires an access point to the measurement path. In this particular setup we keep the control path independent, but in theory we could also like that to AI for more autonomous operation.
The bridge between the measurement path and Codex is a small Python script (m2k_logic_mcp.py) built with FastMCP. Codex launches it in the background, communicates with it over standard input/output, and uses it to run a Python function called capture_logic_trace.
Inside the Python script (m2k_logic_mcp.py), capture_logic_trace is a Python function marked with @mcp.tool(). That tag tells FastMCP to register the function with Codex as an available hardware command, complete with its argument names, data types, and description. When Codex wants to inspect the micro:BIT pins, it does not write or execute a new script. Instead, Codex sends a structured JSON request naming capture_logic_trace along with the capture settings it wants, such as which DIO pins to watch and how fast to sample them. FastMCP unpacks those JSON values into the Python function arguments, runs the capture against the ADALM2000 over USB, and returns a compact JSON summary of the recorded pin transitions back to VS Code.
Thus, in summary, three pieces make up the server runtime:
- FastMCP inspects the capture_logic_trace Python function, registers it as an available command for Codex in VS Code, and translates JSON requests and responses over standard input/output.
- libm2k opens the connected ADALM2000 (libm2k.m2kOpen()), configures the digital inputs, and records the pin states.
- sigrok-cli (optional) runs only when protocol decoding is requested, exporting selected channels to a temporary CSV file, collecting decoded frames, and removing the temporary file afterward.
It's worth noting that Codex and the Python script run as separate processes, thus Codex cannot call the capture_logic_trace function directly in memory. Instead, it passes a JSON data structure containing the capture settings it wants to use.
{
"channels": [0],
"sample_rate_hz": 1000000,
"num_samples": 100000
}
FastMCP then maps each JSON field to the matching parameter in def capture_logic_trace(...) and executes the capture.
Any trigger pin or protocol decoder pin is automatically included in the active channel list, and at least one valid DIO channel must be selected.
|
JSON Request Field |
What It Controls |
|
|
ADALM2000 DIO pin numbers to watch, from 0 through 15 |
|
|
Requested digital sampling rate in Hz (defaults to 1 MHz) |
|
|
Total number of samples to record (defaults to 16,384) |
|
|
Optional DIO pin used to trigger the capture |
|
|
Trigger condition (rising, falling, any, high, or low) |
|
|
Samples kept before the trigger event, from 0 through 8,192 |
|
|
USB capture timeout in milliseconds (defaults to 3,000 ms) |
|
|
Optional sigrok decoder name, such as i2c, spi, or uart |
|
|
Decoder pin assignments and protocol settings |
|
|
Optional filter for decoded protocol annotations |
Whenever Codex invokes capture_logic_trace, the Python function runs through the same 11 steps:
- Checks that all requested settings are valid.
- Opens the connected ADALM2000 over USB.
- Sets the USB capture timeout.
- Resets the ADALM2000 digital pins.
- Requests the target sample rate and reads back the actual rate accepted by the hardware clock so timestamps stay accurate.
- Configures every selected DIO pin as an input.
- Clears old trigger settings and applies the requested trigger.
- Records the requested number of samples.
- Runs sigrok-cli if protocol decoding was requested.
- Condenses the raw readings into a list of pin states and timestamped changes.
- Closes the connection to the ADALM2000.
The returned JSON object reports the requested and accepted sample rates, total sample count, capture duration, trigger details, and a list of timestamped pin changes (sample index, timestamp, hexadecimal pin summary, and individual pin levels). Transitions are capped at 500 entries (or 50 entries alongside up to 500 decoded protocol frames) so the output stays readable in VS Code.
3.0 Debugging the micro:MIT LED Matrix in Action
For the micro:bit LED matrix investigation, only two wires were needed between the ADALM2000 and the micro:bit edge connector.
ADALM2000 GND -> micro:bit GND ADALM2000 DIO0 -> micro:bit edge connector P3

Edge pin P3 (nRF51822 P0.04) is one of the display's active-low multiplexed column lines, shared by Firmata pixels 0, 14, and 22. Because the display scans columns continuously rather than holding a static level, a logic capture reveals the exact refresh pulse width and period.
|
User action |
DIO0 observation |
Physical display observation |
|
Display blank |
Steady HIGH |
No selected pixel lit |
|
Pixel 0 ON |
Repeating active-low pulses (~2.174 ms low, ~19.8 ms period) |
Pixel 0 lit |
|
Pixel 0 OFF |
Returned to steady HIGH |
Pixel 0 extinguished |
|
Pixel 14 ON (before fix) |
P3 showed the same class of active-low pulses |
Pixel 0 lit instead of Pixel 14 |
|
Pixel 14 ON (after fix) |
P3 column activity present as expected |
Pixel 14 lit correctly |
My Prompt Log
Prompt: If I click on Pixel 14 nothing turns on (0 to 13 is fine). If I click it again, it turns off on the web page but then Pixel 0 turns off on the microbit. Before we make any code changes let's consider if the Logic analyser lab will help here. E.g. P3
| Reponse1 | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
Yes—P3 is particularly useful because Firmata pixels 0, 14, and 22 all share the same physical active-low matrix column:
The fact that operating pixel 14 appears to affect pixel 0 may be significant because they share P3. Run this controlled test with no other pixels illuminated:
Interpretation:
One limitation: P3 cannot distinguish pixels 0, 14, and 22 when more than one is enabled. Each test must start from a completely blank matrix. Also, pin 14 is not an ordinary 8-pin Firmata boundary: it is port 1, bit 6. Pin 15 is the bit-7 boundary. That makes the shared P3 matrix wiring more suspicious than a straightforward Firmata port-boundary error. |
Prompt: I have connected P3 to the logic analyser. If I open Scopy I can see a logic change on DIO0. I have now closed Scopy. I want you to monitor using libm2k. I will open the web UI page. You instruct and then I will confirm.
| Reponse2 |
|---|
|
Baseline confirmed: I captured all 16 digital inputs for 20 ms at 1 MS/s.
Step 2:
I’ll then capture DIO0 and confirm whether P3 carries the expected active-low multiplexing pulses. |
Prompt: Ready.
| Reponse3 |
|---|
|
Pixel 0 is confirmed electrically on P3:
This matches the expected multiplexed column signal. Step 3:
I’ll verify that DIO0 returns to steady HIGH before testing pixel 14. |
Prompt: Ready.
| Reponse4 |
|---|
|
Pixel 0 switched off correctly:
Step 4:
I’ll capture P3 and determine whether pixel 14 reached the physical display driver. |
Prompt: Ready.
| Reponse5 |
|---|
|
Pixel 14 definitely reached the physical display subsystem:
This is essentially the same electrical signature as pixel 0. Therefore, the fault is not the web click, Firmata transport, or digital-port selection. The display driver is activating the P3 column for pixel 14. Before switching it off: what exactly is visible on the physical micro:bit right now—no LED at all, the expected row-3 rightmost LED, or a different LED? |
Prompt: Pixel 0 is on not 14.
| Reponse6 |
|---|
|
That confirms a logical framebuffer mapping defect: Firmata pixel 14 is producing the correct P3 column activity, but the display driver renders it at physical pixel 0. Step 5:
I’ll simultaneously verify that P3 returns to steady HIGH. This will confirm that web pixel 14—not stale state—is directly controlling physical pixel 0. |
Prompt: Pixel 0 turns off
| Reponse7 | ||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
The logic-analyser lab exposed the cause, and no code has been changed. Johnny-Five identifies a board with exactly 25 pins as an Arduino Leonardo: const pinsToType = { 20: "UNO", 25: "LEONARDO", 70: "MEGA" }; Leonardo normalization translates digital pin 14 to A0, then converts A0 to pin 0: Web pixel 14 → Johnny-Five Led pin 14 → Leonardo alias A0 → Firmata pin 0 → physical pixel 0 That exactly matches the HIL evidence:
This also predicts additional aliases:
Pixels 0–13 work because Johnny-Five does not translate them. Pixels 20–24 should remain unchanged by this particular alias table. The appropriate fix is to stop using Johnny-Five’s Led abstraction for these virtual display pins. The server should write directly through board.io.pinMode() and board.io.digitalWrite(), preserving pin numbers 0–24 exactly. That retains Firmata and Johnny-Five’s board connection while bypassing Arduino-specific pin normalization. |
Prompt: Proceed to make changes.
| Reponse8 |
|---|
|
The server now bypasses Johnny-Five’s Arduino pin normalization:
Restart the server: # Ctrl+C npm start Then:
Leave P3 connected to DIO0; I’ll capture it again after your observation. |
Prompt: Pixel 14 turns now turns on.
| Reponse9 |
|---|
|
Confirmed visually and electrically. With corrected pixel 14 on:
Pixel 14 now controls physical pixel 14 while retaining the expected P3 column signal. The Johnny-Five Leonardo pin-alias issue is resolved. |
Why electrical evidence plus visual checks mattered
A single P3 trace cannot tell pixels 0, 14, and 22 apart because all three share that column, and the matrix row lines are not wired to the micro:bit edge connector. Combining the ADALM2000's electrical proof (showing that the firmware really did drive column P3 at ~50.5 Hz) with a one-pixel-at-a-time visual check supplied the missing row context and pinpointed the Johnny-Five board-type rule right away.
4.0 Conclusion
Codex was able to read the logic analyser data directly through the libm2k MCP bridge while I guided the bench steps and added visual observations. Having an AI agent in VS Code that can both inspect the codebase and verify real electrical signals on the bench turned a puzzling LED matrix bug into a quick, evidence-backed fix.
This really proved to be a great time saver.
In fact, this is only the beginning.
For my next step I plan to create some bridging software using SCPI to send and receive SCPI commands in my LabVIEW Community edition.
Exciting times ahead…