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.

Raspberry Pi 4 Health Flags: A Past Undervoltage Is Not a Current Fault

You read throttled=0x10000 and conclude that your Raspberry Pi is undervolting right now. The number looks alarming, but that conclusion confuses a historical flag with a current one. This lesson builds a small read-only diagnostic tool that keeps those meanings separate, preserves the raw report and says โ€œunknownโ€ when a command fails.

The reference hardware is a Raspberry Pi4 ModelB,2GB,revision1.5, whose documented revision code is b03115. The supply is the official Universal Serial Bus Type-C (USB-C) power-supply model with nominal5.1V,3A output; record the actual regional version on your bench. No new sensor or GPIO wiring is required. GPIO means general-purpose input/output; we leave that header alone for this experiment.

Verification: actual delivered CPython code is exercised with fake firmware replies and real execution of its explicitly synthetic demo. No Pi commands were executed on hardware, no power or thermal trial was performed, and no firmware binary was built. Example temperatures, frequencies and bitmasks are teaching fixtures, not measurements.

Freeze the environment before interpreting it

Our named software baseline is Raspberry Pi OS Legacy Lite64-bit,Bookworm,release6October2026, with the Python3.11-or-later standard-library application programming interface (API), the callable software interface. The official download listing identified kernel family6.12 and the image 2026-10-06-raspios-bookworm-arm64-lite.img.xz. Its published SHA256 (Secure Hash Algorithm,256-bit) was 9e938c5a6981c3f498b3b564c527f3e1fd58ef20bbf703be0eea748384a6c1af. This is a publisher listing checked for the article; we did not download, hash or run the image.

OS means operating system, the software managing the machine. Bookworm is Debian12’s release name. Updates can change the kernel, interpreter and firmware without changing that name. Therefore a real trial must record /etc/rpi-issue, OS release, kernel, Python version and vcgencmd version. An image filename alone is not a measured firmware version. The blank trial sheet has places for the actual values.

This deliberately narrow program refuses a different board revision or a non-Bookworm environment with UNSUPPORTED_BASELINE. That does not mean another Pi is defective. It means this lesson has not silently extended its interpretation to a different configuration. The program reads identity before issuing firmware queries. Its board check is an experiment boundary, not a general-purpose recommendation to identify all Pis by one hard-coded revision.

Normal power and cooling are enough

Normal official USB-C supply powers a Pi4 ModelB2GB revisionb03115; no GPIO wiring. A read-only Python snapshot records identity and issues four bounded vcgencmd queries, preserving command errors as unknown results.
Original connection and data-flow diagram. USB-C power is the normal board input; the diagnostic path is software, not a new voltage sensor.
  • Use the named Pi with its normal case/cooling arrangement, official USB-C supply, boot storage and ordinary network/console access.
  • Keep power and cooling protections enabled. No deliberate undervoltage, damaged cable, covered heatsink, overclock or forced reboot is part of this procedure.
  • Save the supplied file in your home project directory. It needs no third-party Python package and does not require administrator privileges for the operations it requests.
  • If the tool or a device permission is missing, record the actual error. Do not replace the error with a successful example or run an unrelated installer merely to make a graph look healthy.

The official power recommendation for Pi4 is a3A USB-C source. A current rating is capacity, not a command forcing3A through the board. Real current depends on activity, peripherals and supply conditions. The diagnostic flag is not a supply voltmeter: it does not give the exact5V rail waveform, cable resistance or peak current. A quiet current flag also cannot certify every peripheral’s power quality.

Read bits rather than the whole number as a verdict

A bitfield stores several independent yes/no conditions in one integer. Hexadecimal notation, marked by0x, is a compact way to display it. The documented low four-bit group (a nibble),bits0โ€“3, names current undervoltage, Arm-frequency capping, throttling and soft-temperature-limit status. Bits16โ€“19 are the corresponding โ€œhas occurredโ€ flags. Arm is the processor-core family name; here the command observes that core clock.

Synthetic get_throttled observations show current undervoltage bit0 clearing while historical bit16 remains set. A failed query is an unknown observation, not zero; segments illustrate samples and do not recover intervening events.
Original synthetic current/history traces from one illustrative boot session. No power fault was induced, and a history flag supplies neither timestamp nor duration.
Synthetic report Supported interpretation What it does not establish
0x0 Known reported flags are clear All hardware is healthy
0x10000 Undervoltage has occurred; known current flags are clear Exact event time or a present voltage fault
0x10001 Current undervoltage plus its historical counterpart Which connector or supply caused it
0x50005 Current undervoltage/throttling and both historical counterparts Duration or complete event chronology
0x100000 A bit outside the documented mask is set A meaning invented by this decoder

