Skip to main content

Stepper motor control in WinForm: 2 modes

Single-axis commissioning example

This page is a single-axis commissioning example, not a synchronized-axis or electronic-gearing use case: it only keeps one stepper drive running smoothly at its own cadence, and involves no virtual master axis, gear-ratio following or multi-axis coupling. For strict multi-axis coupling, see Synchronized axes / electronic gearing.

Hardware configuration​

  • Master: Windows 10 × 1 + Intel i5 × 1
  • Stepper drive: FASTECH Ezi-SERVO2 EtherCAT stepper drive × 1 + 57 stepper motor × 1

Performance figures​

  • Control modes: position mode (CSP) / velocity mode (CSV)
  • Velocity range: 0 ~ 3000 RPM
  • Position accuracy: ±1 pulse
  • Bus cycle: 500 µs (default); 1 ms also works for single-axis commissioning

Application scenario​

A WinForm UI controls a single-axis stepper motor and switches between CSP position mode and CSV velocity mode. Motion is timed only by the PDO cyclic callback (500 µs by default, DC Sync0 equal to the bus cycle); a background thread at 20 Hz only refreshes the UI. This suits commissioning verification and first steps.

Code example​

PDO structure definitions​

using System.Runtime.InteropServices;

/// <summary>
/// FASTECH Ezi-SERVO2 stepper drive input PDO (custom CSP/CSV mapping on this page, 10 bytes)
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct Stepper_Input
{
public ushort StatusWord; // 0x6041 status word offset 0
public int ActualPosition; // 0x6064 actual position offset 2
public int ActualVelocity; // 0x606C actual velocity offset 6 (pulses/s)
}

/// <summary>
/// FASTECH Ezi-SERVO2 stepper drive output PDO (custom CSP/CSV mapping on this page, 11 bytes)
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct Stepper_Output
{
public ushort ControlWord; // 0x6040 control word offset 0
public sbyte ModesOfOperation; // 0x6060 mode of operation offset 2 (8=CSP, 9=CSV)
public int TargetPosition; // 0x607A target position offset 3 (pulses)
public int TargetVelocity; // 0x60FF target velocity offset 7 (pulses/s)
}
PDO mapping

The structs above must match the ESI / DENI mapping of the actual device byte for byte; do not assume the field order from the CiA 402 object numbers.

Ezi-SERVO2 factory defaults:

  • CSP: RxPDO 0x1600 (0x6040, 0x607A, 0x60FE:01, 0x60B8) / TxPDO 0x1A00 (0x6041, 0x6064, 0x60FD, 0x603F, 0x60B9, 0x60BA, 0x60BC)
  • PP: RxPDO 0x1601 (0x6040, 0x607A, 0x6081, 0x6060) / TxPDO 0x1A01 (0x6041, 0x6064, 0x606C, 0x60FD, 0x603F, 0x6061)

The CSP / CSV dual mode on this page shares one RxPDO (it contains both 0x6060 and 0x60FF), and the input side also reads 0x606C, so this is a custom mapping: first confirm in the DENI which entries the slave actually allocates, then rewrite the structs above in that entry order. 0x1C12 / 0x1C13 are only for checking that the device allocation matches the ESI; do not write them blindly; if the process image size or order does not match, export config.deni again from the master GUI; do not run with a close-enough mapping.

If you use the factory CSP mapping directly, cut Stepper_Input down to the two fields StatusWord + ActualPosition (the last 4 bytes are 0x60FD, not velocity) and compute velocity from the position difference.

Complete WinForm control code​

using System;
using System.Threading;
using System.Windows.Forms;
using DarraEtherCAT_Master;

