Furuta pendulum at 250 µs
This Furuta rotary inverted pendulum example shows closed-loop control with counter IO and a CiA 402 stepper axis on the same EtherCAT network: a GCAN-8200 reads the pendulum encoder, the arm stepper receives target positions in CSP mode, and the control sequence covers connection, enable, recentering, energy-based swing-up, handoff and balancing.
This page uses 250 µs (4 kHz) as the target cycle time to explain the configuration. The cycle time, PDO layout and control parameters must be reviewed as one set; do not change only the cycle value and continue motion.
The complete project, parameter files and operating instructions: https://github.com/DarraTechnology/Windows-FurutaPendulum
Both the 1 ms and 500 µs balance baselines have now PASSED: 1 ms completed a 30 s PASS (exit=0, no Fault); 500 µs measured 500000 ns, 30 s, 2 slaves in OP, WKC 4/4, exit=0, no Fault, max|φ̇|=6.79, max|aCmd|=297.6, and 4 swing-up revolutions. 250 µs did not pass and is outside the current EZI drive + control envelope: decimation=2 produced FollowingError, and full-rate (Kψ/Kω=0.5/ref16) produced BalanceLost (max|φ̇|=16.14, aCmd800). 500 µs is the highest verified stable frequency; at 250 µs, still repeat connection, enable, swing-up, handoff and balancing with the same DENI topology and mappings used by this example; this page does not claim that balancing at 250 µs has passed.
The disturbance observer is off by default (enable it explicitly with FURUTA_DIST_OBS=1); the 0.065 disturbance test at 500 µs resulted in FAIL (ThetaOverrun), so disturbance rejection must not be described as passed. For acceptance, inspect the dHat / dConf / ff / margin / freeze log fields.
Hardware and cycle configuration
| Item | Example configuration |
|---|---|
| Master NIC | Intel 82575EB, MAC A0:10:A2:B6:94:8A |
| Arm actuator | Ezi-SERVO2 stepper (EC1 series), CSP mode |
| Encoder input | GCAN-8200 EtherCAT MDP coupler with a GC1602 AB quadrature counter slice |
| Pendulum encoder | 2400 CPR (600 lines × AB quadrature); approximately 0 count hanging down and ±1200 count upright |
| Arm resolution | Read 0x2102 during connection and enable, then derive counts per revolution with the gear ratio; no fixed value is assumed |
| Mechanical coupling ratio | r/l = 0.24, measured by calibrate-radius |
| Master index | master index = 1; cycle events and process-data reads use the same master number |
| Network configuration | EtherCATRestore/config.deni below the executable directory |
0x2102 is the live source for arm counts per revolution; an explicit calibration and the parameter file are only defined fallbacks. After changing the motor, microstepping or gear ratio, check the live value and angle conversion again. r/l is a mechanical parameter: use the calibrate-radius measurement, not a historical fitted value.
DENI and 250 µs settings
| Setting | Target | Notes |
|---|---|---|
DENI cycleNs | 250000 | 250 µs = 4 kHz |
Master PDO LoopCycle | 250 µs | Match the DENI cycle time and read it back after connecting |
| EC1 SYNC0 | 1 ms recommended | When DC is enabled, use an integer multiple supported by the drive. 1 ms is 4 × the master's 250 µs cycle; it does not reduce the master to 1 ms |
| Control thread | Follows the bus cycle | Completed PASS: 1 ms at 1 kHz and 500 µs at 2 kHz (highest stable frequency); 250 µs (4 kHz) did not pass and is outside the current EZI drive + control envelope |
For 250 µs, first complete RT core isolation, NIC IRQ affinity and power configuration, then check measured cycle time, jitter, WKC and following error. High-performance power settings do not replace RT isolation and IRQ configuration, and application thread priority does not replace these machine-level prerequisites.
The DENI is the configuration authority for topology, PDO and cycle time; do not hand-edit a configuration file that carries integrity data. Use the master configuration tool to export config.deni with 250000 ns from the same physical topology while keeping slaves and PDO mappings unchanged, then repeat the full sequence with that file. If EC1 DC is enabled, separately verify SYNC0 arming and its permitted cycle window.
PDO process-data layout
@n denotes a byte offset. Field order must match the device's actual PDO entries byte for byte; do not reorder fields by object-dictionary index.
| Direction | PDO | Entry order | Total width |
|---|---|---|---|
| Arm RxPDO | 0x1600 | 0x6040:16bit@0 → 0x607A:32bit@2 → 0x6060:8bit@6 | 56 bit = 7 B |
| Arm TxPDO | 0x1A00 | 0x603F:16bit@0 → 0x6041:16bit@2 → 0x6064:32bit@4 → 0x606C:32bit@8 → 0x60FD:32bit@12 → 0x6061:8bit@16 | 136 bit = 17 B |
| GCAN input | 0x1A03 | 0x6003:1 / 0x6003:2, two signed 32-bit counters | 64 bit = 8 B |
Arm stepper PDO
Source: StepperRxPdo and StepperTxPdo in Control/PdoStructs.cs (XML comments omitted).
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct StepperRxPdo
{
public ushort ControlWord;
public int TargetPosition;
public sbyte ModesOfOperation;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct StepperTxPdo
{
public ushort ErrorCode;
public ushort StatusWord;
public int ActualPosition;
public int ActualVelocity;
public uint DigitalInputs;
public sbyte ModesDisplay;
}
0x6040: CiA 402 control word, used for the0x06 → 0x07 → 0x0Fenable sequence; fault finalization writes0x0000.0x607A: CSP target position, updated every control cycle. CSP does not use the PP "new set-point" handshake bit.0x6060: mode of operation; write8for CSP.0x6041: CiA 402 status word. Decode it with masks rather than treating the raw integer as a state.0x6064: actual position. On this open-loop stepper it is the drive's integrated estimate of command position, not an external encoder measurement of the mechanical shaft angle.0x603F/0x606C/0x60FD/0x6061: error code, actual velocity, digital inputs and mode-of-operation display respectively.
GCAN encoder input
Source: Gcan1602TxPdo in Control/PdoStructs.cs (XML comments omitted).
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct Gcan1602TxPdo
{
public int CountCh1;
public int CountCh2;
}
CountCh1 maps 0x6003:1 and carries the pendulum encoder; CountCh2 maps 0x6003:2 and can carry a second encoder or a cross-check. Both are signed DINT counters. Pendulum angle is converted at 2400 CPR, and the angle loop uses the GCAN count rather than the stepper's 0x6064.
Cyclic control and application settings
Cyclic control thread
Source: Control/ControlThread.cs. These are the key calls, with exception handling, stall recovery and lifecycle management omitted.
private const uint WaitTimeoutMilliseconds = 0;
bool cycleReady;
cycleReady = _receiver.WaitForCycle(WaitTimeoutMilliseconds);
_engine.ExecuteCycle();
Both baseline cycles, 1 ms and 500 µs, have PASSED, corresponding to 1 kHz and 2 kHz respectively; the 250 µs target configuration is 4 kHz, did not pass and is outside the current EZI drive + control envelope; 500 µs is the highest verified stable frequency. CycleEventReceiver.WaitForCycle(0) checks the bus cycle event with a zero timeout. Once the cycle is ready, _engine.ExecuteCycle() computes the control output and writes 0x607A / 0x6040 in that same cycle. Do not approximate the cycle with Thread.Sleep, and do not defer the target-position write to a later UI-thread pass.
Soft real time and feedback window
Key lines from Control/SoftRealTime.cs and Control/ControlThread.cs.
process.PriorityClass = ProcessPriorityClass.RealTime;
thread.Priority = ThreadPriority.Highest;
previousMask = NativeMethods.SetThreadAffinityMask(
NativeMethods.GetCurrentThread(), mask);
uint result = NativeMethods.timeBeginPeriod(TimerPeriodMilliseconds);
private const int DefaultRtCpuIndex = 27;
- The process uses
ProcessPriorityClass.RealTime, corresponding toREALTIME_PRIORITY_CLASS. - The control thread uses
Highestand is pinned bySetThreadAffinityMaskto housekeeping CPU27 by default. On another machine, check the CPU index and role instead of copying the number. timeBeginPeriod(1)requests a 1 ms system timer resolution and is paired with restoration on exit; it does not determine the EtherCAT cycle time.- These application settings only reduce scheduling interference. They do not replace the RT core isolation, IRQ affinity and power configuration required at 250 µs.
Feedback has two layers: per-cycle differences use a first-order low-pass filter set by TdLpMs, while balancing estimates ω_est with a least-squares window that defaults to the swing-up value of 40 ms. To try a 20 ms balance feedback window, explicitly set FURUTA_BALANCE_OMEGA_WINDOW_MS=20 and run a comparison. 20 ms is an experimental setting, not the current default, and it does not take effect automatically when changing to 250 µs. After shortening the window, recheck quantization noise, handoff gates and dHat confidence.
Commands and operating sequence
The CLI implementation is in Cli/CliSession.Commands.cs. The stage sequence is enable → recenter → swingup → balance → stop / fault-reset. balance is the manual-capture entry and is not needed again after a successful automatic swing-up handoff.
# Command sequence
connect
enable
recenter
swingup
balance
stop
fault-reset
| Command | Action and criteria |
|---|---|
connect | Read EtherCATRestore/config.deni, check the NIC, slave identities, PDO mappings and cycle time, and establish the bus session. Connecting does not enable the drive |
enable | Pass the no-motion gate and then complete the CiA 402 enable sequence. Start with the pendulum hanging down and valid arm calibration |
recenter | Move the arm to the midpoint of its soft-limit travel and normalize around the center, leaving travel on both sides for swing-up |
swingup | Use energy-based swing-up and hand off automatically to Balancing when the capture gates pass. Otherwise wait or report a timeout as measured |
balance | Register a capture-balancing request when holding the pendulum manually. It is unnecessary after a successful automatic handoff |
stop | Perform a controlled stop and confirm both the stopped state and the control-word readback |
fault-reset | Remove the cause, release the hardware emergency stop and restore safe conditions before clearing faults and latches. Reset must not hide an active fault |
Swing-up and balance control
Handoff hard gates
Source: Step in Control/SwingUpController.cs.
bool currentStateOk =
Math.Abs(thetaFromUpright) <= 0.15 &&
Math.Abs(omegaEst) <= 1.2 &&
Math.Abs(phiDotRadPerSec) <= 2.5 &&
lowPsiOmegaOk &&
Math.Abs(aPend) <= 960.0 &&
Math.Abs(aArm) <= 160.0 &&
Math.Abs(a1) <= 220.0;
bool headGate = CaptureGateAllows(psiPred, omegaPred, phiDotRadPerSec, p);
bool ready =
!Recentering &&
currentStateOk &&
headGate;
Handoff is not based only on the pendulum reaching the top. The current hard gates include |ψ| ≤ 0.15 rad and |ω_est| ≤ 1.2 rad/s, while also bounding arm rate, the pendulum term and the arm term. |a1| ≤ 220 rad/s² ensures an unsaturated entry. The predicted-envelope gate and dwell counters still apply, and recentering never hands off. Do not loosen these gates just to make swingup return success.
Fixed four-gain feedback
Source: Control/PendulumEngine.cs.
internal const double BalanceKPsi = 5015.0;
internal const double BalanceKOmega = 573.0;
internal const double BalanceKPhiDot = -6.16;
internal const double BalanceKPhi = -8.51;
aCmdRaw = -(_balanceActiveProfile.KPsi * thetaFromUpright
+ _balanceActiveProfile.KOmega * omegaControl
+ balancePosTerm
+ balancePhiDotControlTerm);
The balance law uses the fixed gain vector K = [5015, 573, -8.51, -6.16], ordered as [Kψ, Kω, Kφ, Kφ̇]. Its output is the arm acceleration command aCmdRaw, which passes through authority arbitration and position-reference integration before becoming the CSP target position. Swing-up prediction, handoff entry and balancing read the same constants rather than maintaining three independently tuned copies.
R22 additive recentering and reference anti-windup
Source: the balance-control section of Control/PendulumEngine.cs.
uCmdEff = _balancePhiDotCmd;
double referenceRate = uCmdEff + (recentering ? _balanceRecenterRate : 0.0);
double previousCmd = _balanceCmdRad;
double requestedCmdNext = previousCmd + referenceRate * _dtSec;
R22 recentering does not replace the original four-gain position term. It adds a slow recentering rate to the balance law's self-integrated reference rate: referenceRate = uCmdEff + _balanceRecenterRate. Recentering yields immediately when the pendulum leaves its stable band or the observer requests a freeze, while balance feedback remains active.
The ±22 rad/s reference-rate bound is an integrator anti-windup budget, not an additional mechanical speed limit. During recentering, the position reference may also lead measured φ by no more than ±0.12 rad. After clamping, the reference rate is rewritten from the increment actually applied, preventing the integrator from accumulating further "rate debt".
Fault publication and disable order
Key lines from EmergencyStopInternal and WriteDisableVoltage in Control/PendulumEngine.cs.
Volatile.Write(ref _faultCode, (int)reported);
SetState(EngineState.Fault);
EnqueueFault(reported, from);
WriteDisableVoltage();
outPdo.TargetPosition = inPdo.ActualPosition;
outPdo.ModesOfOperation = CiA402.ModeCsp;
outPdo.ControlWord = CiA402.CwDisableVoltage;
The fault path publishes the fault code, Fault state and fault event before attempting to disable the drive. This preserves a real fault record even when process-data writes are blocked. Disable itself also has an order: pin 0x607A to 0x6064, confirm CSP, and only then write 0x6040 = 0x0000, avoiding a position step in the final frame.
Optional disturbance observer
Sources: Control/DisturbanceObserver.cs and Control/PendulumEngine.cs. The model is ψ̈ = (g/l)sinψ + (r/l)aArm + d, where aArm is the arm's measured acceleration rather than an unconfirmed command acceleration. Feedforward is aCmd_ff = −kff·dHat/b_ff.
feedForwardTarget = -_disturbanceHat / feedForwardCoupling * FeedForwardGain * weight;
double cap = Math.Min(
MaxCompensationRadPerSec2,
CompensationAuthorityRatio * input.ArmAccMaxRadPerSec2);
- The observer is off by default. Set
FURUTA_DIST_OBS=1explicitly to enable observation and feedforward. kff = 0.5andb_ff = max(r/l, 0.20). Feedforward authority is capped atmin(200, 0.20 × accMax) rad/s², leaving at least 80% of acceleration authority for balance feedback.- The observer uses fitted acceleration windows for both pendulum and arm, with confidence, saturation state and margin levels deciding feedforward and recentering freezes.
- Acceptance under external contact is not marked as passed in this page. During revalidation, inspect
dHat(estimated disturbance),dConf(confidence),ff(applied feedforward),margin(margin level) andfreeze(recentering freeze) in[BALANCE]logs, while checking that the pendulum stays within the safety-interlock envelope.
Revalidate at 250 µs
- Prepare the machine: complete RT core isolation, NIC IRQ affinity and high-performance power configuration, and confirm that the Intel 82575EB is the master NIC for this run.
- Export the configuration: export
EtherCATRestore/config.deniwithcycleNs = 250000from the same physical topology without changing PDO entry order. If DC is enabled, use the recommended 1 ms EC1 SYNC0 and read back its confirmation. - Check the connection: run
connectand confirmmaster index = 1, bus state OP, actual WKC equal to the value fixed at configuration time, and PDO sizes of 7 B / 17 B / 8 B. - Check the cycle: confirm a 250 µs master
LoopCycle, then record measured cycle time, maximum jitter, consecutive frame loss and control computation time. Do not rely on the configured value alone. - Calibrate and enable: check 2400 CPR for the pendulum, live
0x2102for the arm andr/l = 0.24, then runenableandrecenterand confirm no abnormal drift. - Swing up and balance: run
swingup, inspect each handoff-gate log entry, and then observe balancing. Current acceptance result: both 1 ms and 500 µs PASS; 500 µs measured500000 ns, 30 s, 2 slaves in OP, WKC 4/4, exit=0, no Fault,max|φ̇|=6.79,max|aCmd|=297.6, and 4 swing-up revolutions, and is the highest verified stable frequency; 250 µs did not pass and is outside the current EZI drive + control envelope:decimation=2producedFollowingError, and full-rate (Kψ/Kω=0.5/ref16) producedBalanceLost(max|φ̇|=16.14,aCmd800). The 0.065 disturbance test at 500 µs resulted inFAIL(ThetaOverrun), and the observer is off by default. Update the result for a given cycle only after the hardware or drive envelope changes and the run is repeated. - Optionally recheck disturbance response: set
FURUTA_DIST_OBS=1before an external-contact test, and savedHat/dConf/ff/margin/freezetogether with the interlock result. Do not claim disturbance-rejection acceptance before this is complete.
If any step fails, stop at that stage and investigate its cause. Do not manufacture a pass by loosening handoff gates, lowering expected WKC or extending the balance criterion.
Engineering checks and optimization points
| Item | Example implementation and revalidation focus |
|---|---|
| Handoff hard gates | Keep ` |
| R22 additive recentering | Add the recentering rate to the balance reference rate and yield on instability or a freeze. Check that referenceRate, uCmdEff and measured φ remain controlled in the same direction |
| Fault order | Publish Fault before disabling. Check that both the fault event and final 0x6040 readback are available |
| Observer input | Use measured arm acceleration so an unexecuted command is not mistaken for an external disturbance. Pay particular attention to dConf and feedforward withdrawal during saturation |
| Reference-rate anti-windup | Check that the rate integrator, position-lead clamp and final applied rate agree, so reversing direction does not first spend old integral debt |
| Core / SDK version consistency | Check version consistency through the companion-component allowlist. Upgrade the complete set rather than mixing files from different generations |
| Multilingual i18n | Maintain Chinese and English resources together when adding UI or documentation text. Other languages use the site's existing fallback for missing translations; do not mix languages within half a page |
Handoff gates, R22 recentering, fault ordering and reference anti-windup are already connected in the example code. Current acceptance result: both 1 ms and 500 µs PASS, and 500 µs is the highest verified stable frequency; 250 µs did not pass and is outside the current EZI drive + control envelope (FollowingError / BalanceLost, max|φ̇|=16.14, aCmd800). The 0.065 disturbance test at 500 µs resulted in FAIL (ThetaOverrun), and the observer is off by default. Disturbance rejection under external contact still requires the separate acceptance steps above; the presence of code does not establish an on-machine result.
Complete source code
- Project repository: Windows-FurutaPendulum
- PDO definitions:
Control/PdoStructs.cs - Cyclic execution and application settings:
Control/ControlThread.cs,Control/SoftRealTime.cs - Swing-up and handoff:
Control/SwingUpController.cs - Balancing, recentering and faults:
Control/PendulumEngine.cs - Disturbance observation:
Control/DisturbanceObserver.cs - CLI commands:
Cli/CliSession.Commands.cs
Independent hardwired emergency stop, STO, mechanical limits and a cleared work area are still required for on-machine operation. Software stop and fault interlocks in this example do not replace the safety circuit.