Real-time remote sensor data acquisition
This page covers IO / weighing data acquisition only. It does not cover servo enable, CSP/CSV or synchronized axes, and contains no motion control code.
Hardware configuration
- Master: Windows 10 × 1 + Intel i3 × 1
- Weighing transmitter: EtherCAT weighing module × 15 (spread across different silos in the plant)
- Network topology: daisy chain, branchable, up to 80 m between nodes
Cost analysis
| Category | Model/spec | Reference unit price (¥) | Qty | Subtotal (¥) |
|---|---|---|---|---|
| Weighing transmitter | EtherCAT weighing module | 600 | 15 | 9,000 |
| Industrial PC | Intel i3 class | 2,500 | 1 | 2,500 |
| Total for the line (reference) | ≈ ¥11,500 |
Reference prices (RMB) for the core components; load cells, cables and similar are not included.
Performance figures
- Sampling cycle: 250 µs
- Weighing accuracy: ±0.1%
- Transmission distance: up to 80 m between nodes
- Acquisition channels: 15 (4 channels per module; this example uses only 1 channel)
Application scenario
Chemical raw material silo management system.
15 weighing transmitters are spread across different silos in the plant (up to 80 m between nodes); the master collects weight data in real time on a 250 µs cycle.
This example is the data acquisition layer: an external system reads the Weights[] property directly to obtain real-time weights, and implements inventory monitoring, automatic replenishment, limit alarms and similar business logic on that basis.
In practice, acquisition is usually driven by the system at high speed.
It also applies to high-speed synchronized acquisition of multi-point temperature / pressure / flow sensors.
Code example
PDO struct definition (4-channel module; this example uses 1 channel)
using System.Runtime.InteropServices;
/// <summary>
/// 4-channel weighing transmitter input PDO (0x6000)
/// Each subindex is one channel's weight value, read-only
/// This example uses W1 only (1 channel)
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct WeighingModule_Input // 4 channels, 16 bytes in total
{
public int W1; // 0x6000:01 - channel 1 weight value (offset 0, used by this example)
public int W2; // 0x6000:02 - channel 2 weight value (offset 4)
public int W3; // 0x6000:03 - channel 3 weight value (offset 8)
public int W4; // 0x6000:04 - channel 4 weight value (offset 12)
}
/// <summary>
/// 4-channel weighing transmitter output PDO (0x7000)
/// Calibration commands: write 1 = zero, 4 = clear, 16 = confirm calibration without a weight, write >100 = calibrate gain
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct WeighingModule_Output // 24 bytes
{
public int Calibration1; // 0x7000:01 - channel 1 calibration (offset 0)
public int Calibration2; // 0x7000:02 - channel 2 calibration (offset 4)
public int Calibration3; // 0x7000:03 - channel 3 calibration (offset 8)
public int Calibration4; // 0x7000:04 - channel 4 calibration (offset 12)
public int FullScale; // 0x7000:05 - full scale (offset 16)
public int Sensitivity; // 0x7000:06 - sensitivity (offset 20, actual value x10000, e.g. write 20000 for 2.0 mV/V)
}
The struct lays out the fields in the order of the module's ESI default mapping of 0x1A00 / 0x1600 (4 input channels, 16 bytes in total, at offsets 0 / 4 / 8 / 12).
If the module maps only 0x6000:01 (4 bytes), shorten the struct accordingly — InputsMapping<T>() throws "struct larger than input PDO" when T is larger than the input process image. Take the mapping from the actual assignment exported by DENI.
Control code
using System;
using System.Runtime.InteropServices;
using DarraEtherCAT_Master;
class WeighingController
{
// ============ Configurable parameters (set externally) ============
/// <summary> Number of weighing modules </summary>
public static int ModuleCount { get; set; } = 15;
// ============ Acquired data (read directly by external systems) ============
/// <summary>
/// Live weight of every bin (only W1 is used per module); external systems access this property directly
/// </summary>
public static int[] Weights { get; set; } = new int[15];
/// <summary>
/// Sample counter; external systems can tell from it whether the data has refreshed
/// </summary>
public static volatile long SampleCount;
static void Main(string[] args)
{
// Build() returns a BuildResult (not the master itself); you must call .Master to get the master instance
var master = new DarraEtherCAT()
.SetENI("config.deni")
.Build()
.Master;
if (master == null)
{
Console.WriteLine("主站初始化失败!"); // Master initialization failed!
return;
}
try
{
// 1. Set the cycle time first and read it back to verify (unit ns); refuse to start if the readback does not match
const uint CYCLE_NS = 250_000; // 250 µs
master.LoopCycle = CYCLE_NS;
if (master.LoopCycle != CYCLE_NS)
{
Console.WriteLine($"LoopCycle 读回 {master.LoopCycle}ns ≠ {CYCLE_NS}ns"); // LoopCycle read back {master.LoopCycle}ns ≠ {CYCLE_NS}ns
return;
}
if (!master.SetState(EcState.OP, out string opError))
{
Console.WriteLine($"无法进入 OP 状态: {opError}"); // Failed to enter the OP state: {opError}
return;
}
int slaveCount = Math.Min(ModuleCount, master.SlaveCount);
if (slaveCount <= 0)
{
Console.WriteLine("没有在线称重模块"); // No weighing module online
return;
}
Weights = new int[ModuleCount]; // Modules that are not online stay at 0
Console.WriteLine($"传感器采集启动! 在线模块: {slaveCount}/{ModuleCount}"); // Sensor acquisition started! Modules online: {slaveCount}/{ModuleCount}
// 2. Take the process image pointer once outside the callback (InputsPtr / ProcessImageGeneration both live on Slave,
// not on slave.PDO). The pointer is valid until Close / a process image generation change; re-fetch when the generation number changes.
IntPtr[] inputPtrs = new IntPtr[slaveCount];
ulong[] inputGens = new ulong[slaveCount];
for (int i = 0; i < slaveCount; i++)
{
inputPtrs[i] = master.Slaves[i].InputsPtr;
inputGens[i] = master.Slaves[i].ProcessImageGeneration;
}
// 3. Sampling hangs off the bus cycle callback: read the process image once per cycle instead of spinning in user space to set the pace
void OnPdoCycle(ushort masterIndex)
{
var m = master;
if (m == null) return;
for (int i = 0; i < inputPtrs.Length; i++)
{
var slave = m.Slaves[i];
if (slave.ProcessImageGeneration != inputGens[i])
{
inputPtrs[i] = slave.InputsPtr; // Process image generation changed, the old pointer is void
inputGens[i] = slave.ProcessImageGeneration;
}
// W1 is at process image input offset 0 (W2 / W3 / W4 follow at 4 / 8 / 12)
Weights[i] = Marshal.ReadInt32(inputPtrs[i], 0);
}
SampleCount++;
}
master.Events.ProcessDataCyclicSync += OnPdoCycle;
Console.WriteLine("采集中, 按 Enter 停止"); // Acquiring, press Enter to stop
Console.ReadLine();
master.Events.ProcessDataCyclicSync -= OnPdoCycle;
}
finally
{
master.Dispose();
}
}
// ============ Interface called by external systems ============
/// <summary>
/// Get the weight of a specific bin (called directly by external systems)
/// </summary>
public static int GetWeight(int moduleIndex) => Weights[moduleIndex];
// ============ Calibration procedure ============
//
// Calibration with a weight (recommended):
// 1. No load -> TareZero() zero
// 2. Place a known weight -> CalibrateGain(weight value) calibrate the gain
//
// Calibration without a weight:
// 1. SetCalibrationParams(sensitivity, full scale) write the sensor parameters
// 2. No load -> TareZero() zero
// 3. ConfirmNoWeightCalibration() confirm calibration without a weight
/// <summary>
/// Step 1: zero with no load (call with nothing on the scale)
/// </summary>
public static void TareZero(DarraEtherCAT master, int moduleIndex)
{
ref var output = ref master.Slaves[moduleIndex].PDO.OutputsMapping<WeighingModule_Output>();
output.Calibration1 = 1; // 1=zero
}
/// <summary>
/// Step 2: place a known weight and calibrate the gain (write the actual weight value, must be >100)
/// </summary>
/// <param name="knownWeight">calibration weight value (must be >100, e.g. write 5000 for 5000 g)</param>
public static void CalibrateGain(DarraEtherCAT master, int moduleIndex, int knownWeight)
{
ref var output = ref master.Slaves[moduleIndex].PDO.OutputsMapping<WeighingModule_Output>();
output.Calibration1 = knownWeight; // >100=calibrate gain
}
/// <summary>
/// Calibration without a weight: write the sensor parameters (call before zeroing)
/// </summary>
/// <param name="sensitivity">sensor sensitivity (actual value x10000, e.g. write 20000 for 2.0 mV/V)</param>
/// <param name="fullScale">full-scale value</param>
public static void SetCalibrationParams(DarraEtherCAT master, int moduleIndex, int sensitivity, int fullScale)
{
ref var output = ref master.Slaves[moduleIndex].PDO.OutputsMapping<WeighingModule_Output>();
output.Sensitivity = sensitivity;
output.FullScale = fullScale;
}
/// <summary>
/// Calibration without a weight: confirm (call after zeroing)
/// </summary>
public static void ConfirmNoWeightCalibration(DarraEtherCAT master, int moduleIndex)
{
ref var output = ref master.Slaves[moduleIndex].PDO.OutputsMapping<WeighingModule_Output>();
output.Calibration1 = 16; // 16=confirm calibration without a weight
}
}
InputsPtr / ProcessImageGeneration are both on Slave (not on slave.PDO). For low-frequency reads you can also take the read-only struct directly with slave.PDO.InputsMapping<WeighingModule_Input>(); the high-frequency version above takes the pointer once outside the callback and re-takes it when the generation number changes, so each cycle performs a single pointer dereference instead of a mapping lookup inside the callback.
Pure acquisition does not require Distributed Clocks (DC): this page only reads the process image on the bus cycle. If several modules must share one time base, call slave.ConfigureDC(CYCLE_NS) on the modules that support DC during the PreOp stage (the cycle time equal to LoopCycle), that is, the step-by-step sequence SetState(PreOp) → ConfigureDC → SetState(OP).
Complete example code
This page is a scenario description; for runnable reference code see FurutaPendulum: a compilable project that likewise uses "a non-servo IO module (counter module) plus a 500 µs cyclic callback reading the process image" — replace the counter slice with the weighing module's W1. The weighing calibration flow and the silo business logic are specific to this page's scenario, and the reference project contains no corresponding implementation.