namespace StepperControl
{
public partial class MainForm : Form
{
DarraEtherCAT master;
bool isRunning = false;

// ==================== Motion request (UI thread write-only, PDO callback read-only) ====================
// The motion tick has exactly one source: the PDO cycle callback. The UI never writes the control word/target position directly.
volatile bool enableRequested;
volatile bool faultResetRequested;
volatile sbyte modeRequest = MODE_CSP;
volatile int targetRequest; // Target position (pulses)
volatile int velocityRequest; // Target velocity (pulses/s)

// Only the PDO callback thread may touch it: counts the fault reset bit7 rising edge; the UI only sets faultResetRequested to true
int faultResetTicks;

// Slave index
const int SLAVE_STEPPER = 0;

// Mode of operation constants
const sbyte MODE_CSP = 8; // Cyclic synchronous position mode
const sbyte MODE_CSV = 9; // Cyclic synchronous velocity mode

// Motor parameters
int _ppr = 0; // Pulses per revolution: read at connect time over SDO (0x608F position encoder resolution + 0x6091 electronic gear ratio); 0 = CPR unknown, angle/velocity conversion only when _ppr > 0

public MainForm()
{
InitializeComponent();
}

/// <summary>
/// Connect button - set the cycle time and DC first, then enter OP; enable only sets a request, which the cycle callback advances
/// </summary>
void btnConnect_Click(object sender, EventArgs e)
{
const uint CYCLE_NS = 500_000; // 500 µs; for single-axis debugging 1_000_000 (1 ms) also works

var build = new DarraEtherCAT()
.SetENI("config.deni") // The DENI exported by the master GUI after scanning the real slaves
.EnableAutoStartup() // Auto-configure the slaves not covered by the DENI
.Build();

if (!build.Success)
{
MessageBox.Show($"主站初始化失败: {build.Message}"); // Master initialization failed: {build.Message}
return;
}
master = build.Master;
if (master == null)
{
MessageBox.Show("主站初始化失败: BuildResult.Master 为空"); // Master initialization failed: BuildResult.Master is null
return;
}
if (master.SlaveCount < 1)
{
MessageBox.Show("DENI 中没有从站"); // No slaves in the DENI
master.Dispose();
master = null;
return;
}

// The cycle time must be set before any state transition and read back to verify; refuse to enter the motion chain if the readback does not match
master.LoopCycle = CYCLE_NS;
if (master.LoopCycle != CYCLE_NS)
{
MessageBox.Show($"周期设定失败: 请求 {CYCLE_NS}ns, 读回 {master.LoopCycle}ns"); // Cycle time setup failed: {CYCLE_NS}ns requested, {master.LoopCycle}ns read back
master.Dispose();
master = null;
return;
}

var slave = master.Slaves[SLAVE_STEPPER];
if (!master.SetState(EcState.PreOp, out string preOpError))
{
MessageBox.Show($"无法进入 PreOp: {preOpError}"); // Failed to enter PreOp: {preOpError}
master.Dispose();
master = null;
return;
}

// DC Sync0 equals the bus cycle; lack of DC capability is reported honestly instead of pretending to be synchronised
if (slave.HasDC)
{
if (!slave.ConfigureDC(CYCLE_NS))
{
MessageBox.Show($"DC Sync0({CYCLE_NS}ns) 配置失败 — CSP 依赖周期同步, 拒绝进入运动链路"); // DC Sync0({CYCLE_NS}ns) configuration failed — CSP depends on cyclic synchronization, refusing to enter the motion link
master.Dispose();
master = null;
return;
}
}
else
{
MessageBox.Show("该从站无 DC 能力, 未配置 Sync0: CSP 退化为 SM 事件同步, 同步精度下降"); // This slave has no DC capability and Sync0 was not configured: CSP degrades to SM event synchronization, synchronization accuracy reduced
}

if (!master.SetState(EcState.SafeOp, out string safeOpError))
{
MessageBox.Show($"无法进入 SafeOp: {safeOpError}"); // Failed to enter SafeOp: {safeOpError}
master.Dispose();
master = null;
return;
}

// Before entering OP, lay down one safety frame: CSP + target=actual + Shutdown, so the first enable does not jump from a 0 target
ref var output0 = ref master.Slaves[SLAVE_STEPPER].PDO.OutputsMapping<Stepper_Output>();
ref readonly var input0 = ref master.Slaves[SLAVE_STEPPER].PDO.InputsMapping<Stepper_Input>();
output0.ModesOfOperation = MODE_CSP;
output0.ControlWord = 0x0006; // Normal stop command (0x0000 is used only when leaving QuickStopActive)
output0.TargetPosition = input0.ActualPosition; // Target = actual
output0.TargetVelocity = 0;

// Anchor the CSP target to the current actual position: after enabling, it will not yank because targetRequest is still the default 0
targetRequest = input0.ActualPosition;
velocityRequest = 0;

if (!master.SetState(EcState.OP, out string opError))
{
MessageBox.Show($"无法进入 OP 状态: {opError}"); // Failed to enter the OP state: {opError}
master.Dispose();
master = null;
return;
}

// Motion pacing: the PDO cycle callback (not the UI thread, not a Sleep thread)
master.Events.ProcessDataCyclicSync += OnPdoCycle;

// The UI only sets the enable request; the callback advances 0x06 -> 0x07 -> 0x0F from the status word
enableRequested = true;

// The status refresh thread only reads the status word/position
isRunning = true;
new Thread(StatusUpdateLoop) { IsBackground = true }.Start();

btnConnect.Enabled = false;
grpPosition.Enabled = true;
grpVelocity.Enabled = true;
lblStatus.Text = "已连接"; // Connected
}

/// <summary>
/// PDO cycle callback (default 500 µs): CiA402 state machine + target command, the single motion tick
/// </summary>
void OnPdoCycle(ushort masterIndex)
{
if (master == null) return;

ref readonly var input = ref master.Slaves[SLAVE_STEPPER].PDO.InputsMapping<Stepper_Input>();
ref var output = ref master.Slaves[SLAVE_STEPPER].PDO.OutputsMapping<Stepper_Output>();

ushort sw = input.StatusWord;
bool opEnabled = (sw & 0x6F) == 0x27; // OperationEnabled; do not use 0x4F to test for the running state
bool fault = (sw & 0x4F) == 0x08; // 0x4F is used for the fault state

output.ModesOfOperation = modeRequest;

// Note: the CSP targetRequest is given explicitly by the UI buttons (move / home); there is no "auto-align on mode switch" here,
// Otherwise it would overwrite the homing / positioning target the user just issued with the current position.

// 1. Fault reset: bit7 must be a clean rising edge. Use 0x0006 for the low phase, 0x0086 for the high phase;
// 0x0000 (Disable Voltage) / 0x0080 (bit2 is active low and would hold QuickStop) are not written here.
// The one exception is QuickStopActive: that state can only be left with 0x0000, handled uniformly by NextEnableCommand.
if (faultResetRequested && fault)
{
faultResetTicks++;
output.ControlWord = ((faultResetTicks / 400) % 2 == 0) ? (ushort)0x0086 : (ushort)0x0006;
output.TargetPosition = input.ActualPosition;
output.TargetVelocity = 0;
return;
}
faultResetRequested = false;
faultResetTicks = 0;

// 2. Not enabled / faulted / handshake incomplete: target=actual, velocity=0, send only the stop command
if (!enableRequested || fault || !opEnabled)
{
output.ControlWord = NextEnableCommand(sw, enableRequested && !fault);
output.TargetPosition = input.ActualPosition;
output.TargetVelocity = 0;
return;
}

// 3. Only OperationEnabled may write targets/velocities
output.ControlWord = 0x000F; // CSP keeps 0x000F, never 0x001F
if (modeRequest == MODE_CSP)
{
// targetRequest is anchored to the actual position at connect time and is only written explicitly by UI buttons afterwards;
// The callback must not rewrite it any more, otherwise it would overwrite the positioning / homing target the user just issued.
output.TargetPosition = targetRequest;
output.TargetVelocity = 0;
}
else
{
output.TargetPosition = input.ActualPosition;
output.TargetVelocity = velocityRequest;
}
}

/// <summary>
/// Advance the CiA402 enable from the status word: 0x06 -> 0x07 -> 0x0F
/// </summary>
static ushort NextEnableCommand(ushort sw, bool enable)
{
if ((sw & 0x6F) == 0x07) return 0x0000; // QuickStopActive: only exit = Disable Voltage (T12)
if (!enable) return 0x0006; // Shutdown
if ((sw & 0x4F) == 0x40) return 0x0006; // SwitchOnDisabled
if ((sw & 0x6F) == 0x21) return 0x0007; // ReadyToSwitchOn
if ((sw & 0x6F) == 0x23) return 0x000F; // SwitchedOn
if ((sw & 0x6F) == 0x27) return 0x000F; // OperationEnabled
return 0x0006; // NotReady / FaultReaction
}

/// <summary>
/// Stop control word: QuickStopActive can only be left with 0x0000 (T12); every other state sends 0x0006 (Shutdown)
/// </summary>
static ushort StopControlWord(ushort sw)
=> (sw & 0x6F) == 0x07 ? (ushort)0x0000 : (ushort)0x0006;

// ==================== Position mode ====================

/// <summary>
/// Position mode - run to the target position (only sets the request; the cycle callback sends it when OperationEnabled)
/// </summary>
void btnMoveToPosition_Click(object sender, EventArgs e)
{
targetRequest = (int)((double)numTargetPosition.Value * _ppr / 360.0);
modeRequest = MODE_CSP;
}

/// <summary>
/// Position mode - homing
/// </summary>
void btnHome_Click(object sender, EventArgs e)
{
targetRequest = 0;
modeRequest = MODE_CSP;
}

// ==================== Velocity mode ====================

/// <summary>
/// Velocity mode - start
/// </summary>
void btnStartVelocity_Click(object sender, EventArgs e)
{
int rpm = (int)numTargetRPM.Value;
int velocityPulses = rpm * _ppr / 60; // Convert to pulses/s

// Invert
if (chkReverse.Checked)
velocityPulses = -velocityPulses;

velocityRequest = velocityPulses;
modeRequest = MODE_CSV;
}

/// <summary>
/// Velocity mode - stop
/// </summary>
void btnStopVelocity_Click(object sender, EventArgs e)
{
velocityRequest = 0; // When disabled the callback already forces 0, so this only withdraws the request
}

// ==================== Status refresh ====================

/// <summary>
/// Background thread refreshing motor state to the UI (read-only, not a motion cycle)
/// </summary>
void StatusUpdateLoop()
{
// The mapping only needs to be fetched once; it points into shared PDO memory, so just read it directly in the loop
ref readonly var input = ref master.Slaves[SLAVE_STEPPER].PDO.InputsMapping<Stepper_Input>();

while (isRunning)
{
double positionDeg = input.ActualPosition * 360.0 / _ppr;
double velocityRPM = input.ActualVelocity * 60.0 / _ppr;
ushort sw = input.StatusWord;

// 20 Hz is UI refresh only, not a motion cycle; the motion tick lives in the PDO callback
Invoke(new Action(() =>
{
lblActualPosition.Text = $"{positionDeg:F2}°";
lblActualVelocity.Text = $"{velocityRPM:F1} RPM";
lblStatusWord.Text = $"0x{sw:X4} {DescribeState(sw)}";
}));

Thread.Sleep(50); // 20 Hz UI refresh
}
}

/// <summary>
/// Status word interpretation: 0x6F for the running state, 0x4F for fault/not ready
/// </summary>
static string DescribeState(ushort sw)
{
if ((sw & 0x4F) == 0x00) return "NotReady";
if ((sw & 0x4F) == 0x40) return "SwitchOnDisabled";
if ((sw & 0x6F) == 0x21) return "ReadyToSwitchOn";
if ((sw & 0x6F) == 0x23) return "SwitchedOn";
if ((sw & 0x6F) == 0x27) return "OperationEnabled";
if ((sw & 0x6F) == 0x07) return "QuickStopActive";
if ((sw & 0x4F) == 0x0F) return "FaultReaction";
if ((sw & 0x4F) == 0x08) return "Fault";
return "Unknown";
}

/// <summary>
/// Release resources when the form closes
/// </summary>
protected override void OnFormClosing(FormClosingEventArgs e)
{
isRunning = false;

if (master != null)
{
// Withdraw the enable request first: the callback keeps sending 0x0006 and the status word confirms that OperationEnabled really left
enableRequested = false;

// The wait on the cold path after closing the window is only to confirm the state read-back; it is not part of the motion tick
var deadline = DateTime.UtcNow.AddSeconds(1);
while (DateTime.UtcNow < deadline &&
(master.Slaves[SLAVE_STEPPER].PDO.InputsMapping<Stepper_Input>().StatusWord & 0x6F) == 0x27)
{
Thread.Sleep(10);
}

master.Events.ProcessDataCyclicSync -= OnPdoCycle;

// After detaching the callback, send one explicit stop frame (the PDO thread is still running, so this frame really goes out):
// target=actual, velocity=0; leave QuickStopActive with 0x0000, every other state with 0x0006
{
ref readonly var lastIn = ref master.Slaves[SLAVE_STEPPER].PDO.InputsMapping<Stepper_Input>();
ref var lastOut = ref master.Slaves[SLAVE_STEPPER].PDO.OutputsMapping<Stepper_Output>();
lastOut.TargetPosition = lastIn.ActualPosition;
lastOut.TargetVelocity = 0;
lastOut.ControlWord = StopControlWord(lastIn.StatusWord);
}

master.Dispose();
}

base.OnFormClosing(e);
}
}
}

Complete example code​

This page describes the scenario. For a runnable reference, see Ezi-SERVO2_CSP_PP: a single-axis project for the same FASTECH stepper drive, WinForms UI, CSP / PP dual mode, with a real PDO mapping, the CiA 402 state machine and fault reset. For a multi-axis version, see STF-EC_CSP_PP (the number of axes is determined by the config.deni scan result).