C# WinForm中连接NI采集卡
1.1安装NI-DAQmx和新建仿真设备

1.2采集电压的代码框架
NI-DAQmx对于Microsoft .NetFramework平台,提供了NationalInstruments.Common.dll和NationalInstruments.DAQmx.dll两个动态链接库,作为第三方使用NI-DAQmx控制National Instruments DAQ设备的应用程序接口。其中NationalInstruments.Common.dll动态库位于C:\Program Files (x86)\National Instruments\Measurement Studio\DotNET\v4.0\AnyCPU\NationalInstruments.Common 19.0.40\NationalInstruments.Common.dll
NationalInstruments.DAQmx.dll动态库位于C:\Program Files (x86)\National Instruments\MeasurementStudioVS2012\DotNET\Assemblies (64-bit)\Current\NationalInstruments.DAQmx.dll。
private static AnalogMultiChannelReader reader;
private static NationalInstruments.AnalogWaveform
private NationalInstruments.DAQmx.Task mytask;
///
/// 开始数据采集
///
private void StartDataCollection()
{
lock (collectionLock)
{
try
{
cancellationTokenSource = new CancellationTokenSource();
mytask = new NationalInstruments.DAQmx.Task();
mytask.AIChannels.CreateVoltageChannel(
"Dev1/ai1,Dev1/ai3,Dev1/ai5,Dev1/ai7", //物理通道名称
"", //虚拟通道名称
AITerminalConfiguration.Rse, //输入配置:RSE
-10, 10, //测量范围(-10V--10V)
AIVoltageUnits.Volts //电压单位:伏特
);
mytask.Timing.ConfigureSampleClock(
"", //时针源(空字符串使用内部时针)
2000, //采样率 2kHZ
SampleClockActiveEdge.Rising, //采样时钟边沿
SampleQuantityMode.ContinuousSamples, //采样模式 ContinuousSamples:连续采样 FiniteSamples:有限模式
SAMPLES_PER_READ //每次读取的样本数
);
mytask.Control(TaskAction.Verify);
reader = new AnalogMultiChannelReader(mytask.Stream);
isCollecting = true;
// 使用异步任务替代Timer
System.Threading.Tasks.Task.Run(() => DataCollectionLoop(cancellationTokenSource.Token));
}
catch (DaqException exception)
{
BoxLogHelper.WriteLog($"初始化采集卡失败: " + exception.Message);
MessageBox.Show("初始化采集卡失败: " + exception.Message);
isCollecting = false;
cancellationTokenSource?.Dispose();
}
catch (Exception ex)
{
BoxLogHelper.WriteLog($"初始化错误: " + ex.Message);
MessageBox.Show("初始化失败: " + ex.Message);
isCollecting = false;
cancellationTokenSource?.Dispose();
}
}
}
///
/// 数据采集循环
///
///
///
private async System.Threading.Tasks.Task DataCollectionLoop(CancellationToken cancellationToken)
{
while (isCollecting && !cancellationToken.IsCancellationRequested)
{
try
{
await System.Threading.Tasks.Task.Delay(50, cancellationToken); // 替代Timer的延迟
if (!isCollecting || cancellationToken.IsCancellationRequested)
break;
//ReadAndProcessData();
// 使用异步读取方式
await System.Threading.Tasks.Task.Run(() => ReadAndProcessData(), cancellationToken);
}
catch (TaskCanceledException)
{
// 正常取消,忽略
break;
}
catch (Exception ex)
{
if (!cancellationToken.IsCancellationRequested)
{
BoxLogHelper.WriteLog($"数据采集循环错误: {ex.Message}");
}
break;
}
}
}
///
/// 分离数据读取和处理逻辑
///
private void ReadAndProcessData()
{
if (!isCollecting) return;
try
{
data = reader.ReadWaveform(SAMPLES_PER_READ);
WriteDataToFile(data);
}
catch (DaqException exception)
{
HandleDaqException(exception);
}
catch (Exception ex)
{
BoxLogHelper.WriteLog($"读取数据处理错误: {ex.Message}");
}
}

浙公网安备 33010602011771号