The C++ side: Building the physical model
The C++ implementation is divided into three major components.
1. PID Controller
The PID class implements the familiar proportional, integral and derivative control mechanism.
The controller receives:
It calculates the control force using the accumulated error, the current error and the rate of change of error.
The essential control equation is:
$$
u(t) = K_p e(t) + K_i \int e(t)\,dt + K_d \frac{de(t)}{dt}
$$
The implementation maintains the integral and previous error internally. This means that the controller has state, just as a real controller does.
2. Plant
The Plant class represents a simple mass-spring-damper system.
Its physical model is based on Newton's second law:
[
\[
m\ddot{x} + c\dot{x} + kx = F
\]
]
where:
(m) is mass
(c) is damping
(k) is spring stiffness
(F) is the applied force
The plant calculates acceleration from the net force and updates its velocity and position using semi-implicit Euler integration.
This is a small but important step. We are no longer simply calculating a mathematical expression; we are simulating the evolution of a physical system over time.
3. Simulation
The Simulation class brings the controller and plant together.
At every time step:
The plant's current position is measured.
The PID controller calculates the required force.
The force is applied to the plant.
The plant advances to its next state.
The simulation returns position, velocity, force and error.
The entire control loop is encapsulated in C++.
This separation of responsibilities makes the implementation easier to understand, maintain and extend.
Bringing Julia into the picture
The next challenge was to make this C++ simulation accessible from Julia.
I used jluna, a C++–Julia interoperability library, to establish the bridge.
Rather than exposing the entire C++ object model directly, I created a small set of functions that Julia can call.
For example, the C++ side provides functions for creating a PID controller, updating it, resetting it and deleting it.
The simulation has a similar interface:
Simulation(kp, ki, kd, mass, damping, stiffness)
sim_step(sim, setpoint, dt)
The Julia code does not need to know how the C++ classes are implemented internally.
It simply creates a simulation, advances it and receives numerical results.
This is an important architectural decision. The bridge exposes the functionality that Julia needs without unnecessarily exposing the internal implementation.
Studying different PID responses
I then extended the program to investigate how different PID gains affect the response of the system.
Three sets of controller parameters were selected.
Underdamped response
run_regime(18.0, 2.0, 0.2)
A relatively low derivative gain produces an oscillatory response in this experiment.
The plant approaches the target position, overshoots it and oscillates before settling.
Fast settling response
run_regime(18.0, 4.0, 8.5)
This parameter set produces a response intended to demonstrate a faster, more balanced approach to the setpoint with reduced overshoot.
It is labelled as the critically damped response in the experiment. Strictly speaking, critical damping is a mathematical condition, and the actual response of a PID-controlled system depends on the complete closed-loop dynamics. The label here describes the intended response regime rather than a formally verified critical-damping condition.
Overdamped response
run_regime(18.0, 2.0, 22.0)
A higher derivative gain produces a more sluggish response in this experiment, with a slower approach to the target.
The three experiments illustrate an important engineering lesson: controller tuning is not simply about increasing gains. The objective is to find a suitable balance between speed, stability and overshoot.
Julia takes over the visualization
After running the simulations, Julia writes the collected data to a CSV file.
The plotting script then uses Plots.jl to generate four figures:
The underdamped response
The fast-settling response
The overdamped response
A combined comparison of all three trajectories
The combined graph is particularly useful because it allows us to compare the response curves against the same setpoint.
The visualization is generated by Julia, but the underlying physical simulation is executed by C++.
This is where the two languages complement each other rather than compete with each other.
Why this combination makes sense
C++ gives us control over the structure and implementation of the simulation.
We can use classes, encapsulation, modern C++ features and efficient numerical computation to build the model.
Julia gives us a convenient environment for experimentation.
We can change parameters, run multiple simulations, collect data, perform numerical analysis and generate plots without rewriting the simulation engine.
For scientific computing, this separation can be extremely useful.
A simulation engine written in C++ can remain stable while the experimental environment evolves rapidly in Julia.
The same approach could be extended to:
Source Code
Main.cpp
#include "PID.hpp"
#include "Plant.hpp"
#include "Simulation.hpp"
#include <jluna.hpp>
#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
#include <mutex>
#include <stdexcept>
using namespace jluna;
static std::unordered_map<Int64, PID*> g_pids;
static std::unordered_map<Int64, Simulation*> g_sims;
static std::mutex g_mutex;
static Int64 g_next_id = 1;
static Int64 g_next_sim_id = 1;
static Int64 register_pid(PID* p)
{
std::lock_guard lock(g_mutex);
Int64 id = g_next_id++;
g_pids[id] = p;
return id;
}
static PID* get_pid(Int64 id)
{
std::lock_guard lock(g_mutex);
auto it = g_pids.find(id);
if (it == g_pids.end())
throw std::runtime_error("invalid PID handle");
return it->second;
}
static void erase_pid(Int64 id)
{
std::lock_guard lock(g_mutex);
auto it = g_pids.find(id);
if (it != g_pids.end()) {
delete it->second;
g_pids.erase(it);
}
}
static Int64 register_sim(Simulation* sim)
{
std::lock_guard lock(g_mutex);
Int64 id = g_next_sim_id++;
g_sims[id] = sim;
return id;
}
static Simulation* get_sim(Int64 id)
{
std::lock_guard lock(g_mutex);
auto it = g_sims.find(id);
if (it == g_sims.end())
throw std::runtime_error("invalid Simulation handle");
return it->second;
}
static void erase_sim(Int64 id)
{
std::lock_guard lock(g_mutex);
auto it = g_sims.find(id);
if (it != g_sims.end()) {
delete it->second;
g_sims.erase(it);
}
}
int main()
{
try {
const std::string jluna_so =
"/home/som/Workspace/C++/AdvancedC++20/CPP-Julia-Bridge/PID_CPP_Julia/third_party/jluna/install/libjluna.so";
const std::string julia_bindir =
"/home/som/.julia/juliaup/julia-1.10.10+0.x64.linux.gnu/bin";
const std::string julia_image =
"/home/som/.julia/juliaup/julia-1.10.10+0.x64.linux.gnu/lib/julia/sys.so";
initialize(1, false, jluna_so, julia_bindir, julia_image);
// ---- PID bindings ----
Main.create_or_assign("pid_create",
as_julia_function<Int64(std::vector<double>)>(
[](std::vector<double> gains) -> Int64
{
if (gains.size() != 3)
throw std::runtime_error("pid_create expects [kp, ki, kd]");
return register_pid(new PID(gains[0], gains[1], gains[2]));
}));
Main.create_or_assign("pid_update_aux",
as_julia_function<double(Int64, std::vector<double>)>(
[](Int64 id, std::vector<double> v) -> double
{
if (v.size() != 3)
throw std::runtime_error("pid_update expects [sp, meas, dt]");
return get_pid(id)->update(v[0], v[1], v[2]);
}));
Main.create_or_assign("pid_reset",
as_julia_function<void(Int64)>(
[](Int64 id) -> void { get_pid(id)->reset(); }));
Main.create_or_assign("pid_delete",
as_julia_function<void(Int64)>(
[](Int64 id) -> void { erase_pid(id); }));
// ---- Simulation bindings ----
Main.create_or_assign("sim_create_aux",
as_julia_function<Int64(std::vector<double>)>(
[](std::vector<double> p) -> Int64
{
if (p.size() != 6)
throw std::runtime_error("sim_create expects 6 parameters");
auto* sim = new Simulation(p[0], p[1], p[2], p[3], p[4], p[5]);
return register_sim(sim);
}));
Main.create_or_assign("sim_step_aux",
as_julia_function<std::vector<double>(Int64, std::vector<double>)>(
[](Int64 id, std::vector<double> p) -> std::vector<double>
{
if (p.size() != 2)
throw std::runtime_error("sim_step expects [setpoint, dt]");
return get_sim(id)->step(p[0], p[1]);
}));
Main.create_or_assign("sim_reset",
as_julia_function<void(Int64)>(
[](Int64 id) -> void { get_sim(id)->reset(); }));
Main.create_or_assign("sim_delete",
as_julia_function<void(Int64)>(
[](Int64 id) -> void { erase_sim(id); }));
// ---- Julia-friendly wrappers ----
Main.safe_eval(R"(
PID(kp, ki, kd) = pid_create(Float64[kp, ki, kd])
pid_update(id, sp, meas, dt) = pid_update_aux(id, Float64[sp, meas, dt])
Simulation(kp, ki, kd, mass, damping, stiffness) =
sim_create_aux(Float64[kp, ki, kd, mass, damping, stiffness])
sim_step(id, setpoint, dt) =
sim_step_aux(id, Float64[setpoint, dt])
)");
// ---- PID Self-test ----
Main.safe_eval(R"(
p = PID(1.0, 0.1, 0.05)
println("handle = ", p, " typeof = ", typeof(p))
println("update = ", pid_update(p, 10.0, 0.0, 0.01))
pid_reset(p)
pid_delete(p)
println("PID bridge OK")
)");
// ---- Julia-controlled simulation ----
Main.safe_eval(R"(
println("\nJulia-controlled simulation:")
# Higher kp (15.0) + lower damping (0.3) + 4.0 seconds (400 steps)
sim = Simulation(15.0, 0.5, 0.0, 1.0, 0.3, 2.0)
setpoint = 1.0
dt = 0.01
steps = 400
times = Float64[]
positions = Float64[]
velocities = Float64[]
forces = Float64[]
errors = Float64[]
for i in 1:steps
result = sim_step(sim, setpoint, dt)
push!(times, i * dt)
push!(positions, result[1])
push!(velocities, result[2])
push!(forces, result[3])
push!(errors, result[4])
if i % 10 == 0
println(
"t = ", times[end],
" x = ", positions[end],
" v = ", velocities[end],
" force = ", forces[end],
" error = ", errors[end]
)
end
end
println("Julia simulation completed.")
println("Collected ", length(times), " samples.")
flush(stdout)
sim_delete(sim)
)");
// ---- Blog Post Visualization: Underdamped, Critically Damped (Steady-State), and Overdamped
Main.safe_eval(R"julia(
println("\nRunning PID damping regime simulations for blog post...")
function run_regime(kp, ki, kd; setpoint=1.0, dt=0.01, steps=800)
sim = Simulation(kp, ki, kd, 1.0, 0.5, 2.0)
t = Vector{Float64}(undef, steps)
x = Vector{Float64}(undef, steps)
for i in 1:steps
res = sim_step(sim, setpoint, dt)
t[i] = i * dt
x[i] = res[1]
end
sim_delete(sim)
return t, x
end
# 1. Underdamped (low Kd -> oscillatory decay)
t, x_under = run_regime(18.0, 2.0, 0.2)
# 2. Critically Damped / Fast Steady-State (balanced Kd -> fast settle, no overshoot)
_, x_crit = run_regime(18.0, 4.0, 8.5)
# 3. Overdamped (high Kd -> sluggish approach, no overshoot)
_, x_over = run_regime(18.0, 2.0, 22.0)
using DelimitedFiles
writedlm("blog_damping_data.csv", hcat(t, x_under, x_crit, x_over), ',')
plot_script = """
ENV["GKSwstype"] = "100"
using DelimitedFiles, Plots
d = readdlm("blog_damping_data.csv", ',')
t, x_under, x_crit, x_over = d[:, 1], d[:, 2], d[:, 3], d[:, 4]
sp = 1.0
# Common styling for crisp blog figures (high DPI)
base_kwargs = (
xlabel = "Time (s)",
ylabel = "Position x(t)",
xlims = (0, 8.0),
ylims = (0, 1.85),
grid = true,
minorgrid = true,
framestyle = :box,
dpi = 300,
size = (850, 480)
)
# --- Graph 1: Underdamped Response ---
p_under = plot(t, x_under;
title = "1. Underdamped PID Response (Kp=18, Ki=2, Kd=0.2)",
label = "Underdamped Trajectory",
color = :royalblue,
linewidth = 2.5,
base_kwargs...
)
hline!(p_under, [sp], label = "Steady-State Setpoint (1.0)", linestyle = :dash, color = :black)
savefig(p_under, "blog_1_underdamped.png")
# --- Graph 2: Critically Damped / Steady-State Response ---
p_crit = plot(t, x_crit;
title = "2. Critically Damped / Steady-State Response (Kp=18, Ki=4, Kd=8.5)",
label = "Critically Damped Trajectory",
color = :forestgreen,
linewidth = 2.5,
base_kwargs...
)
hline!(p_crit, [sp], label = "Steady-State Setpoint (1.0)", linestyle = :dash, color = :black)
savefig(p_crit, "blog_2_steadystate_critically_damped.png")
# --- Graph 3: Overdamped Response ---
p_over = plot(t, x_over;
title = "3. Overdamped PID Response (Kp=18, Ki=2, Kd=22.0)",
label = "Overdamped Trajectory",
color = :darkorange,
linewidth = 2.5,
base_kwargs...
)
hline!(p_over, [sp], label = "Steady-State Setpoint (1.0)", linestyle = :dash, color = :black)
savefig(p_over, "blog_3_overdamped.png")
# --- Graph 4: Combined Blog Hero Comparison ---
p_all = plot(t, x_under;
title = "PID Control Damping Regimes (C++ Simulation + Julia Plots)",
label = "Underdamped (Kd = 0.2)",
color = :royalblue,
linewidth = 2.5,
base_kwargs...
)
plot!(p_all, t, x_crit, label = "Critically Damped / Optimal Steady-State (Kd = 8.5)", color = :forestgreen, linewidth = 2.5)
plot!(p_all, t, x_over, label = "Overdamped (Kd = 22.0)", color = :darkorange, linewidth = 2.5, linestyle = :dashdot)
hline!(p_all, [sp], label = "Target Setpoint (1.0)", linestyle = :dash, color = :black)
savefig(p_all, "blog_4_combined_comparison.png")
println("Generated all 4 blog PNGs in: ", pwd())
"""
cmd = addenv(`$(Base.julia_cmd()) -e $plot_script`, "LD_LIBRARY_PATH" => "")
run(cmd)
flush(stdout)
)julia");
}
catch (const std::exception& e) {
std::cerr << "Julia/jluna error: " << e.what() << std::endl;
}
// ---- Pure C++ Plant verification ----
Plant plant(1.0, 0.5, 2.0);
std::cout << "\nPlant test:\n";
for (int i = 0; i < 10; ++i)
{
plant.update(10.0, 0.01);
std::cout << "t = " << (i + 1) * 0.01
<< " x = " << plant.position()
<< " v = " << plant.velocity()
<< std::endl;
}
return 0;
}
PID.hpp
#pragma once
class PID {
public:
PID(double kp, double ki, double kd);
double update(double setpoint,
double measurement,
double dt);
void reset();
private:
double kp_;
double ki_;
double kd_;
double integral_;
double previous_error_;
};
PID.cpp
#include "PID.hpp"
PID::PID(double kp, double ki, double kd)
: kp_(kp),
ki_(ki),
kd_(kd),
integral_(0.0),
previous_error_(0.0)
{
}
double PID::update(double setpoint,
double measurement,
double dt)
{
const double error = setpoint - measurement;
integral_ += error * dt;
const double derivative =
(error - previous_error_) / dt;
previous_error_ = error;
return kp_ * error
+ ki_ * integral_
+ kd_ * derivative;
}
void PID::reset()
{
integral_ = 0.0;
previous_error_ = 0.0;
}
cmake_minimum_required(VERSION 3.20)
project(PID_CPP_Julia
VERSION 1.0
LANGUAGES CXX
)
# --------------------------------------------------
# C++ Standard (jluna requires C++20)
# --------------------------------------------------
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
# --------------------------------------------------
# Julia Discovery
# --------------------------------------------------
execute_process(
COMMAND julia -e "print(Sys.BINDIR)"
OUTPUT_VARIABLE JULIA_BINDIR
OUTPUT_STRIP_TRAILING_WHITESPACE
)
if(NOT JULIA_BINDIR)
message(FATAL_ERROR "Julia executable not found in PATH.")
endif()
get_filename_component(JULIA_PREFIX "${JULIA_BINDIR}" DIRECTORY)
set(JULIA_INCLUDE_DIR "${JULIA_PREFIX}/include/julia")
set(JULIA_LIB_DIR "${JULIA_PREFIX}/lib")
message(STATUS "Julia BINDIR : ${JULIA_BINDIR}")
message(STATUS "Julia PREFIX : ${JULIA_PREFIX}")
message(STATUS "Julia INCLUDE_DIR : ${JULIA_INCLUDE_DIR}")
message(STATUS "Julia LIB_DIR : ${JULIA_LIB_DIR}")
# --------------------------------------------------
# jluna (Pre-built in third_party/jluna/install)
# --------------------------------------------------
set(JLUNA_ROOT ${CMAKE_CURRENT_SOURCE_DIR}/third_party/jluna)
set(JLUNA_LIB_DIR ${JLUNA_ROOT}/install)
find_library(JLUNA_LIB
NAMES jluna
PATHS ${JLUNA_LIB_DIR}
NO_DEFAULT_PATH
REQUIRED
)
# Locate jluna.jl runtime script
if(EXISTS "${JLUNA_ROOT}/jluna.jl")
set(JLUNA_JL_PATH "${JLUNA_ROOT}/jluna.jl")
elseif(EXISTS "${JLUNA_ROOT}/jluna/jluna.jl")
set(JLUNA_JL_PATH "${JLUNA_ROOT}/jluna/jluna.jl")
endif()
message(STATUS "jluna library : ${JLUNA_LIB}")
message(STATUS "jluna script : ${JLUNA_JL_PATH}")
# --------------------------------------------------
# Executable Configuration
# --------------------------------------------------
add_executable(PID_CPP_Julia
cpp/main.cpp
cpp/PID.cpp
cpp/Plant.cpp
cpp/Simulation.cpp
)
target_include_directories(PID_CPP_Julia PRIVATE
cpp
${JLUNA_ROOT}
${JLUNA_ROOT}/include
${JLUNA_ROOT}/install/include
${JULIA_INCLUDE_DIR}
)
# Pass script path to C++ macro
target_compile_definitions(PID_CPP_Julia PRIVATE
JLUNA_JL_PATH=${JLUNA_JL_PATH}
)
target_link_directories(PID_CPP_Julia PRIVATE
${JULIA_LIB_DIR}
${JLUNA_LIB_DIR}
)
target_link_libraries(PID_CPP_Julia PRIVATE
${JLUNA_LIB}
julia
dl
pthread
m
rt
)
# Set RPATH so executable finds libjulia.so and libjluna.so at runtime
set_target_properties(PID_CPP_Julia PROPERTIES
BUILD_RPATH "${JULIA_LIB_DIR};${JLUNA_LIB_DIR}"
INSTALL_RPATH "${JULIA_LIB_DIR};${JLUNA_LIB_DIR}"
)
target_compile_features(PID_CPP_Julia PRIVATE cxx_std_20)