The common firmware vocabulary includes a soft-temperature-limit bit, but the current Pi4 hardware documentation states that no soft limit is defined for Pi4. The decoder retains the documented name if firmware reports it; it does not promise that this bit will occur on this board. Do not copy another model’s thermal thresholds or assume that every frequency-capping event has one temperature cause.

The known mask is 0x000F000F. The decoder obtains current bits with raw&0xF and historical bits with (raw>>16)&0xF. It separately keeps raw&~0x000F000F as unknown bits. For example,131,072 is2ยนโท, a historical-frequency-capping bit; it is not a large temperature reading. Keeping the raw value makes later interpretation possible when firmware documentation changes.

History is not a timestamp

A sticky flag remembers that a condition happened. It contains no time-of-day, duration, count or root-cause explanation. Record the Linux boot ID, an identifier for the running boot session, when comparing samples. If that ID changes, do not merge the before/after values into one continuous history. This lesson does not mutate or clear firmware history and does not guarantee persistence across restarts or other software’s interactions.

A historical flag present in your first sample may predate the experiment. A newly seen historical bit between two samples narrows when your software first observed it, but it still does not reconstruct every event inside that interval. A current bit can appear and disappear between polls. Our tool produces individual snapshots rather than claiming an exhaustive event logger or uptime monitor.

A lower clock is not automatically a fault

DVFS, dynamic voltage and frequency scaling, changes operating conditions with demand. An idle Pi can run its Arm cores at a lower clock than a busy one without a fault. measure_clock arm reports a clock frequency in hertz; one megahertz is one million cycles per second. The value is a separate observation from get_throttled. Never label every reading below a nominal maximum โ€œthermal throttling.โ€

measure_temp reports the system-on-chip’s internal temperature channel. A SoC, system on a chip, integrates the processor and other functions; this reading is not ambient room temperature or an external connector temperature. Temperature and frequency can help explain context, but they do not prove the cause of a historical flag. The code’sโˆ’40โ€ฆ150ยฐC and0โ€ฆ4GHz parser bounds are sanity policies, not operating ratings or claimed sensor accuracy.

Complete read-only program

Download the complete CPython program (ZIP; file: batch-005/code/pi4-health-flags.py). Its command-line interface (CLI) selects one explicit mode. Run python3 pi4-health-flags.py --demo on a normal computer first. It prints clearly labeled synthetic cases and never calls a hardware command. On the named real Pi baseline, python3 pi4-health-flags.py --live requests an actual snapshot. No default invocation silently starts collecting data.

Complete program
"""Read-only Pi4 revisionb03115 diagnostics. CPython3.11+; --demo never queries hardware."""
import json
import math
import re
import subprocess
import sys
import time

TOOL = "/usr/bin/vcgencmd"
NAMES = ("undervoltage", "arm_frequency_capped", "throttled", "soft_temperature_limit")
KNOWN_MASK = 0x000F000F


def decode_throttled(text):
    match = re.fullmatch(r"throttled=0x([0-9a-fA-F]{1,8})", text.strip())
    if not match:
        raise ValueError("malformed throttled bitfield")
    raw = int(match[1], 16)
    current = [name for bit, name in enumerate(NAMES) if raw & (1 << bit)]
    historical = [name for bit, name in enumerate(NAMES) if raw & (1 << (bit + 16))]
    unknown = raw & ~KNOWN_MASK
    state = ("UNKNOWN_BITS" if unknown else "CURRENT_FLAGS" if current else
             "HISTORY_ONLY" if historical else "KNOWN_FLAGS_CLEAR")
    return {"raw_hex": hex(raw), "current": current, "historical": historical,
            "unknown_bits_hex": hex(unknown), "interpretation": state,
            "all_hardware_healthy_proved": False}


def decode_temperature(text):
    match = re.fullmatch(r"temp=(-?[0-9]+(?:\.[0-9]+)?)'C", text.strip())
    if not match:
        raise ValueError("malformed temperature")
    value = float(match[1])
    if not math.isfinite(value) or not -40 <= value <= 150:
        raise ValueError("temperature outside parser sanity policy")
    return {"temperature_C": value}


