Ladderlib is a C library designed for implementing ladder logic programming, a method widely used in Programmable Logic Controllers (PLCs) for industrial automation. It provides a robust framework to define, execute, and manage ladder logic programs, supporting hardware interactions and custom function extensions. This library is particularly suited for embedded systems.
Project Information:
- Repository: Ladderlib GitHub
- Version: 2.0.0
- License: MIT License
- Copyright: 2025 Emiliano Gonzalez ([email protected])
Ladderlib enables developers to create ladder logic programs, which are graphical representations of control logic resembling electrical relay circuits. These programs are executed cyclically by PLCs to automate industrial processes, such as controlling machinery in manufacturing or chemical processing. The library supports defining logic through cells and networks, managing execution states, handling hardware inputs/outputs, and integrating custom functions for enhanced flexibility.
Key features include:
- Instruction Set: 39 instructions for defining logic operations.
- State Management: 6 states to control program execution.
- Error Handling: 8 error codes for robust operation.
- Hardware Integration: Function pointers for reading inputs and writing outputs.
- Custom Extensions: Support for adding user-defined functions.
The library is likely optimized for embedded systems.
Ladder logic programs consist of "rungs" connecting two vertical "rails," mimicking electrical relay circuits. Each rung contains conditions (e.g., contacts) and actions (e.g., coils)
The following table summarizes the instructions, their codes, categories, and symbols.
Basic instructions manage Input/Output functions
- Instruction Code:
LADDER_INS_NO
(3) - Description: The Normally Open contact allows logic flow when its associated input is true, acting like a switch that closes when activated. It is used to check if an input condition (e.g., a sensor) is met.
- Example Use: Checking if a pushbutton is pressed to activate a motor.
- Instruction Code:
LADDER_INS_NC
(4) - Description: The Normally Closed contact allows logic flow when its associated input is false, acting like a switch that opens when activated. It is used to proceed when a condition is not met.
- Example Use: Ensuring a safety switch is not triggered before starting a process.
- Instruction Code:
LADDER_INS_COIL
(7) - Description: The Coil instruction sets an output to true when the rung's logic is true, controlling devices like motors or lights. It represents the action taken when conditions are satisfied.
- Example Use: Turning on a conveyor belt when all conditions are met.
- Instruction Code:
LADDER_INS_COILL
(8) - Description: The Coil Latch sets an output to true and maintains it (latches) even if the input conditions change, until unlatched. It is used for memory functions in control systems.
- Example Use: Keeping a pump running after a start button is released.
- Instruction Code:
LADDER_INS_COILU
(9) - Description: The Coil Unlatch resets a latched output to false, releasing the latched state. It is paired with
COILL
for set/reset operations. - Example Use: Stopping a latched pump when a stop button is pressed.
Timer instructions manage time-based operations, delaying or pulsing outputs.
- Instruction Code:
LADDER_INS_TON
(10) - Description: The Timer On Delay starts timing when its input is true. After a preset time, the output becomes true. It is used to delay actions, such as waiting before starting a motor.
- Example Use: Delaying a fan activation for 10 seconds after a heater starts.
- Instruction Code:
LADDER_INS_TOFF
(11) - Description: The Timer Off Delay starts timing when its input goes false. After a preset time, the output becomes false. It is used to extend the duration of an output.
- Example Use: Keeping a light on for 5 seconds after a switch is turned off.
- Instruction Code:
LADDER_INS_TP
(12) - Description: The Timer Pulse generates a pulse of a specified duration when triggered by a true input. It is used for creating timed signals, such as a brief alarm.
- Example Use: Activating a buzzer for 2 seconds when a fault is detected.
Counter instructions track the number of events or occurrences.
- Instruction Code:
LADDER_INS_CTU
(13) - Description: The Count Up counter increments its count each time the input transitions from false to true, up to a preset value. It is used to count items or events.
- Example Use: Counting the number of boxes on a conveyor belt.
- Instruction Code:
LADDER_INS_CTD
(14) - Description: The Count Down counter decrements its count each time the input transitions from false to true, down to zero. It is used for countdown tasks.
- Example Use: Tracking remaining items in a batch process.
These instructions perform mathematical operations on data.
- Instruction Code:
LADDER_INS_ADD
(17) - Description: Adds two values and stores the result in a specified location. It is used for calculations like summing sensor readings.
- Example Use: Adding the outputs of two flow sensors.
- Instruction Code:
LADDER_INS_SUB
(16) - Description: Subtracts one value from another and stores the result. It is used for differential calculations.
- Example Use: Calculating the difference in pressure between two points.
- Instruction Code:
LADDER_INS_MUL
(18) - Description: Multiplies two values and stores the result. It is used for scaling or area calculations.
- Example Use: Calculating power by multiplying voltage and current.
- Instruction Code:
LADDER_INS_DIV
(19) - Description: Divides one value by another and stores the result. It is used for ratio calculations.
- Example Use: Determining speed by dividing distance by time.
- Instruction Code:
LADDER_INS_MOD
(20) - Description: Computes the remainder of dividing one value by another. It is used for cyclic operations or remainder checks.
- Example Use: Checking if a counter value is even or odd.
These instructions manipulate bits within data values.
- Instruction Code:
LADDER_INS_SHL
(21) - Description: Shifts the bits of a value to the left by a specified number of positions, filling with zeros. It is used for bit manipulation or scaling.
- Example Use: Doubling a binary value by shifting left.
- Instruction Code:
LADDER_INS_SHR
(22) - Description: Shifts the bits of a value to the right by a specified number of positions, filling with zeros or sign bits. It is used for division or bit extraction.
- Example Use: Halving a binary value by shifting right.
- Instruction Code:
LADDER_INS_ROL
(23) - Description: Rotates the bits of a value to the left, with the most significant bit wrapping around to the least significant position. It is used for circular shifts.
- Example Use: Rotating status flags in a control word.
- Instruction Code:
LADDER_INS_ROR
(24) - Description: Rotates the bits of a value to the right, with the least significant bit wrapping around to the most significant position. It is used for circular shifts.
- Example Use: Cycling through a set of control bits.
- Instruction Code:
LADDER_INS_AND
(25) - Description: Performs a bitwise AND operation on two values, setting output bits to 1 only where both inputs are 1. It is used for masking or condition checks.
- Example Use: Masking specific bits in a status register.
- Instruction Code:
LADDER_INS_OR
(26) - Description: Performs a bitwise OR operation on two values, setting output bits to 1 where either input is 1. It is used for combining conditions.
- Example Use: Combining multiple fault flags.
- Instruction Code:
LADDER_INS_XOR
(27) - Description: Performs a bitwise XOR operation on two values, setting output bits to 1 where inputs differ. It is used for toggling or comparison.
- Example Use: Detecting changes in bit patterns.
- Instruction Code:
LADDER_INS_NOT
(28) - Description: Performs a bitwise NOT operation, inverting all bits of a value. It is used for logical negation.
- Example Use: Inverting a control signal.
These instructions compare values and produce boolean outputs.
- Instruction Code:
LADDER_INS_EQ
(29) - Description: Checks if two values are equal, outputting true if they are. It is used for equality checks in control logic.
- Example Use: Verifying if a temperature reading matches a setpoint.
- Instruction Code:
LADDER_INS_GT
(30) - Description: Checks if one value is greater than another, outputting true if so. It is used for threshold checks.
- Example Use: Checking if pressure exceeds a safe limit.
- Instruction Code:
LADDER_INS_GE
(31) - Description: Checks if one value is greater than or equal to another, outputting true if so. It is used for inclusive threshold checks.
- Example Use: Ensuring a tank level is at or above a minimum.
- Instruction Code:
LADDER_INS_LT
(32) - Description: Checks if one value is less than another, outputting true if so. It is used for lower-bound checks.
- Example Use: Detecting if a speed is below a target.
- Instruction Code:
LADDER_INS_LE
(33) - Description: Checks if one value is less than or equal to another, outputting true if so. It is used for inclusive lower-bound checks.
- Example Use: Verifying a flow rate is at or below a maximum.
- Instruction Code:
LADDER_INS_NE
(34) - Description: Checks if two values are not equal, outputting true if they differ. It is used for change detection.
- Example Use: Detecting a change in a sensor value.
These instructions provide additional functionality, some of which may be specific to ladderlib.
- Instruction Code:
LADDER_INS_NOP
(0) - Description: Performs no operation, acting as a placeholder or for timing purposes. It does not affect the program state.
- Example Use: Reserving space for future instructions.
- Instruction Code:
LADDER_INS_CONN
(1) - Description: Likely used to connect different parts of the ladder diagram, such as branching or joining rungs. It facilitates complex logic structures.
- Example Use: Linking parallel branches in a rung.
- Instruction Code:
LADDER_INS_NEG
(2) - Description: Inverts the logic state of an input, turning true to false or vice versa. It is used to reverse conditions.
- Example Use: Inverting a stop signal to enable a process.
- Instruction Code:
LADDER_INS_RE
(5) - Description: Detects a rising edge, triggering when an input transitions from false to true. It is used for event-driven actions.
- Example Use: Starting a counter when a button is pressed.
- Instruction Code:
LADDER_INS_FE
(6) - Description: Detects a falling edge, triggering when an input transitions from true to false. It is used for event-driven actions.
- Example Use: Resetting a system when a sensor deactivates.
- Instruction Code:
LADDER_INS_MOVE
(15) - Description: Copies data from one memory location to another without modification. It is used for data transfer.
- Example Use: Transferring a sensor value to a display register.
- Instruction Code:
LADDER_INS_TMOVE
(36) - Description: Likely used for moving data within tables or arrays, possibly for batch processing or data manipulation. The exact functionality may depend a lot on ladderlib's implementation.
- Example Use: Moving a set of values to a new memory block.
- Instruction Code:
LADDER_INS_FOREIGN
(35) - Description: Allows calling external or user-defined functions not natively supported by ladder logic. It enables integration with custom code.
- Example Use: Calling a custom algorithm for complex calculations.
- Instruction Code:
LADDER_INS_INV
(37) - Description: Marks the beginning of invalid instruction codes, not intended for use in programs. It serves as a boundary for valid instructions.
- Example Use: None, as it is not used in programming.
- Instruction Code:
LADDER_INS_MULTI
(255, 0xff) - Description: Indicates that the cell is part of a larger instruction spanning multiple cells, used for complex operations requiring additional data.
- Example Use: Implementing a multi-step operation like a sequence control.
Defines 6 possible states for program execution:
STOPPED
: Program is halted.RUNNING
: Program is actively executing.ERROR
: An error has occurred.EXIT_TSK
: Task is exiting.NULLFN
: Null function encountered.INV
: Invalid state.
These states manage the lifecycle of the ladder logic program, ensuring proper control and error handling.
Provides 8 error codes for instruction execution:
OK
: Successful execution.GETPREVVAL
: Error retrieving previous value.GETDATAVAL
: Error getting data value.SETDATAVAL
: Error setting data value.NOFOREIGN
: No foreign function found.NOTABLE
: Table not found.OUTOFRANGE
: Value out of range.FAIL
: General failure.
These codes help developers diagnose and handle issues during program execution.
Defines 15 data types and 4 basetime options:
- Types:
NONE
,M
(Memory Register),Q
(Output),I
(Input),Cd
(Counter Done),Cr
(Counter Running),Td
(Timer Done),Tr
(Timer Running),IW
(Input Word),QW
(Output Word),C
(Counter),T
(Timer),D
(Data Register),CSTR
(Constant String),REAL
(Floating Point). - Basetime Options:
BASETIME_MS
,BASETIME_10MS
,BASETIME_100MS
,BASETIME_SEC
,BASETIME_MIN
.
These types support various data representations, crucial for defining inputs, outputs, and internal variables.
Ladderlib uses structures to organize ladder logic programs, hardware interactions, and execution management. Below is a detailed breakdown of key structures.
Represents an individual cell in a ladder logic diagram, akin to a contact or coil in a relay circuit.
Field | Description |
---|---|
state |
Current state of the cell (e.g., on/off). |
vertical_bar |
Indicates vertical connection presence. |
code |
Instruction code from LADDER_INSTRUCTIONS . |
data_qty |
Number of data elements associated. |
data |
Array of ladder_value_s for cell data. |
Represents a network or rung, a horizontal line in the ladder diagram containing multiple cells.
Field | Description |
---|---|
enable |
Flag to enable/disable the network. |
cells |
Array of ladder_cell_s for the network. |
Manages timer functions for time-based operations.
Field | Description |
---|---|
time_stamp |
Timestamp for timer operations. |
acc |
Accumulator for timer value. |
The main structure for the ladder logic program, encapsulating overall state and configuration.
Field | Description |
---|---|
state |
Current state from LADDER_STATE . |
last |
Tracks last executed instruction, network, etc. |
quantity |
Quantities of memory, inputs, outputs, etc. |
Handles hardware interactions, providing function pointers for I/O and timing. This Functions are external and hardware dependant
Field | Description |
---|---|
_read_inputs_local |
Reads local hardware inputs. |
_write_outputs_local |
Writes to local outputs. |
_read_inputs_remote |
Reads remote inputs. |
_write_outputs_remote |
Writes to remote outputs. |
_millis |
Returns current time in milliseconds. |
_delay |
Delays execution for a specified time. |
Manages execution events through callbacks. This functions are optionals.
Field | Description |
---|---|
_on_scan_end |
Called at the end of a scan cycle. |
_on_instruction |
Called per instruction execution. |
_on_task_before |
Called before task execution. |
_on_task_after |
Called after task execution. |
_on_panic |
Handles panic situations. |
_on_end_task |
Called at task completion. |
Additional structures include:
ladder_instructions_ioc_s
: Defines input/output/cell configurations.ladder_value_s
: Holds data with type and union (u32, i32, cstr, real).ladder_memory_s
: Manages memory areas (M, I, Q, etc.).ladder_prev_scan_vals_s
: Stores previous scan values.ladder_registers_s
: Manages registers (IW, QW, C, D, R).ladder_scan_internals_s
: Tracks scan timing information.ladder_foreign_function_s
: Defines custom functions with ID, name, and execution logic.ladder_foreign_s
: Manages a collection of foreign functions.ladder_ctx_s
: The main context, combining all components for program execution.
The API provides functions for initializing, running, and managing ladder logic programs. Below is a detailed description of each.
Initializes the ladder context, setting up structures and resources.
Parameter | Description |
---|---|
net_columns_qty |
Number of columns in networks (max 32). |
net_rows_qty |
Number of rows in networks. |
networks_qty |
Number of networks. |
qty_m , qty_i , etc. |
Quantities for memory, inputs, outputs, etc. |
Returns: Pointer to ladder_ctx_s
.
Deinitializes the context, freeing allocated resources.
Parameter | Description |
---|---|
ladder_ctx |
Pointer to ladder_ctx_s . |
Executes the ladder logic task, processing networks and cells.
Parameter | Description |
---|---|
ladderctx |
Pointer to ladder_ctx_s . |
Clears the current ladder logic program, resetting the context.
Parameter | Description |
---|---|
ladder_ctx |
Pointer to ladder_ctx_s . |
Adds custom (foreign) functions to the context for extended functionality.
Parameter | Description |
---|---|
ladder_ctx |
Pointer to ladder_ctx_s . |
fn_init |
Initialization function for foreign functions. |
init_data |
Data for initialization. |
qty |
Number of foreign functions to add. |
Assigns a function to a specific cell in the ladder logic.
Parameter | Description |
---|---|
ladder_ctx |
Pointer to ladder_ctx_s . |
network |
Network index. |
row |
Row index within the network. |
column |
Column index within the network. |
function |
Function code to assign. |
foreign_id |
ID of foreign function, if applicable. |
To use Ladderlib, follow these steps:
- Initialize Context: Call
ladder_ctx_init
with appropriate quantities for networks, memory areas, inputs, outputs, counters, timers, data, and registers. - Define Program: Populate the
ladder_s
structure by defining networks (ladder_network_s
) and cells (ladder_cell_s
), assigning instructions fromLADDER_INSTRUCTIONS
and configuring data or timers as needed. - Set Hardware Callbacks: Provide functions for hardware interactions in
ladder_hw_s
, such as_read_inputs_local
and_write_outputs_local
, to interface with physical devices. - Set Event Callbacks: Optionally, assign callbacks in
ladder_manage_s
for events like scan end (_on_scan_end
) or panic handling (_on_panic
). - Run Task: Execute the ladder logic by calling
ladder_task
periodically, typically in a loop, to process the program and interact with hardware. - Monitor and Handle Errors: Check
LADDER_STATE
andLADDER_INS_ERROR
to monitor execution status and handle errors. - Deinitialize: Call
ladder_ctx_deinit
to free resources when the program is no longer needed.
Below is a simplified example of how to structure a Ladderlib program:
// TODO: EXAMPLE
This example initializes a context, sets hardware callbacks, defines a simple program, runs the task, and deinitializes the context. Actual implementations will vary based on specific hardware and logic requirements.
// TODO: DOC