CAPL Programming Tutorial: A Practical Automotive Engineering Guide
CAPL is an event-driven programming language used in supported automotive network simulation and testing environments. It is commonly used to simulate network nodes, transmit and receive CAN messages, stimulate ECU behavior and automate communication checks.
The most effective way to learn CAPL is to build a small simulation node in stages. This tutorial starts with variables and message definitions, then adds initialization, cyclic transmission, message reception, response handling and verification.
Compatibility note: CAPL is associated with specific automotive test and simulation runtimes. Available functions, message declarations and event syntax can vary by environment and version. Check every example against the documentation and compiler for the exact runtime used by your project.
1. What you will build
The exercise creates one simulated CAN node with this behavior:
- Initialize a status message and a rolling counter.
- Transmit the status message periodically.
- Receive a request message.
- Validate the request before responding.
- Stop periodic activity cleanly when measurement ends.
- Verify the transmitted frames in the trace.
2. CAPL program structure
A basic CAPL program is organized around declarations and event procedures.
| Element | Purpose |
|---|---|
variables | Declares timers, counters, flags and message objects |
on start | Initializes state when measurement starts |
on stop | Performs cleanup when measurement stops |
on timer | Runs scheduled or periodic logic |
on message | Reacts to reception of a configured message |
| User-defined function | Keeps repeated processing in reusable routines |
Unlike a conventional sequential program, the runtime calls the relevant event procedure when its event occurs. Keep each handler focused and move repeated logic into functions.
3. Declare messages, timers and state
For this exercise, assume the network design reserves:
- CAN ID
0x321for the simulated status message - CAN ID
0x322for a request message - A 100 ms status transmission period
These are tutorial values only. In a real project, use the approved DBC or network specification and confirm message ownership, frame format, DLC, cycle time, counter and checksum requirements.
Example declarations:
variables
{
message 0x321 StatusMsg;
msTimer statusTimer;
byte aliveCounter = 0;
int requestCount = 0;
}
The message declaration associates a CAPL message object with the example CAN identifier. If your project uses symbolic messages from a configured database, use the corresponding database message definition instead.
4. Initialize the simulation node
Initialize state when measurement starts. This avoids carrying values over from an earlier measurement run.
on start
{
aliveCounter = 0;
requestCount = 0;
StatusMsg.dlc = 8;
StatusMsg.byte(0) = 0;
StatusMsg.byte(1) = 0;
setTimer(statusTimer, 100);
}
The example initializes two payload bytes and sets an eight-byte DLC. Complete payload initialization should follow the actual message definition. Do not assume unused bytes, reserved bits or padding values are universally zero.
5. Transmit a periodic CAN message
The timer event performs one bounded transmission and schedules the next callback.
on timer statusTimer
{
aliveCounter = (aliveCounter + 1) % 16;
StatusMsg.byte(0) = aliveCounter;
output(StatusMsg);
setTimer(statusTimer, 100);
}
This illustrates a four-bit rolling counter stored in the low values of byte 0. It is not a complete production counter implementation: the bit position, counter width, initial value, update rule and checksum must match the network specification. If the counter occupies only part of a byte, preserve the other bits rather than overwriting the complete byte.
A timer callback is scheduled work, not a hard real-time guarantee. Measure actual intervals in the trace and compare them with the project's allowed timing tolerance.
6. Receive and validate a CAN request
A message event can react to a received request. The example below accepts a request only when its first payload byte has the expected value.
on message 0x322
{
if (this.dlc < 1)
{
write("Request rejected: DLC is too short");
return;
}
if (this.byte(0) == 0x01)
{
requestCount++;
sendStatusResponse();
}
else
{
write("Request rejected: unsupported command");
}
}
The exact message-event selector and access syntax should be checked in the target CAPL runtime. In a database-based project, a symbolic message name may be preferable to a hard-coded identifier.
Validation should be derived from the interface definition. Depending on the protocol, checks may include DLC, message state, rolling counter, checksum, signal range, source, timing and operating mode.
7. Create a reusable response function
Keep the response construction in a function so it can be called from the relevant event handler or other test logic.
void sendStatusResponse()
{
StatusMsg.byte(1) = requestCount;
output(StatusMsg);
}
This is a deliberately small example. A real implementation should define whether a response is a separate message or the same status frame, and should avoid transmitting a message whose ownership belongs to another ECU or simulation node.
8. Stop timers and clean up
Always define what happens when measurement stops. Active timers should not be left running unintentionally.
on stop
{
cancelTimer(statusTimer);
}
If the simulation controls outputs or shared state, also define the required shutdown values and ensure that the test setup returns to a known condition.
9. Use a DBC and understand signal encoding
A DBC provides message and signal definitions that can be used for symbolic access in supported environments. It describes items such as:
- CAN identifier and frame format
- Message length
- Signal start bit and length
- Byte order and signedness
- Scaling factor and offset
- Sender and receiver information
For a raw signal value (R), physical value conversion commonly follows:
[ P = R \times F + O ]
where (F) is the factor and (O) is the offset defined by the signal description. The exact bit extraction and encoding depend on start bit, length, byte order and signedness.
Symbolic access reduces manual byte calculations, but it does not remove the need to understand the database definition. Verify the decoded value against raw trace bytes, especially when debugging scaling or endianness issues.
10. Verify the simulation in the trace
| Check | Expected evidence |
|---|---|
| Startup | State initialized once at measurement start |
| Cyclic transmission | Status frame appears at the configured nominal interval |
| Counter | Counter changes according to the defined width and rollover |
| Request reception | Correct request ID and payload are observed |
| Invalid request | No unintended response is transmitted |
| Response | Response content matches the approved interface definition |
| Measurement stop | Timer is cancelled and no further periodic transmissions occur |
Capture raw frames and timestamps before applying filters. Compare observed DLC, payload bytes, cycle time and counter behavior against the DBC and project requirements.
11. Common beginner mistakes
- Using arbitrary CAN identifiers: message IDs must be allocated by the network design.
- Ignoring message ownership: two nodes transmitting the same message can create conflicts.
- Starting a timer without cleanup: cancel active timers during measurement stop or test reset.
- Overwriting a complete byte: preserve unrelated signal bits when a counter occupies only part of a byte.
- Assuming timer precision: verify actual timing from measured timestamps.
- Trusting symbolic decoding blindly: check database version, start bit, byte order, signedness, factor and offset.
- Treating a received frame as a valid request: validate the required payload and state before responding.
- Leaving state uninitialized: explicitly reset counters, flags and test state for repeatable runs.
12. Suggested learning exercises
- Change the periodic transmission interval and measure the observed cycle time.
- Add a second request command with a different response.
- Reject requests with an incorrect DLC.
- Add a response timeout and record a clear test verdict.
- Implement the rolling counter according to a sample DBC definition.
- Add a checksum only after documenting the exact algorithm and covered bytes.
- Run the same test across repeated measurement start/stop cycles and check for stale state or duplicate timers.
13. Engineering checklist
- Message IDs, DLC and cycle times come from an approved network definition.
- Each simulated message has one clearly defined owner.
- All state variables are initialized at measurement start.
- Timer start, re-arm and cancellation paths are defined.
- Request payload and operating state are validated before responding.
- Counter and checksum behavior match the network specification.
- Trace timestamps and raw payload bytes are captured.
- Repeated measurement runs produce consistent results.
- CAPL syntax is compiled and tested in the target runtime/version.
14. Check your understanding
- Why should a CAPL simulation node initialize its state in
on start? - What is the difference between scheduling a timer callback and guaranteeing a hard real-time transmission interval?
- Why must a rolling counter update preserve unrelated bits in the same payload byte?
- Which trace fields should be compared with the DBC when a signal appears incorrect?
Related articles
- CAPL Functions and Events
- CAPL CAN Message Simulation
- CAPL Test Automation
- CANoe Testing Concepts: A Practical Automotive Engineering Guide