def decode_clock(text):
    match = re.fullmatch(r"frequency\(([0-9]{1,3})\)=([0-9]{1,10})", text.strip())
    if not match:
        raise ValueError("malformed clock")
    hz = int(match[2])
    if not 0 < hz <= 4_000_000_000:
        raise ValueError("clock outside parser sanity policy")
    return {"clock_id": int(match[1]), "arm_Hz": hz}


def text_report(text):
    if not text.strip():
        raise ValueError("empty version report")
    return {"report": text.strip()}


def query(arguments, parser, runner=subprocess.run):
    try:
        result = runner([TOOL] + list(arguments), capture_output=True, text=True,
                        encoding="utf-8", errors="strict", timeout=2.0,
                        check=False, shell=False)
        if result.returncode != 0:
            raise ValueError("command exit " + str(result.returncode))
        if len(result.stdout) > 4096:
            raise ValueError("unexpectedly long command response")
        return {"valid": True, "raw": result.stdout.strip(), "value": parser(result.stdout)}
    except (OSError, subprocess.TimeoutExpired, UnicodeError, ValueError) as error:
        return {"valid": False, "raw": None, "value": None, "error": type(error).__name__ + ": " + str(error)}


def read_file(path):
    with open(path, encoding="utf-8") as handle:
        result = handle.read(8193)
    if len(result) > 8192:
        raise ValueError("identity file unexpectedly large")
    return result


def identity(reader=read_file):
    result = {"python": sys.version.split()[0]}
    fields = {"model": "/proc/device-tree/model", "cpuinfo": "/proc/cpuinfo",
              "os_release": "/etc/os-release", "image_issue": "/etc/rpi-issue",
              "boot_id": "/proc/sys/kernel/random/boot_id",
              "kernel": "/proc/sys/kernel/osrelease"}
    for key, path in fields.items():
        try:
            text = reader(path).strip().rstrip("\x00")
            if key == "cpuinfo":
                match = re.search(r"^Revision\s*:\s*([0-9a-fA-F]+)\s*$", text, re.M)
                if not match:
                    raise ValueError("no board revision")
                result["revision"] = match[1].lower()
            elif key == "boot_id":
                if not re.fullmatch(r"[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}", text):
                    raise ValueError("invalid Linux boot identity")
                result[key] = text.lower()
            else:
                if not text:
                    raise ValueError("empty identity field")
                result[key] = text
        except (OSError, UnicodeError, ValueError) as error:
            result[key + "_error"] = str(error)
    result["supported_board"] = (result.get("revision") == "b03115"
                                 and result.get("model", "").startswith("Raspberry Pi 4 Model B"))
    result["bookworm_declared"] = bool(re.search(r'^VERSION_CODENAME=["\']?bookworm["\']?$', result.get("os_release", ""), re.M))
    result["all_identity_fields_recorded"] = all(key in result for key in ("model", "revision", "os_release", "image_issue", "boot_id", "kernel"))
    return result


def snapshot(runner=subprocess.run, reader=read_file, monotonic=time.monotonic):
    environment = identity(reader)
    if not environment["supported_board"] or not environment["bookworm_declared"]:
        return {"mode": "LIVE_REQUESTED", "sample_complete": False, "state": "UNSUPPORTED_BASELINE",
                "identity": environment, "diagnostics": {}}
    try:
        started = monotonic()
        if not math.isfinite(started) or started < 0:
            raise ValueError("invalid monotonic start")
    except (OSError, ValueError) as error:
        return {"mode": "LIVE_REQUESTED", "sample_complete": False, "state": "CLOCK_UNKNOWN", "error": str(error), "identity": environment, "diagnostics": {}}
    diagnostics = {
        "firmware_version": query(["version"], text_report, runner),
        "throttled": query(["get_throttled"], decode_throttled, runner),
        "temperature": query(["measure_temp"], decode_temperature, runner),
        "arm_clock": query(["measure_clock", "arm"], decode_clock, runner)}
    try:
        ended = monotonic()
        duration = ended - started
        if not math.isfinite(ended) or duration < 0:
            raise ValueError("invalid monotonic end")
    except (OSError, ValueError) as error:
        return {"mode": "LIVE_REQUESTED", "sample_complete": False, "state": "CLOCK_UNKNOWN", "error": str(error), "identity": environment, "diagnostics": diagnostics}
    complete = all(row["valid"] for row in diagnostics.values()) and environment["all_identity_fields_recorded"]
    return {"mode": "LIVE_REQUESTED", "sample_complete": complete,
            "state": "RECORDED" if complete else "PARTIAL_UNKNOWN",
            "identity": environment, "monotonic_start_s": started,
            "monotonic_end_s": ended, "duration_s": duration,
            "diagnostics": diagnostics, "atomic_or_simultaneous_snapshot": False}


