Skip to content
Beta.c@modelscript/c 10 diagnostic rules
Parser WASM GLR
Diagnostics 10 rules
DAE Arena Lowering
Simulation Co-sim / Export
Projections Modelica
Live ExampleFocCurrentLoop.c

Embedded C Field-Oriented Control (FOC) PI Regulator

Deterministic C control law with integral anti-windup clamped to bus voltage limits, scraped and lowered into the DAE arena.

Playground
Source (20 lines)
1// Embedded C Discrete PI Current Controller with Anti-Windup
2typedef struct {
3  double kp;
4  double ki;
5  double v_max;
6  double integral;
7} PiController;
8 
9double pi_current_step(PiController *ctrl, double i_ref, double i_meas, double dt) {
10  double err = i_ref - i_meas;
11  double candidate = ctrl->integral + ctrl->ki * err * dt;
12  if (candidate > ctrl->v_max) candidate = ctrl->v_max;
13  if (candidate < -ctrl->v_max) candidate = -ctrl->v_max;
14  ctrl->integral = candidate;
15 
16  double v_out = ctrl->kp * err + ctrl->integral;
17  if (v_out > ctrl->v_max) return ctrl->v_max;
18  if (v_out < -ctrl->v_max) return -ctrl->v_max;
19  return v_out;
20}
C External Function & DAE Block Interface
call v_out «c_inputs» FOC Telemetry Inputs «arguments» double i_ref [A] double i_meas [A] double dt [s] «c_function» pi_current_step() «struct picontroller» err = i_ref - i_meas integral += ki * err * dt clamp(±v_max) anti-windup «dae_output» DAE Arena Lowering «return» double v_out [V] Clamped Bus Command
Drag to pan · Click % to reset

C Numerical & Embedded Engineering Integration (.c, .h) ​

@modelscript/c (languages/c) provides native WebAssembly GLR parsing, procedural simulation step compilation, automated Modelica external "C" header binding, continuous DAE lowering, and static analysis diagnostics for ANSI C / C99 engineering blocks, Simulink C MEX S-functions, and PSCAD custom C components.


Supported Extensions & Standards ​

ExtensionStandard / FormatDescription
.cC99 / ANSI CControl algorithms, filter routines, ODE integration steps, and S-functions
.hC HeadersFunction prototypes, typedefs, and struct layouts for Modelica external bindings

Key Capabilities ​

1. WebAssembly GLR C Parser ​

  • Ahead-of-time compiled WebAssembly GLR parser generated by @modelscript/dsl with zero grammar conflicts.
  • Parses full C99 translation units, nested functions, struct/union/enum declarations, typedef names, control flow (if, while, for, do-while), pointer/array operators, and bitwise/arithmetic expressions.

2. Automated Modelica External "C" Bridge ​

  • Header Scraper (scrapeCHeader) extracts C prototypes, argument names, causalities, and struct fields from .h files.
  • Modelica Binder (bindCHeaderToModelica) auto-generates strongly typed Modelica functions with:
    modelica
    function motor_torque
      input Real current;
      input MotorParams p;
      output Real y;
      external "C" y = motor_torque(current, p)
        annotation(Include = "#include \"motor.h\"");
    end motor_torque;

3. Zero-Allocation Simulation Step Compiler ​

  • Compiles procedural C control blocks and discrete filters into low-overhead execution closures executing 100,000 steps in < 30ms without heap allocations.
  • Direct mapping to pre-allocated typed arrays: statesReal (Float64Array) and statesInt (Int32Array).
  • Built-in support for standard <math.h> mathematical functions (sin, cos, tan, asin, acos, atan, atan2, exp, log, log10, sqrt, fabs, pow, fmin, fmax, floor, ceil).

4. Direct DAE Subroutine Lowering ​

  • Translates ODE continuous state derivatives (dx[i] = ... / der_x = ...) directly into continuous states der(s_i) in @modelscript/runtime's IDaeBuilder linear memory arena.
  • Enables Simulink continuous S-functions and PSCAD C segments to integrate directly into continuous DAE and hybrid ODE solvers.

Static Analysis & Safety Linter Rules ​

The C analyzer surfaces common numeric defects, memory safety concerns, and algorithmic cycles (M8401–M8410):

10 rules3 warning6 error1 info Run with msx lint

CodeRuleSeverityMessage
M8401uninitialized-variablewarningLocal variable '<varName>' may be read before being initialized.
M8402constant-division-by-zeroerrorDivision or modulo by constant zero detected in arithmetic expression.
M8403array-bounds-overflowerrorStatic array subscript '<arrName>[<index>]' exceeds declared dimension bound of <bound>.
M8404unreachable-codewarningUnreachable statements detected following unconditional 'return', 'break', or 'goto'.
M8405assignment-in-conditionalwarningAssignment operator '=' used inside conditional expression; did you mean '=='?
M8406algebraic-dependency-cycleerrorProcedural algebraic dependency cycle detected without state lag: '<cycle>'.
M8407null-pointer-dereferenceerrorDereference of statically known NULL pointer in expression '<expr>'.
M8408function-prototype-mismatcherrorFunction '<fnName>' signature conflicts with declaration: expected '<expected>', got '<actual>'.
M8409missing-return-valueerrorNon-void function '<fnName>' with return type '<returnType>' reaches end of body without returning a value.
M8410implicit-lossy-conversioninfoImplicit floating-point to integer conversion from '<fromType>' to '<toType>' may cause lossy truncation.

Generated from languages/c/src/errors.ts. All languages →


CLI Usage ​

bash
# Lint C source files or headers
msx lint Controller.c

# Generate Modelica external "C" bindings from header
msx c to-modelica SensorDriver.h -o SensorDriver.mo

Open-Core under the GNU AGPL v3 License; Enterprise Edition (ee/) under the ModelScript Enterprise License. • Trademark Policy