Implementation and Validation of UDS Services on STM32 with CAN Communication
Unified Diagnostic Services (UDS) is a diagnostic communication protocol widely utilized within automotive electronics. Defined by the ISO 14229-1 standard, UDS plays a key role in managing Electronic Control Units (ECUs) within vehicles. Diagnostic tools can communicate with all installed ECUs that have UDS services enabled, making it invaluable for fault detection, troubleshooting, and reprogramming ECUs as needed.
With UDS, the diagnostic and maintenance processes are significantly streamlined, enhancing vehicle reliability while reducing maintenance time and costs.
UDS Message Format
In UDS, both requests and responses follow a specific format to facilitate diagnostic communication between a diagnostic tool and an ECU. The format varies slightly depending on the type of request or response.
- Format: SID | SubFunction | Request Data
- Format: SID | Request Data
2. Response Format
- Format: SID + 0x40 | SubFunction | Response Data
- Format: SID + 0x40 | Response Data
3. Negative Response Format
- Format: 0x7F | SID | NRC
- Format: 0x7F | SID | 0x78
Implementation of UDS Services
Diagnostic Communication Management_functional unit
1. Diagnostic Session Control (0x10)
Managing diagnostic sessions through the DiagnosticSessionControl (0x10) service is essential for enabling various levels of diagnostics and configuration within a vehicle’s Electronic Control Units (ECUs). This service allows the client to request the ECU to switch between multiple diagnostic sessions, each activating a specific set of functionalities.
The DiagnosticSessionControl service activates specific diagnostic sessions within the ECU, such as the default session, programming session, and extended diagnostic session. Each session configures the ECU for unique functionalities. By default, the ECU always starts in the default session, but other sessions can be activated as needed. These advanced sessions enable operations like reprogramming ECU parameters or adjusting critical functions.
Implementation Details
Session Management:
CAN Communication for Responses:
Test Scenarios
Extensive tests were conducted to validate the robustness of the implementation:
2. ECU Reset (0x11)
The ECU Reset (0x11) service allows the client to request a reset of the Electronic Control Unit (ECU), resetting its functions based on the specified reset type. This service is essential for reinitializing certain ECU functions or parameters, which aids in diagnostics and maintenance operations within the UDS protocol.
The ECUReset service allows the client to specify the desired reset type using the resetType parameter. Based on this command, the ECU can perform various types of resets:
Following the reset, the ECU returns to the default session, ready to receive new commands. If needed, the system sends a positive response before executing the reset, and during the reset process, no communication is allowed until completion.
Implementation Details
Reset Handling:
CAN Responses:
Test Scenarios
Several tests were conducted to verify the functionality of the ECUReset service and its compliance with UDS specifications:
3. Security Access (0x27)
The Security Access (0x27) service is integral for enabling secured functionalities within the Electronic Control Unit (ECU) by enforcing access control. This service restricts access to certain sensitive data and diagnostic services, which are critical for vehicle safety, emissions, and security standards.
The Security Access service provides a seed and key mechanism for the client to unlock protected services within the ECU. This process ensures that only authorized users can access secure functionalities. Here’s how it typically works:
Security Access prevents unauthorized access that could compromise the vehicle's performance or regulatory compliance. The ECU supports various security levels, with each level defined by a unique requestSeed and sendKey pairing. Additionally, the ECU can enforce a delay after multiple incorrect key attempts to further safeguard the system.
Implementation Details
Seed and Key Handling:
CAN Communication for Responses:
Test Scenarios
To validate the functionality of the Security Access service, the following test scenarios were conducted:
4. Communication Control (0x28)
The Communication Control (0x28) service is designed to manage the transmission and reception of messages in a vehicle’s Electronic Control Unit (ECU) communication network. By toggling these functions, the ECU can limit or allow certain types of message traffic for various operational needs, including diagnostics or communication prioritization.
The Communication Control service allows the client to:
The controlType parameter in the request message defines the type of control action, such as enabling only Rx, only Tx, or both. The communicationType parameter specifies the category of communication to control, and an optional nodeIdentificationNumber can specify a sub-network segment in enhanced addressing scenarios.
Implementation Details
Control Actions:
CAN Communication:
Test Scenarios
To ensure robustness in handling the Communication Control service, various test scenarios were conducted:
Enable Rx and Tx: Confirms that the ECU allows both message reception and transmission.
Enable Rx and Disable Tx: Ensures that only incoming messages are processed.
Disable Rx and Enable Tx: Limits ECU communications to outgoing messages only.
Disable Rx and Tx: Verifies that both sending and receiving are successfully disabled.
Enable Rx and Tx with Enhanced Info: Tests if the ECU properly uses enhanced addressing to apply communication settings on specific segments.
Enable Rx with Enhanced Info: Confirms enhanced addressing controls for Rx only.
5. Tester Present (0x3E)
The Tester Present (0x3E) service is used to maintain an active diagnostic session between a client and an Electronic Control Unit (ECU). By periodically sending a Tester Present message, the client prevents the ECU from reverting to the default session when there is no active diagnostic command.
The Tester Present service enables the client to:
The sub-function parameter in the request message determines whether the ECU should send a response or remain silent.
Implementation Details
Sub-functions:
CAN Communication:
Test Scenarios
To validate the functionality of the Tester Present service, the following tests were conducted:
Basic Session Maintenance:
Error Handling:
6. Access Timing Parameter (0x83)
The Access Timing Parameter (0x83) service allows a client to read and modify the default timing parameters of an ECU's communication link while the link remains active. This service can be used for adjusting response timings, which can be necessary for specific diagnostic sessions or communication configurations.
The Access Timing Parameter service provides the following functionalities:
Implementation Details
Control Actions:
CAN Communication:
Test Scenarios
To ensure robustness in handling the Access Timing Parameter service, the following test scenarios were conducted:
Basic Timing Parameter Control:
7. Secured Data Transmission (0x84)
The Secured Data Transmission (0x84) service is designed to securely transmit data between a client and an ECU using encryption, ensuring data security and preventing unauthorized access. This service allows diagnostic communication in a secured mode and supports secure point-to-point communication only, requiring physical addressing.
Implementation Details
Encryption and Decryption:
Response Types:
Test Scenarios
To validate the Secured Data Transmission service, the following tests were conducted:
8. Control DTC Setting (0x85)
The Control DTC Setting (0x85) service allows the client to enable or disable the updating of Diagnostic Trouble Code (DTC) status bits in an ECU. DTC status bits record diagnostic data specific to each detected fault, providing insight for maintenance and troubleshooting. The service is used primarily to manage whether the ECU updates these bits or keeps them static under certain diagnostic conditions.
Implementation Details
DTC Control Actions:
CAN Communication:
Test Scenarios
To validate the functionality of the Control DTC Setting service, several tests were conducted:
Enable DTC Updating: Sends a request to enable DTC updating, expecting a positive response (0xC5) with the echo of sub-function (0x01).
Disable DTC Updating: Sends a request to disable DTC updating, expecting a positive response (0xC5) with the echo of sub-function (0x02).
Unsupported Sub-function: Sends a request with an unsupported sub-function (e.g., 0x03), expecting a negative response with NRC 0x12.
Conditions Not Correct: Tests the scenario where the ECU is not in a session that supports DTC control, expecting NRC 0x22 to indicate incorrect conditions.
9. Response on Event (0x86)
The Response on Event (0x86) service allows a client to configure an ECU to monitor and automatically respond to specific events. This service enables dynamic diagnostic actions triggered by real-time events within the ECU, enhancing responsiveness and adaptability to varying diagnostic conditions.
Start or Stop Event Monitoring: Configure the ECU to start or stop responding to specified events.
Event Type and Window Duration: Define the event type, duration, and any parameters to control the timing and conditions of event-triggered responses.
Event Types Supported:
Implementation Details
Event Control Actions:
CAN Communication:
Positive Response (0xC6): Confirms successful event setup or termination.
Negative Response Codes (NRC): Sub-function Not Supported (0x12): Returned if an unsupported event is requested. Incorrect Message Length (0x13): Indicates an invalid message length. Request Out of Range (0x31): Signifies an error in parameters like event type or unsupported DIDs.
Test Scenarios
To verify the Response on Event service functionality, various tests were conducted:
Start Event on DTC Status Change: Starts event monitoring for DTC status changes, expecting a positive response (0xC6) echoing the configured event.
Start Event on Timer Interrupt: Begins event monitoring on a timer interval, with a positive response confirming the event parameters.
Stop Response on Event: Tests disabling event-triggered responses, expecting a confirmation response (0xC6).
Clear Response on Event: Completely clears all configured events, validating that no lingering events remain active.
10. Link Control (0x87) Service
The Link Control (0x87) service is primarily used to control communication parameters (e.g., baud rate) to optimize bus bandwidth for diagnostic purposes, particularly in non-default diagnostic sessions. This feature is crucial during activities such as programming, where high data throughput is essential.
Mode Transition Steps:
Step #1: Verification of the transition capability to ensure the server(s) can handle the requested transition (e.g., higher baud rate). All servers should respond affirmatively before proceeding.
Step #2: Execution of the mode transition. For functional communication, suppressing positive responses is recommended to avoid conflicting states across multiple servers.
Implementation Details
Mode Verification and Transition:
Test Scenarios
To ensure proper implementation of the Link Control service, the following test scenarios were executed:
Verify Mode Transition with Fixed Parameter: Verifies if the server can transition to a fixed communication mode, expecting a positive response echoing the request parameters.
Verify Mode Transition with Specific Parameter: Checks if the server can handle a custom mode parameter transition, receiving a positive response for successful configuration.
Execute Mode Transition: After successful verification, initiates the actual mode transition. Depending on configuration, either a confirmation response or silence (suppressing responses) is expected.
Data Transmission functional unit
1. Read Data by Identifier (0x22)
The Read Data by Identifier (0x22) service allows a client to retrieve specific data records from an ECU, identified by unique Data Identifiers (DIDs). This service enables the client to access information like system status, internal data, and analog/digital signal values as needed for diagnostics.
Implementation Details
Test Scenarios
2. Read Memory by Address (0x23)
The Read Memory by Address (0x23) service allows the client to request memory data from a specified starting address and for a defined size, enabling the reading of specific memory sections within the ECU for diagnostics.
Implementation details
Test Scenarios
领英推荐
3. Read Data by Periodic Identifier (0x2A)
The Read Data by Periodic Identifier (0x2A) service allows the client to request periodic transmission of specific data values from the ECU based on specified intervals. This is particularly useful for monitoring dynamic data continuously without multiple requests.
Implementation details
Test Scenarios
4. Dynamically Define Data Identifier (0x2C)
The Dynamically Define Data Identifier (0x2C) service enables the client to define a custom data identifier (DID) in the ECU that can group data from other identifiers or memory addresses, enabling later retrieval as a single data block. This flexibility facilitates targeted diagnostics and reduces bandwidth by grouping data into composite records.
Implementation details
Test Scenarios
5. Write Data By Identifier (0x2E)
The WriteDataByIdentifier (0x2E) service enables a client to write specific data to an ECU location associated with a data identifier (DID). Common use cases include updating configuration data, resetting learned values, or programming option-specific content.
Implementation details
Test Scenarios
Stored Data Transmission functional unit
1. Clear Diagnostic Information (0x14)
The ClearDiagnosticInformation (0x14) service enables the client to clear stored diagnostic information within the Electronic Control Unit (ECU). This service allows the client to reset diagnostic data for a specific group of Diagnostic Trouble Codes (DTCs), such as powertrain, chassis, or body, as well as individual DTCs. Clearing diagnostic information can be useful for resetting ECU status after repairs or maintenance.
The service is structured to handle cases where multiple copies of DTC status information exist in the ECU (e.g., in RAM and EEPROM). The ECU is required to clear the primary data used for DTC status reporting while following the designated backup strategy for other copies.
Implementation Details
DTC Group Management: Each DTC group is defined by a groupOfDTC parameter, a 3-byte identifier. Unsupported groups trigger a Request Out of Range (0x31) response.
ECU Response Mechanisms:
Test Scenarios
Positive Response for Supported Group: Confirms successful DTC clearing for valid groups, expecting a response (0x54).
2. Read DTC Information Service (0x19)
The ReadDTCInformation service (ID 0x19) is a crucial component within the Unified Diagnostic Services (UDS) suite, designed to provide comprehensive information on Diagnostic Trouble Codes (DTC) stored within the Electronic Control Unit (ECU). This service enables a client to effectively diagnose the condition of various vehicle systems by accessing stored DTCs and extracting specific details about the status, severity, and history of each error code.
Through ReadDTCInformation, the client can:
Sub-Functions of the ReadDTCInformation Service
Each sub-function of the Read DTC Information service addresses a specific request:
REPORT_NUMBER_OF_DTC_BY_STATUS_MASK (0x01): Retrieves the count of DTCs matching a given status mask, providing an overview of active, confirmed, or pending faults.
REPORT_DTC_BY_STATUS_MASK (0x02): Returns a list of DTCs matching a specific status, providing detailed information for each fault, including its code and status.
REPORT_DTC_SNAPSHOT_IDENTIFICATION (0x03): Provides a summary of DTCs with snapshot records, including a capture ID for each DTC to review conditions at the time of detection.
REPORT_DTC_SNAPSHOT_RECORD_BY_DTC_NUMBER (0x04): Returns the snapshot data associated with a specific DTC, allowing examination of values recorded by the ECU at fault detection.
REPORT_DTC_STORED_DATA_BY_RECORD_NUMBER (0x05): Supplies additional recorded data for a specific DTC, such as test and identification data.
REPORT_DTC_EXT_DATA_RECORD_BY_DTC_NUMBER (0x06): Returns extended data associated with a specific DTC, providing advanced diagnostic details.
REPORT_NUMBER_OF_DTC_BY_SEVERITY_MASK (0x07): Counts the number of DTCs matching a specific severity mask.
REPORT_DTC_BY_SEVERITY_MASK_RECORD (0x08): Returns a list of DTCs based on their status and severity, including details for each fault.
REPORT_SEVERITY_INFORMATION_OF_DTC (0x09): Provides severity information for a specific DTC.
REPORT_SUPPORTED_DTC (0x0A): Supplies a list of all DTCs supported by the ECU.
REPORT_FIRST_TEST_FAILED_DTC (0x0B): Returns the first DTC that failed a test.
REPORT_FIRST_CONFIRMED_DTC (0x0C): Provides the first confirmed DTC.
REPORT_MOST_RECENT_TEST_FAILED_DTC (0x0D): Returns the most recent DTC that failed a test.
REPORT_MOST_RECENT_CONFIRMED_DTC (0x0E): Returns the most recently confirmed DTC.
REPORT_MIRROR_MEMORY_DTC_BY_STATUS_MASK (0x0F): Returns the DTCs in the mirror memory matching a specific status mask.
REPORT_MIRROR_MEMORY_DTC_EXT_DATA_RECORD (0x10): Provides extended data for DTCs in mirror memory.
REPORT_NUMBER_OF_MIRROR_MEMORY_DTC_BY_STATUS_MASK (0x11): Counts DTCs in mirror memory based on a status mask.
REPORT_NUMBER_OF_EMISSIONS_OBD_DTC_BY_STATUS_MASK (0x12): Counts emissions-related OBD DTCs that match a status mask.
REPORT_EMISSIONS_OBD_DTC_BY_STATUS_MASK (0x13): Returns OBD-related DTCs based on a status mask.
REPORT_DTC_FAULT_DETECTION_COUNTER (0x14): Provides the fault detection counter for DTCs with a defined occurrence frequency.
REPORT_DTC_WITH_PERMANENT_STATUS (0x15): Returns a list of DTCs with a permanent status.
REPORT_DTC_EXT_DATA_RECORD_BY_RECORD_NUMBER (0x16): Supplies extended data associated with a specific record number.
REPORT_USER_DEF_MEMORY_DTC_BY_STATUS_MASK (0x17): Lists user-defined memory DTCs based on a status mask.
REPORT_USER_DEF_MEMORY_DTC_SNAPSHOT_RECORD (0x18): Provides snapshot records for DTCs in user-defined memory.
REPORT_USER_DEF_MEMORY_DTC_EXT_DATA_RECORD (0x19): Supplies extended data for DTCs in user-defined memory.
REPORT_WWH_OBD_DTC_BY_MASK_RECORD (0x1A): Lists WWH-OBD DTCs based on a mask.
REPORT_WWH_OBD_DTC_WITH_PERMANENT_STATUS (0x1B): Returns WWH-OBD DTCs with permanent status.
Implementation Details
The implementation of the ReadDTCInformation service in the code relies on several key principles:
Test Scenarios
Each sub-function of the ReadDTCInformation service is tested to validate its correct operation and detect potential errors.
Positive test scenarios validate:
Negative test scenarios evaluate:
These tests ensure the robustness and reliability of the Read DTC Information service in diverse diagnostic situations.
InputOutput Control functional unit
1. InputOutputControlByIdentifier (0x2F)
The InputOutputControlByIdentifier (0x2F) service provides the client with the capability to temporarily control or override specific input and output signals within the ECU. This service is typically employed during diagnostics or testing to adjust values for input signals or to force outputs to a desired state. It is ideal for simpler control adjustments, whereas the RoutineControl service may be preferred for more complex operations.
The service works by targeting a specific dataIdentifier, representing input signals, internal functions, or outputs within the ECU. The client sends a control command that can specify multiple parameters if a controlEnableMask is used, allowing for targeted control over individual bits or multiple values within a single data identifier.
Implementation Details
Control Options:
Communication Responses:
Test Scenarios
Various test scenarios validate the functionality and error handling for the InputOutputControlByIdentifier service:
Short Term Adjustment: Verifies that the ECU correctly adjusts an actuator or signal for temporary control.
Return Control to ECU: Confirms that the ECU can reclaim control after testing is complete.
Freeze Current State: Locks parameters at their current state for testing stability.
Unsupported Data Identifiers: Verifies that out-of-range identifiers produce NRC_REQUEST_OUT_OF_RANGE.
Invalid Conditions: Confirms the ECU responds with NRC_CONDITIONS_NOT_CORRECT for unsupported options or states.
The InputOutputControlByIdentifier service is essential for dynamic diagnostic testing, providing effective control over ECU parameters and contributing to comprehensive ECU functionality validation in a controlled testing environment.
Routine functional unit
1. Routine Control (0x31)
The RoutineControl service (ID 0x31) provides the client with the ability to initiate, halt, or retrieve the results of specific routines defined within the ECU. It is commonly used for tasks that require a sequence of operations or specific, controlled behaviors such as memory erasure, resetting adaptive data, executing self-tests, or temporarily taking over certain ECU functions. This service is suited for more complex operations, as compared to the simpler InputOutputControlByIdentifier service.
The RoutineControl service allows the client to:
These routines, identified by a unique routineIdentifier, can function independently or as part of the ECU’s normal operation. In some cases, the ECU may require an authorized session or specific security access before allowing a routine to start, making this service essential for both diagnostics and maintenance procedures.
Implementation Details
Routine Management:
Response Mechanisms:
Test Scenarios
To ensure correct functionality and error handling, multiple test scenarios were executed:
Positive Response Validation:
Upload Download functional unit
1. Request Download (0x34)
The RequestDownload service (ID 0x34) is designed for initiating data transfers from the client to the server within the ECU. This service prepares the ECU to receive data, setting up the necessary configurations and parameters to ensure the download process operates smoothly. Once a valid request is received, the ECU allocates resources and validates parameters before returning a positive response.
The RequestDownload service allows the client to specify:
The RequestDownload service provides a structured approach for secure data transfer, often used for firmware updates, configuration adjustments, or diagnostic information transfer.
Implementation Details
Data and Memory Address Validation:
Security and Access Control:
Test Scenarios
To ensure functionality and robustness, various test scenarios are employed:
2. Request Upload (0x35)
The RequestUpload service (ID 0x35) is used to initiate data transfers from the ECU (server) to the client, facilitating tasks like retrieving diagnostic data, configuration parameters, or firmware files stored within the ECU. Upon receiving a valid RequestUpload message, the ECU takes necessary preparatory actions before returning a positive response and enabling data transfer.
The RequestUpload service specifies:
This service allows secure data retrieval and structured access to diagnostic or operational data, typically used for system configurations or maintenance tasks.
Implementation Details
Test Scenarios
To confirm the functionality and security of the RequestUpload service, several test scenarios are employed:
3. Transfer Data (0x36)
Transfer Data (0x36) The TransferData service (ID 0x36) facilitates data exchange between the client and the server in an ECU, supporting both download (client to server) and upload (server to client) operations. This service is part of a data transfer sequence that follows a RequestDownload or RequestUpload initiation, making it an essential element in firmware updates, memory operations, or diagnostic data retrieval.
The TransferData service uses:
Implementation Details
The server initializes the blockSequenceCounter at the start of each RequestDownload or RequestUpload.
When errors or timeouts occur, the blockSequenceCounter assists the server in distinguishing new transmissions from repeated requests, enabling efficient retransmission handling.
If a TransferData request arrives out of sequence, a "Wrong Block Sequence Counter" (NRC) is issued.
If the message is incorrectly formatted or the transfer conditions are unmet, the ECU returns an appropriate error response, such as Incorrect Message Length or Request Sequence Error.
Test Scenarios
Several test scenarios ensure the reliability of the TransferData service:
4. Request Transfer Exit (0x37)
Request Transfer Exit (0x37) The RequestTransferExit service (ID 0x37) is used by the client to terminate an ongoing data transfer between the client and the server within the ECU. It finalizes either an upload or download session, allowing the server to complete any necessary post-transfer actions, such as validation or storage of received data.
Implementation Details
The server validates that the request is received while a data transfer is active. If not, a "Request Sequence Error" is returned, indicating that no active transfer session exists.
The transferRequestParameterRecord is validated to confirm its integrity and suitability for the server’s specific post-transfer requirements.
If the message length is incorrect or improperly formatted, the server responds with an "Incorrect Message Length" error.
If the provided parameters are invalid or outside the acceptable range, the server issues a "Request Out of Range" response.
Any issues detected during finalization, such as integrity check failures, will result in a "General Programming Failure" error code.
Test Scenarios
Several test cases validate the robustness of the RequestTransferExit service:
5. Request File Transfer (0x38)
The RequestFileTransfer service (ID 0x38) allows a client to initiate file transfers between the client and server in either direction, enabling file upload, download, and directory management. It serves as an alternative to RequestDownload and RequestUpload for ECUs that support file systems, and it includes additional operations, such as file deletion and directory retrieval.
Implementation Details
File Operation Modes:
Positive Response:
Error Handling:
Test Scenarios
To ensure robust performance, the following test cases are applied:
?
Conclusion
The Unified Diagnostic Services (UDS) protocol is a cornerstone in managing the embedded systems of modern vehicles. Governed by the ISO 14229-1 standard, UDS unifies and simplifies diagnostics, maintenance, and reprogramming of Electronic Control Units (ECUs). With a rigorous structure of services, UDS ensures reliable and secure communication between diagnostic tools and ECUs, enhancing fault detection, precise troubleshooting, and maintenance cost optimization. As vehicles become increasingly connected and automated, the UDS protocol continues to evolve to meet the growing demands for remote diagnostics and enhanced security, making it an indispensable asset for the automotive industry.
?
Senior Engineer - PES I Diagnostics Developer and Tester for EV, ICE | Testing and Validation | AUTOSAR Configurator COM, DEM | .cdd | CANoe | Automotive Ethernet | DoIP | CAN | OBD II | UDS | J1939
4 个月Great job!!
Very Helpful! Thanks for sharing
Technical (Project/Department) Manager | Senior Team Leader | Senior R&D Engineer | +20 Years Experience
4 个月An good article written about UDS protocol. Thanks for sharing your knowledge ??
Automotive Diagnostic Engineer | Diagnostic Subdomain Lead @ Stellantis
4 个月Very informative, thanks for sharing! I noticed that Read Scaling Data By Identifier (0x24) and Write Memory By Address (0x3D) weren’t mentioned. Also, which version of ISO 14229 did you reference? as the Access Timing Parameters (0x83) service doesn’t appear in the latest published version (2020)
Software Integration Engineer at Stellantis | IoT and Embedded Systems Development enginner
4 个月Good job ????