def main(arguments=None, output=print):
    arguments = sys.argv[1:] if arguments is None else arguments
    if arguments == ["--demo"]:
        data = {"mode": "SYNTHETIC_DEMO_NOT_MEASUREMENT",
                "cases": [decode_throttled("throttled=" + word) for word in
                          ("0x0", "0x10000", "0x10001", "0x50005", "0x100000") ]}
        output(json.dumps(data, indent=2))
        return 0
    if arguments != ["--live"]:
        output("Usage: python3 pi4-health-flags.py --demo | --live")
        return 2
    data = snapshot()
    output(json.dumps(data, indent=2))
    return 0 if data["sample_complete"] else 1


if __name__ == "__main__":
    raise SystemExit(main())

Each command uses an argument list with shell=False and a2second subprocess timeout. That avoids constructing a shell command from a string and bounds each requested command wait under the subprocess API; it is not a hard real-time deadline for every possible operating-system failure. Responses are parsed with exact formats rather than searching arbitrary text for a convenient zero.

A missing executable, nonzero exit status, timeout, decoding problem, malformed reply or implausible value produces valid:false and value:null. JSON, JavaScript Object Notation, is the printed structured text format. A valid throttling reply is retained even if temperature fails; the overall sample is marked PARTIAL_UNKNOWN. Conversely sample_complete:true means all requested records were obtained, not that the board is healthy. Unknown flag meanings remain visible even in a completely recorded sample.

The four queries happen successively. Monotonic start/end values bracket their time window; a monotonic clock measures elapsed time without depending on calendar adjustments. Their difference is collection duration, not synchronization accuracy. A temperature spike or load change can occur between commands. The output explicitly says it is not an atomic or simultaneous snapshot.

A repeatable experiment with safe synthetic faults

  1. Decode the demo first. Predict the meaning of each mask without looking at the output. Check that0x10000 has no current flag while0x10001 has one. Confirm that the unknown-bit example is not called healthy.
  2. Record real identity. On the named configuration, save your observed board revision, OS/image issue, kernel, interpreter and firmware version in the blank worksheet. Compare the baseline deliberately; do not copy the article’s publisher hash into a box labeled โ€œverified on my card.โ€
  3. Take an idle snapshot. Leave normal power/cooling untouched. Record boot ID, raw mask, decoded lists, temperature, Arm clock and sample-complete state. If a historical flag is already present, record it without dating it.
  4. Use an ordinary workload. Repeat during work the Pi normally performs, such as its usual application. Do not force a heat or voltage fault. A changing frequency with no current flag can be normal; note the actual readings instead of expecting a specific synthetic value.
  5. Return to idle. Repeat with the same normal setup and boot identity. Compare current flags separately from historical flags. A history bit remaining set after a current warning disappears is not contradictory.
  6. Inject failures in host tests. The tests simulate command absence, timeout, bad temperature, unknown bits, unsupported board/OS identity and broken monotonic timing. They verify actual application paths without damaging a cable or changing thermal limits.

The blank observation CSV (ZIP; file: batch-005/code/pi4-health-flags-observations-blank.csv) is intentionally empty apart from its header. CSV means comma-separated values, a plain tabular file format. Store real observations only. If a current undervoltage or thermal flag occurs naturally, stop and investigate the ordinary supply/cooling situation before extending a workload; a software label does not repair it.

What can and cannot be concluded

This tool separates known flag meanings, parsing success and environment identity. It cannot diagnose every crash, certify a power supply unit (PSU), validate an SD card, capture every transient or prove that an idle frequency is optimal. It does not compare a firmware report against a certified voltage/temperature standard. The version report is recorded for reproducibility, not authenticated as a secure attestation.

Challenge:0x10000,45ยฐC and600MHzโ€”currently overheated?

Those synthetic values do not establish current overheating. The mask reports historical undervoltage with known current flags clear. Temperature and an idle-compatible clock are separate observations. Check the exact board/firmware context, keep the raw report and avoid inventing an event time or cause. A failed command would instead make the relevant field unknown.

Host tests execute the supplied parsers, argument construction, query-failure handling, identity gate and snapshot assembly. The real demo entry point is run on CPython, but no real Pi command is run. Physical measurements remain future work. For the electrical ideas behind cable drop and power budgets, continue with our electronics lessons. Keep this small diagnostic experiment distinct from a database logger or web dashboard.

Primary references

๐Ÿ“ก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