pyOCD

0.44.0 · active · verified Sat Apr 11

pyOCD is an open-source Python library and command-line tool for programming and debugging Arm Cortex-M microcontrollers using various debug probes such as CMSIS-DAP, J-Link, and ST-Link. It provides a flexible Python API for low-level target control, suitable for automated testing and CI/CD workflows, alongside a powerful command-line interface for common operations like GDB server, flashing, and erasing. Currently at version 0.44.0, pyOCD maintains an active development cycle with several minor releases annually.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to connect to a debug probe, halt the target microcontroller, program a firmware image (HEX format in this example), and then reset and run the target using the pyOCD Python API. Ensure a debug probe is connected and `your_firmware.hex` is replaced with an actual firmware file or created as a dummy for testing.

import time
import logging
import os

from pyocd.core.helpers import ConnectHelper
from pyocd.flash.file_programmer import FileProgrammer

logging.basicConfig(level=logging.INFO)

FIRMWARE_PATH = "your_firmware.hex" # Replace with the actual path to your firmware

# Create a dummy firmware file for demonstration if it doesn't exist
if not os.path.exists(FIRMWARE_PATH):
    with open(FIRMWARE_PATH, "w") as f:
        f.write(":100000000000000000000000000000000000000000\n") # Minimal valid HEX file

try:
    # Connect to the target with the first found probe.
    # For a specific probe, use unique_id="E6616407E3646B29"
    # For a specific target, use options={"target_override": "nrf52840"}
    with ConnectHelper.session_with_chosen_probe() as session:
        target = session.target
        board_id = session.board.unique_id if session.board else "Unknown"
        logging.info(f"Connected to probe: {board_id}, target: {target.name}")

        # Halt the target
        target.halt()
        logging.info("Target halted.")

        # Program firmware
        logging.info(f"Programming {FIRMWARE_PATH}...")
        FileProgrammer(session).program(FIRMWARE_PATH)
        logging.info("Programming complete.")

        # Reset and run
        target.reset_and_run()
        logging.info("Target reset and running.")

        # Allow the target to run for a short period (demonstration)
        time.sleep(1)

except Exception as e:
    logging.error(f"An error occurred: {e}")
    logging.info("Please ensure a debug probe is connected and compatible firmware is specified.")

view raw JSON →