lpcprog#
SPSDK LPC programming package.
This package provides functionality for programming and managing NXP LPC microcontrollers within the SPSDK framework, offering tools for device communication and firmware deployment.
Module representing communication interface#
SPSDK LPCxxx ISP UART communication interface.
This module provides the communication interface for LPCxxx microcontrollers using In-System Programming (ISP) protocol over UART connection.
- class spsdk.lpcprog.interface.LPCProgInterface(device)#
Bases:
objectLPCxxx ISP UART communication interface.
This class provides a communication layer for LPC microcontrollers using the In-System Programming (ISP) protocol over UART. It handles synchronization, command transmission, and response processing for LPC device programming operations.
- Variables:
NEW_LINE – Line terminator sequence for UART communication.
START_SYNC – Initial synchronization character.
SYNC_STRING – Synchronization command string.
SYNC_VERIFIED_STRING – Expected synchronization response.
RC_SLEEP – Sleep interval for return code operations.
Initialize the LPCProgInterface.
- Parameters:
device (
SerialDevice) – Serial device to be used for communication.
- NEW_LINE = '\r\n'#
- RC_SLEEP = 0.05#
- START_SYNC = '?'#
- SYNC_STRING = 'Synchronized\r\n'#
- SYNC_VERIFIED_STRING = 'OK'#
- clear_serial()#
Clear serial communication buffers.
This method flushes all pending data in the serial device buffers including input and output buffers to ensure clean communication state.
- Raises:
SPSDKError – If buffer clearing operation fails.
- Return type:
None
- close()#
Close the UART interface.
- Raises:
SPSDKConnectionError – In any case of fail of UART close operation.
- Return type:
None
- open()#
Open the UART interface.
- Raises:
SPSDKConnectionError – When UART interface cannot be opened.
- Return type:
None
- read_all()#
Read all available data from the device.
This method retrieves all pending data from the connected device buffer. If no data is available, a timeout error is raised.
- Raises:
SPSDKError – When read operation fails
SPSDKTimeoutError – When no data is available to read
- Return type:
bytes- Returns:
Data read from the device
- read_line(decode=True)#
Read line from the device.
The method reads a line of data from the connected device and optionally decodes it as UTF-8. If decoding fails, an empty string is returned instead of raising an exception.
- Parameters:
decode (
bool) – Whether to decode the data as UTF-8 string, defaults to True- Raises:
SPSDKError – When read operation fails
SPSDKTimeoutError – When no data is received (timeout)
- Return type:
str- Returns:
Data read from the device as string (decoded or hex format)
- send_command(command, expect_rc=True)#
Send command to the device and optionally wait for return code.
Writes the specified command string to the device with a newline terminator. If expect_rc is True, waits for and retrieves the return code from the device.
- Parameters:
command (
str) – Command string to send to the device.expect_rc (
bool) – Whether to wait for and return the device return code.
- Return type:
Optional[int]- Returns:
Return code from device if expect_rc is True, None otherwise.
- sync_connection(frequency, retries=10)#
Synchronize connection with the target device.
Establishes communication by exchanging synchronization messages and setting the crystal frequency. The method implements a retry mechanism to handle communication failures during the synchronization process.
Send ? to get baud rate
Receive “Synchronized” message
Send “Synchronized” message
Receive “OK” message
- Parameters:
frequency (
int) – Frequency of the crystal in Hz.retries (
int) – Number of synchronization attempts, defaults to 10.
- Raises:
SPSDKError – Invalid retries parameter (must be positive).
SPSDKConnectionError – Synchronization failed or invalid response.
- Return type:
None
- write(data)#
Send data to device.
- Parameters:
data (
bytes) – Data to send to the device- Raises:
SPSDKError – When sending the data fails
- Return type:
None
- write_string(data)#
Write string to serial device.
- Parameters:
data (
str) – String data to be written to the serial device.- Raises:
SPSDKError – If writing to the serial device fails.
- Return type:
None
Module representing communication protocol#
ISP Communication protocol for LPC devices.
This module implements the In-System Programming (ISP) communication protocol for NXP LPC microcontrollers, providing low-level protocol handling and device interaction capabilities for secure provisioning operations.
- class spsdk.lpcprog.protocol.LPCProgCRPLevels(tag, label, description=None)#
Bases:
SpsdkEnumLPC Code Read Protection (CRP) levels enumeration.
This enumeration defines the available Code Read Protection levels for LPC microcontrollers. CRP is a security mechanism that restricts access to on-chip flash and ISP functionality by programming specific patterns at flash offset 0x0000 02FC. Each level provides different restrictions on SWD access and ISP command availability, while IAP commands remain unaffected.
- CRP1 = (1499702940, 'CRP1', 'SWD Disabled, ISP commands restricted. Cannot write sector 0 and read memory.')#
- CRP2 = (2520082890, 'CRP2', 'SWD Disabled, ISP only allows erase of all sectors')#
- CRP3 = (1666817190, 'CRP3', 'SWD Disabled, ISP disabled.')#
- NO_CRP = (4294967295, 'NO_CRP', 'All USART ISP commands are supported.')#
- NO_ISP = (1399499925, 'NO_ISP', 'Access to the chip via the SWD pins is enabled, ISP pins disabled')#
- class spsdk.lpcprog.protocol.LPCProgProtocol(interface, print_func, device=None)#
Bases:
objectLPCProg communication protocol handler.
This class implements the LPCProg protocol for communicating with NXP LPC microcontrollers, providing low-level operations for device programming, synchronization, and status management.
- Variables:
UNLOCK_CODE – Magic unlock code for device operations.
SECTOR_SIZE – Standard sector size in bytes.
PAGE_SIZE – Standard page size in bytes.
ALLOWED_BAUD_RATES – List of supported communication baud rates.
Initialize the LPCProgProtocol.
Sets up the protocol handler with the specified interface and configuration options. Opens the interface and initializes internal state tracking.
- Parameters:
interface (
LPCProgInterface) – Communication interface for LPC programming operations.print_func (
Callable[[str],None]) – Function to handle output messages during operations.device (
Optional[LPCDevice]) – Optional LPC device specification for targeted operations.
- ALLOWED_BAUD_RATES = [9600, 19200, 38400, 57600, 115200, 230400, 460800]#
- ALLOWED_BAUD_RATES_STR = ['9600', '19200', '38400', '57600', '115200', '230400', '460800']#
- CRC_VECT_TABLE_OFFSET = 28#
- CRP_LENGTH = 4#
- CRP_OFFSET = 764#
- PAGE_SIZE = 64#
- SECTOR_SIZE = 1024#
- UNLOCK_CODE = 23130#
- VECT_TABLE_SIZE = 32#
- assert_rc(status)#
Assert command execution status and raise exception on failure.
This method checks if the provided status indicates success and raises an SPSDKError with the latest status information if the command failed.
- Parameters:
status (
bool) – Boolean indicating whether the command was successful.- Raises:
SPSDKError – When status is False, indicating command failure.
- Return type:
None
- blank_check_sectors(start_sector, end_sector, print_status=True)#
Check if one or more sectors of on-chip flash memory are blank.
This command verifies whether the specified range of flash memory sectors contains only erased (blank) data. If sectors are not blank, it provides details about the first non-blank word found.
- Parameters:
start_sector (
int) – Starting sector number for blank check.end_sector (
int) – Ending sector number for blank check.print_status (
bool) – Whether to print status messages during operation.
- Return type:
bool- Returns:
True if all specified sectors are blank, False otherwise.
- static calc_crc(data)#
Calculate CRC from the data.
The method uses CRC32 algorithm to compute checksum for the provided data bytes.
- Parameters:
data (
bytes) – Data bytes to calculate CRC from.- Return type:
int- Returns:
Calculated CRC32 checksum as integer.
- calculate_page_count(data)#
Calculate number of pages needed for writing the data.
The method calculates how many device pages are required to store the given data by dividing the data length by the device page size and rounding up.
- Parameters:
data (
bytes) – Binary data to be written to the device.- Return type:
int- Returns:
Number of pages required to store the data.
- calculate_sector_count(data)#
Calculate number of sectors needed for writing the data.
This method determines how many device sectors are required to accommodate the given data based on the device’s sector size.
- Parameters:
data (
bytes) – Binary data to be written to the device.- Return type:
int- Returns:
Number of sectors required to store the data.
- close()#
Close the communication interface.
Safely closes the active communication interface if one is currently open. The method performs cleanup operations to ensure proper resource management.
- Return type:
None
- compare(dst_address, src_address, length, print_status=True)#
Compare memory contents at two locations.
This command compares the memory contents between destination and source addresses for the specified length and reports whether they are identical.
- Parameters:
dst_address (
int) – Destination memory address to compare.src_address (
int) – Source memory address to compare.length (
int) – Number of bytes to compare (must be multiple of 4).print_status (
bool) – Whether to print status messages during operation.
- Raises:
SPSDKAlignmentError – If length is not multiple of 4.
- Return type:
bool- Returns:
True if memory contents are identical, False otherwise.
- copy_ram_to_flash(flash_address, ram_address, length, print_status=True)#
Copy data from RAM to flash memory.
This command programs the flash memory by copying data from RAM. The “Prepare Sector(s) for Write Operation” command should precede this command. The affected sectors are automatically protected again once the copy command is successfully executed. This command is blocked when code read protection is enabled.
- Parameters:
flash_address (
int) – Starting address in flash memory where data will be written.ram_address (
int) – Starting address in RAM where data will be read from.length (
int) – Number of bytes to copy from RAM to flash.print_status (
bool) – Whether to print command execution status.
- Return type:
bool- Returns:
True if data was successfully copied to flash, False otherwise.
- decode_part_id(part_id)#
Decode part ID from the database and identify the corresponding device.
This method converts the input part ID to a standardized hex format and searches through all available device families in the LPCPROG database to find a matching part ID. When found, it sets the device attribute and returns the decoded name.
- Parameters:
part_id (
str) – Raw part ID value to decode (string or numeric format)- Raises:
SPSDKValueError – When part_id cannot be converted to integer
- Return type:
Optional[str]- Returns:
Decoded part ID name if found, None if no match exists in database
- erase_page(start_page, end_page, print_status=True)#
Erase one or more pages of on-chip flash memory.
This command sends an erase command to the target device to clear the specified range of flash memory pages.
- Parameters:
start_page (
int) – Starting page number to erase.end_page (
int) – Ending page number to erase (inclusive).print_status (
bool) – Whether to print command status information.
- Return type:
bool- Returns:
True if pages were successfully erased, False otherwise.
- erase_sector(start_sector, end_sector, print_status=True)#
Erase one or more sectors of on-chip flash memory.
This command only allows erasure of all user sectors when the code read protection is enabled.
- Parameters:
start_sector (
int) – Starting sector number to erase.end_sector (
int) – Ending sector number to erase.print_status (
bool) – Whether to print operation status messages.
- Return type:
bool- Returns:
True if sectors were successfully erased, False otherwise.
- get_crp_level()#
Read CRP level from offset 0x2FC and decode it.
The method reads the Code Read Protection (CRP) level from the device memory at a specific offset and decodes it into a corresponding CRP level enum value. If reading fails or the value cannot be decoded, it defaults to CRP2 level.
- Return type:
- Returns:
Decoded CRP level from device memory, defaults to CRP2 on error.
- get_device()#
Get LPCDevice if defined or read it from part ID.
This method first checks if a device is already defined. If not, it attempts to decode the device from the part ID by reading it from the target. If the device cannot be determined, an exception is raised.
- Raises:
SPSDKError – When LPC Device cannot be decoded from part ID and no family is specified.
- Return type:
LPCDevice- Returns:
LPCDevice instance.
- get_info()#
Get device information summary.
Retrieves and formats comprehensive device information including Part ID, UID, Boot code version, and CRP (Code Read Protection) level with description.
- Return type:
str- Returns:
Formatted string containing device information summary.
- get_latest_status()#
Get latest status information from the protocol.
Retrieves the most recent status information including status label and description if available. Returns formatted status string or indicates no status is available.
- Return type:
str- Returns:
Formatted status string with label and description, or “No status” if unavailable.
- static get_supported_families()#
Get the list of supported families by LPCProg.
This method retrieves all MCU families that are supported by the LPCProg protocol from the database manager.
- Return type:
list[FamilyRevision]- Returns:
List of supported MCU families with their revision information.
- go(address, thumb_mode=False)#
Execute a program residing in RAM or flash memory.
This command starts execution at the specified address. It may not be possible to return to the ISP command handler once this command is successfully executed. This command is blocked when code read protection is enabled.
- Parameters:
address (
int) – Address in RAM or flash memory where program execution starts.thumb_mode (
bool) – Enable Thumb mode execution if True, ARM mode if False.
- Raises:
SPSDKError – When the command execution fails or is blocked by code protection.
- Return type:
None
- prepare_sectors_for_write(start_sector, end_sector, print_status=True)#
Prepare sectors for write operation.
This command must be executed before executing “Copy RAM to flash”, “Erase Sector(s)”, or “Erase Pages” command. Successful execution of these commands causes relevant sectors to be protected again. To prepare a single sector use the same start and end sector numbers.
- Parameters:
start_sector (
int) – Starting sector number to prepare.end_sector (
int) – Ending sector number to prepare.print_status (
bool) – Whether to print command status during execution.
- Return type:
bool- Returns:
True if sectors were successfully prepared, False otherwise.
- print_status(status)#
Print status information from the provided status code.
The method displays the status label and optionally includes a detailed description if the status code tag is non-zero.
- Parameters:
status (
Optional[StatusCode]) – Status code object containing tag and label information, or None if no status to display.- Return type:
None
- program_flash(bin_data, start_sector=0, start_page=None, progress_callback=None, print_status=True, erase=True, verify=True)#
Program binary data to flash memory with optional erase and verify.
The method programs flash memory in reverse order to prevent device bricking. When programming from sector 0, it first erases the first sector to make the image un-bootable during programming process.
Erase the first sector to make the image un-bootable and prevent bricking
Optionally write the checksum to the image vector table
Write the image in reverse order
- Parameters:
bin_data (
bytes) – Binary data to be written to flash memory.start_sector (
int) – Starting sector number for programming.start_page (
Optional[int]) – Starting page number for programming (mutually exclusive with start_sector).progress_callback (
Optional[Callable[[int,int],None]]) – Optional callback function called with (bytes_written, total_bytes) for progress tracking.print_status (
bool) – Whether to print programming status information.erase (
bool) – Whether to erase sectors/pages before writing.verify (
bool) – Whether to verify written data after programming.
- Raises:
SPSDKValueError – When sector count exceeds available sectors or when both start_sector and start_page are specified.
- Return type:
bool- Returns:
True if programming completed successfully, False otherwise.
- program_flash_page(data, page_index, verify=False, erase=True)#
Program a single flash page with data.
This command writes data to a flash page using a multi-step approach: 1) Write data to RAM buffer 2) Prepare sector for writing operations 3) Erase page (if erase flag is enabled) 4) Prepare sector again after erase 5) Copy data from RAM to flash memory 6) Verify operation using CRC checksum
- Parameters:
data (
bytes) – Binary data to be written to flash page.page_index (
int) – Zero-based index of the flash page to program.verify (
bool) – Whether to verify data written to RAM before flash operation.erase (
bool) – Whether to erase the page before writing new data.
- Raises:
SPSDKAlignmentError – When data size exceeds page size.
SPSDKError – When data verification fails or CRC checksum mismatch occurs.
- Return type:
bool- Returns:
True if operation completed successfully, False otherwise.
- program_flash_sector(data, sector, verify=False, erase=True)#
Program flash sector with data verification.
Writes data to the specified flash sector using a multi-step process that includes RAM buffering, sector preparation, optional erasing, and CRC verification to ensure data integrity.
Approach for writing the sector 1) Write data to RAM 2) Prepare sector for writing 3) Erase sector 4) Again prepare sector 5) Copy RAM to flash
- Parameters:
data (
bytes) – Data bytes to be written to the flash sector.sector (
int) – Target sector number for programming.verify (
bool) – Enable verification of data written to RAM buffer.erase (
bool) – Enable sector erase before writing new data.
- Raises:
SPSDKAlignmentError – Data size exceeds sector size limit.
SPSDKError – Data verification failed or CRC checksum mismatch.
- Return type:
bool- Returns:
Status of the programming operation.
- read_boot_code_version()#
Read boot code version from the device.
The method sends a ‘K’ command to the device and reads the version information in two parts: minor and major version numbers.
- Return type:
str- Returns:
Boot code version in format “major.minor”.
- read_crc_checksum(address, length)#
Read CRC checksum of a block of RAM or flash memory.
This command is blocked when code read protection is enabled.
- Parameters:
address (
int) – Address in RAM or flash memory.length (
int) – Length of data block in bytes.
- Return type:
Optional[int]- Returns:
CRC checksum value if successful, None if operation failed.
- read_flash_signature(start_address, end_address, wait_states=2, mode=0)#
Read flash signature generated by the flash controller.
This command uses the flash controller to generate a signature for the specified memory range with configurable wait states and mode parameters.
- Parameters:
start_address (
int) – Starting address of the flash memory range to sign.end_address (
int) – Ending address of the flash memory range to sign.wait_states (
int) – Number of wait states for flash access (default: 2).mode (
int) – Flash signature generation mode (default: 0).
- Raises:
SPSDKError – When flash signature reading fails.
- Return type:
int- Returns:
Flash signature value as integer.
- read_memory(address, length, binary=None, progress_callback=None)#
Read data from RAM or flash memory.
This command reads specified amount of data from device memory starting at given address. The data is read in chunks and can be optionally saved to a binary file. Command is blocked when code read protection is enabled.
- Parameters:
address (
int) – Starting address in RAM or flash memory to read from.length (
int) – Number of bytes to read from memory.binary (
Optional[str]) – Optional path to binary file where read data will be saved.progress_callback (
Optional[Callable[[int,int],None]]) – Optional callback function called with (current, total) progress.
- Return type:
bytes- Returns:
Read data as bytes.
- read_part_id()#
Read the part identification number from the device.
This command sends a ‘J’ command to the device and reads back the part ID.
- Return type:
str- Returns:
Part identification number as a string.
- read_uid()#
Read the unique ID from the device.
This command sends a read UID request to the device and formats the response as a space-separated string of hexadecimal values.
- Return type:
str- Returns:
Formatted unique ID as space-separated hexadecimal values (e.g., “0x12345678 0x9abcdef0 0x11223344 0x55667788”).
- return_status(status)#
Check if the given status code indicates success.
- Parameters:
status (
Optional[StatusCode]) – Status code to evaluate, can be None.- Return type:
bool- Returns:
True if status equals SUCCESS, False otherwise.
- send_command(command, print_status=False, expect_rc=True)#
Send command to the interface and process the response.
The method sends a command through the interface, processes any return code to create a status object, logs the operation, and optionally prints status.
- Parameters:
command (
str) – Command string to send to the interface.print_status (
bool) – Whether to print the status after command execution.expect_rc (
bool) – Whether to expect a return code from the command.
- Return type:
Optional[StatusCode]- Returns:
StatusCode object if return code received, None otherwise.
- set_baud_rate(baud_rate, stop_bits=1, print_status=True)#
Change the baud rate for communication.
The new baud rate is effective after the command handler sends the CMD_SUCCESS return code.
- Parameters:
baud_rate (
int) – New baud rate value to set.stop_bits (
int) – Number of stop bits to use, defaults to 1.print_status (
bool) – Whether to print status information, defaults to True.
- Raises:
SPSDKValueError – Invalid baud rate provided.
- Return type:
bool- Returns:
True if baud rate change was successful, False otherwise.
- set_echo(echo, print_status=True)#
Set echo mode for ISP command handler.
The default setting for echo command is ON. When ON the ISP command handler sends the received serial data back to the host.
- Parameters:
echo (
bool) – Enable or disable echo mode.print_status (
bool) – Whether to print command status information.
- Return type:
bool- Returns:
True if echo mode was successfully set, False otherwise.
- sync_connection(frequency, retries=10)#
Synchronize connection with the target device.
Establishes communication by performing a handshake sequence that includes sending synchronization commands and clearing the serial interface buffer.
Send ? to get baud rate
Receive “Synchronized” message
Send “Synchronized” message
Receive “OK” message
- Parameters:
frequency (
int) – Frequency of the crystal in Hz.retries (
int) – Number of synchronization attempts, defaults to 10.
- Return type:
bool- Returns:
True if synchronization is successful.
- unlock(print_status=True)#
Unlock Flash Write, Erase, and Go commands.
This command removes the protection from flash operations, allowing write, erase, and go commands to be executed on the target device.
- Parameters:
print_status (
bool) – Whether to print command status information.- Return type:
bool- Returns:
True if unlock operation was successful, False otherwise.
- write_ram(address, data)#
Write data to RAM memory.
This command is used to download data to RAM. The command is blocked when code read protection levels 2 or 3 are enabled. Writing to addresses below 0x1000 0600 is disabled for CRP1. The host should send the plain binary code after receiving the CMD_SUCCESS return code. This ISP command handler responds with “OK<CR><LF>” when the transfer has finished.
- Parameters:
address (
int) – Target address in RAM memory.data (
bytes) – Binary data to write (must be aligned to 4-byte boundary).
- Raises:
SPSDKAlignmentError – Data is not aligned to four bytes boundary.
SPSDKError – Cannot write to RAM due to communication or protection error.
- Return type:
bool- Returns:
True if write operation was successful, False otherwise.