public string[] ReadDITasks() { List <string> tasklist = new List <string>(); foreach (string s in DaqSystem.Local.Tasks) { try { using (NationalInstruments.DAQmx.Task t = DaqSystem.Local.LoadTask(s)) { t.Control(TaskAction.Verify); if (t.DIChannels.Count > 0 && t.Timing.SampleTimingType == SampleTimingType.OnDemand) { tasklist.Add(s); } } } catch (DaqException) { } } string[] tasks = tasklist.ToArray(); return(tasks); }
public void startTempReading(tempCallback itcb) { try { tcb = itcb; myTask = new NationalInstruments.DAQmx.Task(); AIChannel channel1; AIChannel channel2; AIThermocoupleType thermocoupleType; thermocoupleType = AIThermocoupleType.K; string[] channellist = DaqSystem.Local.GetPhysicalChannels(PhysicalChannelTypes.AI, PhysicalChannelAccess.External); channel1 = myTask.AIChannels.CreateThermocoupleChannel(channellist[1], "", 0, 1000, thermocoupleType, AITemperatureUnits.DegreesC); channel2 = myTask.AIChannels.CreateThermocoupleChannel(channellist[3], "", 0, 1000, thermocoupleType, AITemperatureUnits.DegreesC); channel1.AutoZeroMode = AIAutoZeroMode.Once; channel2.AutoZeroMode = AIAutoZeroMode.Once; /* if (scxiModuleCheckBox.Checked) * { * switch (autoZeroModeComboBox.SelectedIndex) * { * case 0: * autoZeroMode = AIAutoZeroMode.None; * break; * case 1: * default: * autoZeroMode = AIAutoZeroMode.Once; * break; * } * myChannel.AutoZeroMode = autoZeroMode; * }*/ myTask.Timing.ConfigureSampleClock("", 4, SampleClockActiveEdge.Rising, SampleQuantityMode.ContinuousSamples, 1000); myTask.Control(TaskAction.Verify); analogInReader = new AnalogMultiChannelReader(myTask.Stream); runningTask = myTask; //InitializeDataTable(myTask.AIChannels, ref dataTable); //acquisitionDataGrid.DataSource = dataTable; // Use SynchronizeCallbacks to specify that the object // marshals callbacks across threads appropriately. analogInReader.SynchronizeCallbacks = true; analogInReader.BeginReadWaveform(10, myAsyncCallback, myTask); } catch (DaqException exception) { //MessageBox.Show(exception.Message); myTask.Dispose(); runningTask = null; } }
/// <summary> /// 启动AI采集任务 /// </summary> public void TryArmTask() { if (AIState != Status.Idle) { throw new Exception("If you want to arm, the AI state must be 'Idle'!"); } else { if (aiTask == null) { try { hasFinishFlag = false; //新建任务 aiTask = new NationalInstruments.DAQmx.Task(); //aiTask.Stream.ReadAutoStart = true; //配置任务 NIAIConfigMapper.MapAndConfigAll(aiTask, _staticConfig); //获取并设置通道数 _staticConfig.ChannelCount = aiTask.AIChannels.Count; //使用NI Task中的EveryNSamplesRead事件读取数据 aiTask.EveryNSamplesReadEventInterval = _staticConfig.ClockConfig.ReadSamplePerTime; aiTask.EveryNSamplesRead += AiTask_EveryNSamplesRead; //计算读取次数 times = 0; totalTimes = _staticConfig.ClockConfig.TotalSampleLengthPerChannel / _staticConfig.ClockConfig.ReadSamplePerTime; //Verify the Task aiTask.Control(TaskAction.Verify); //read stream //使用reader读数据 reader = new AnalogMultiChannelReader(aiTask.Stream); aiTask.SynchronizeCallbacks = true; //开始任务 aiTask.Start(); //idle -> ready AIState = Status.Ready; } catch (DaqException ex) { //ex.Message goError(); throw ex; } } } }
private void btnStart_Click(object sender, RoutedEventArgs e) { Mouse.OverrideCursor = Cursors.Wait; try { // create the task and channel myTask.AOChannels.CreateVoltageChannel(physicalChannelComboBox.Text, "", Convert.ToDouble(minimumTextBox.Text), Convert.ToDouble(maximumTextBox.Text), ni.AOVoltageUnits.Volts); // verify the task before doing the waveform calculations myTask.Control(ni.TaskAction.Verify); // calculate some waveform parameters and generate data FunctionGenerator fGen = new FunctionGenerator( myTask.Timing, edfrequency.Text, edsamplesPerBuffer.Text, edcyclesPerBuffer.Text, signalTypeComboBox.Text, edamplitude.Text); // configure the sample clock with the calculated rate myTask.Timing.ConfigureSampleClock("", fGen.ResultingSampleClockRate, ni.SampleClockActiveEdge.Rising, ni.SampleQuantityMode.ContinuousSamples, 1000); ni.AnalogSingleChannelWriter writer = new ni.AnalogSingleChannelWriter(myTask.Stream); //write data to buffer writer.WriteMultiSample(false, fGen.Data); profilechart.SetData(fGen.Data); //start writing out data myTask.Start(); btnStart.IsEnabled = false; btnStop.IsEnabled = true; timer.IsEnabled = true; } catch (ni.DaqException err) { timer.IsEnabled = false; MessageBox.Show(err.Message); myTask.Dispose(); } Mouse.OverrideCursor = Cursors.Arrow; }
public void RunDAQ() { DigitalEdgeStartTriggerEdge triggerEdge = DigitalEdgeStartTriggerEdge.Rising; try { string s = string.Empty; s = _name == "/ai1" ? "etalon" : "measured"; inputTask = new NationalInstruments.DAQmx.Task(s); outputTask = new NationalInstruments.DAQmx.Task(s + "_output"); inputTask.AIChannels.CreateVoltageChannel(sInputName, "", AITerminalConfiguration.Pseudodifferential, inputDAQMinValue, inputDAQMaxValue, AIVoltageUnits.Volts); outputTask.AOChannels.CreateVoltageChannel(sOutputName, "", outputDAQMinValue, outputDAQMaxValue, AOVoltageUnits.Volts); inputTask.Timing.ConfigureSampleClock("", dRateIO, SampleClockActiveEdge.Rising, SampleQuantityMode.ContinuousSamples, iInputOutputSamples); outputTask.Timing.ConfigureSampleClock("", dRateIO, SampleClockActiveEdge.Rising, SampleQuantityMode.ContinuousSamples, iInputOutputSamples); outputTask.Triggers.StartTrigger.ConfigureDigitalEdgeTrigger(terminalNameBase + "ai/StartTrigger", triggerEdge); inputTask.Control(TaskAction.Verify); outputTask.Control(TaskAction.Verify); outputData = fGen.Data; writer = new AnalogSingleChannelWriter(outputTask.Stream); writer.WriteMultiSample(false, outputData); StartTask(); outputTask.Start(); inputTask.Start(); //inputCallback = new AsyncCallback(InputReady); reader = new AnalogSingleChannelReader(inputTask.Stream); //------------ТЕСТОВЫЙ КУСОК------------ ЧТЕНИЕ В ЭТОМ ЖЕ ПОТОКЕ-- double[] data = reader.ReadMultiSample(iInputOutputSamples); BufReadDAQReceived?.Invoke(data); StopTask(); //---------------------------------------------------------------- /*// Use SynchronizeCallbacks to specify that the object * // marshals callbacks across threads appropriately. * reader.SynchronizeCallbacks = bSynchronizeCallbacks; * * reader.BeginReadMultiSample(iInputOutputSamples, inputCallback, inputTask);*/ } catch (Exception ex) { StopTask(); WarningDAQUpdate?.Invoke(ex.Message); } }
public void StartDAQ(double a) { triggerSlope = AnalogEdgeStartTriggerSlope.Rising; sensitivityUnits = AIAccelerometerSensitivityUnits.MillivoltsPerG; terminalConfiguration = (AITerminalConfiguration)(-1); excitationSource = AIExcitationSource.Internal; inputCoupling = AICoupling.AC; myTask = new NationalInstruments.DAQmx.Task(); AIChannel aiChannel; SPmax = a; double Vmin = -5; double Vmax = 5; double sen = 100; double EVN = 0.004; double[] chan = new double[4] { 1, 1, 0, 0 }; //// indexP = 0; iii = 0; //// SW_RMSData = new StreamWriter(System.Environment.CurrentDirectory + "\\logData\\RMSData.txt"); SW_State = new StreamWriter(System.Environment.CurrentDirectory + "\\logData\\State.txt"); SW_State2 = new StreamWriter(System.Environment.CurrentDirectory + "\\logData\\State2.txt"); SW_RawData = new StreamWriter(System.Environment.CurrentDirectory + "\\logData\\RawData.txt"); for (int i = 0; i < chan.Length; i++) { if (chan[i] == 1) { aiChannel = myTask.AIChannels.CreateAccelerometerChannel("cDAQ1Mod1/ai" + Convert.ToString(i), "", terminalConfiguration, Vmin, Vmax, sen, sensitivityUnits, excitationSource, EVN, AIAccelerationUnits.G); aiChannel.Coupling = inputCoupling; } } myTask.Timing.ConfigureSampleClock("", Convert.ToDouble(12800), SampleClockActiveEdge.Rising, SampleQuantityMode.ContinuousSamples, Convert.ToInt32(1280)); myTask.Control(TaskAction.Verify); runningTask = myTask; analogInReader = new AnalogMultiChannelReader(myTask.Stream); analogCallback = new AsyncCallback(AnalogInCallback); analogInReader.SynchronizeCallbacks = true; analogInReader.BeginReadWaveform(Convert.ToInt32(1280), analogCallback, myTask); }
public static string GenerateWave(string sourceDevice = "Dev1", double freq = 100, double amp = 2, string waveType = "sine") { waveType = waveType.ToLower(); AOFunctionGenerationType type = AOFunctionGenerationType.Sine; //default value if (waveType.Equals("square")) { type = AOFunctionGenerationType.Square; } else if (waveType.Equals("triangle")) { type = AOFunctionGenerationType.Triangle; } NationalInstruments.DAQmx.Task myTask = new NationalInstruments.DAQmx.Task(); try { if (amp < 0) { amp *= -1; } if (amp > 5) { amp = 5; } myTask.AOChannels.CreateFunctionGenerationChannel(sourceDevice + "/fgen", "fgen", type, freq, //freq amp); //amplitude // verify the task before doing the waveform calculations myTask.Control(TaskAction.Verify); myTask.Stop(); myTask.AOChannels[0].FunctionGenerationType = type; myTask.AOChannels[0].FunctionGenerationFrequency = freq; myTask.AOChannels[0].FunctionGenerationAmplitude = amp; myTask.Start(); } catch (DaqException err) { myTask.Dispose(); return("Fail" + err.Message); } myTask.Dispose(); return("OK"); }
private void Button_Click(object sender, RoutedEventArgs e) { Start.IsEnabled = false; ni.Task myTask = new ni.Task(); try { // Create a new task // Initialize local variables double sampleRate = Convert.ToDouble(edRate.Text); double rangeMinimum = Convert.ToDouble(edMin.Text); double rangeMaximum = Convert.ToDouble(edMax.Text); int samplesPerChannel = Convert.ToInt32(edchannel.Text); // Create a channel myTask.AIChannels.CreateVoltageChannel(physicalChannelComboBox.Text, "", (ni.AITerminalConfiguration)(-1), rangeMinimum, rangeMaximum, ni.AIVoltageUnits.Volts); // Configure timing specs myTask.Timing.ConfigureSampleClock("", sampleRate, ni.SampleClockActiveEdge.Rising, ni.SampleQuantityMode.FiniteSamples, samplesPerChannel); // Verify the task myTask.Control(ni.TaskAction.Verify); // Prepare the table for data InitializeDataTable(myTask.AIChannels, ref dataTable); //acquisitionDataGrid.DataContext = dataTable.DefaultView; //acquisitionDataGrid.ItemsSource = dataTable.DefaultView; // Read the data reader = new ni.AnalogMultiChannelReader(myTask.Stream); data = reader.ReadWaveform(samplesPerChannel); dataToDataTable(data, ref dataTable); myTask.Dispose(); } catch (ni.DaqException exception) { MessageBox.Show(exception.Message); } finally { myTask.Dispose(); Start.IsEnabled = true; } }
public bool Analog_Connect(string DAQName, string channel) { IsConnect = false; try { IsDataGetCom = false; IsDataReadEnd = false; if (task != null) { task.Dispose(); task = null; } task = new NationalInstruments.DAQmx.Task(); task.AIChannels.CreateVoltageChannel(DAQName + "/" + channel, "", AITerminalConfiguration.Rse, 0, 5.0, AIVoltageUnits.Volts); Reader = new AnalogMultiChannelReader(task.Stream); //task.Timing.ConfigureSampleClock("", SampleRate, SampleClockActiveEdge.Rising, //SampleQuantityMode.FiniteSamples, iChPerSampleNum); task.Control(TaskAction.Verify); IsConnect = true; return(IsConnect); } catch (DaqException Exception) { if (task != null) { task.Dispose(); task = null; MessageBox.Show(Exception.Message); } return(IsConnect); } catch (Exception ex) { if (task != null) { task.Dispose(); task = null; } return(IsConnect); } }
private void BTN_Start_Click(object sender, EventArgs e) { if (runningTask == null) { try { BTN_Reset.Enabled = false; BTN_Start.Enabled = false; BTN_Open.Enabled = false; BTN_Data.Enabled = false; timer1.Interval = (Convert.ToInt32(Text_Time.Text) + 1) * 1000; timer1.Enabled = true; fs = File.Open(@"C:\Users\gy157\Documents\data.bin", FileMode.Create); wr = new BinaryWriter(fs); if (chart1.Series.Count > 0) { chart1.Series[0].Points.Clear(); } chart1.Series.Add("chart1"); chart1.Series["chart1"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line; chart1.Series["chart1"].IsVisibleInLegend = false; myTask = new NationalInstruments.DAQmx.Task(); samples = Convert.ToInt32(UpDown_Samples.Value); freq = Convert.ToDouble(UpDown_Freq.Value); myTask.AIChannels.CreateVoltageChannel("Dev1/ai3", "", (AITerminalConfiguration)(-1), -10, 10, AIVoltageUnits.Volts); myTask.Timing.ConfigureSampleClock("", freq, SampleClockActiveEdge.Rising, SampleQuantityMode.ContinuousSamples, samples); myTask.Control(TaskAction.Verify); runningTask = myTask; Reader = new AnalogMultiChannelReader(myTask.Stream); Callback = new AsyncCallback(AnalogCallback); Reader.SynchronizeCallbacks = true; Reader.BeginReadWaveform(samples, Callback, myTask); } catch (DaqException de) { MessageBox.Show(de.Message); runningTask = null; myTask.Dispose(); BTN_Reset.Enabled = false; BTN_Start.Enabled = true; } } }
/// <summary> /// Включение постоянной генерации сигнала. Чтение и контроль ошибок при этом производится в CALLBACK. Для завершения генерации используй метод StopDAQGeneration() /// </summary> public void RunDAQGeneration() { DigitalEdgeStartTriggerEdge triggerEdge = DigitalEdgeStartTriggerEdge.Rising; try { string s = string.Empty; s = _name == "/ai1" ? "etalon" : "measured"; inputTask = new NationalInstruments.DAQmx.Task(s); outputTask = new NationalInstruments.DAQmx.Task(s + "_output"); inputTask.AIChannels.CreateVoltageChannel(sInputName, "", AITerminalConfiguration.Pseudodifferential, inputDAQMinValue, inputDAQMaxValue, AIVoltageUnits.Volts); outputTask.AOChannels.CreateVoltageChannel(sOutputName, "", outputDAQMinValue, outputDAQMaxValue, AOVoltageUnits.Volts); inputTask.Timing.ConfigureSampleClock("", dRateIO, SampleClockActiveEdge.Rising, SampleQuantityMode.ContinuousSamples, iInputOutputSamples); outputTask.Timing.ConfigureSampleClock("", dRateIO, SampleClockActiveEdge.Rising, SampleQuantityMode.ContinuousSamples, iInputOutputSamples); outputTask.Triggers.StartTrigger.ConfigureDigitalEdgeTrigger(terminalNameBase + "ai/StartTrigger", triggerEdge); inputTask.Control(TaskAction.Verify); outputTask.Control(TaskAction.Verify); outputData = fGen.Data; writer = new AnalogSingleChannelWriter(outputTask.Stream); writer.WriteMultiSample(false, outputData); StartTask(); outputTask.Start(); //inputTask.Start(); inputCallback = new AsyncCallback(AnalogInCallback); reader = new AnalogSingleChannelReader(inputTask.Stream); reader.SynchronizeCallbacks = true; //reader.BeginReadMultiSample(iInputOutputSamples, inputCallback, inputTask); reader.BeginReadWaveform(iInputOutputSamples, inputCallback, inputTask); //statusDAQtimer.Enabled = true; } catch (Exception ex) { StopTask(); WarningDAQUpdate?.Invoke(ex.Message); } }
/// <summary> /// Indstiller DAQ til dataopsamling /// </summary> public void indstilDAQ() { try { analogInTask = new NationalInstruments.DAQmx.Task(); analogInTask.AIChannels.CreateVoltageChannel("Dev1/ai0", "myAIChannel", AITerminalConfiguration.Differential, 0, 5, AIVoltageUnits.Volts); analogInTask.Control(TaskAction.Verify); reader = new AnalogSingleChannelReader(analogInTask.Stream); } catch (Exception) { throw; } }
//아날로그 출력 연결 public void Connect_Output(ref string ErrorMsg) { try { Writetask.AOChannels.CreateVoltageChannel(ini.GetIniValue("NI", "Name") + "/ao0", "Analog Output", -10, 10, AOVoltageUnits.Volts); writer = new AnalogSingleChannelWriter(Writetask.Stream); Writetask.Control(TaskAction.Verify); } catch (DaqException de) { ErrorMsg = de.Message; } catch (Exception e) { ErrorMsg = e.Message; } }
/// <summary> /// 启动AI采集任务 /// </summary> public void TryArmTask() { if (AIState != Status.Idle) { throw new Exception("If you want to arm, the AI state must be 'Idle'!"); } else { if (aiTask == null) { try { //新建任务 aiTask = new NationalInstruments.DAQmx.Task(); aiTask.Stream.ReadAutoStart = true; //配置任务 NIAIConfigMapper.MapAndConfigAll(aiTask, _staticConfig.BasicAITaskConifg); //获取并设置通道数 _staticConfig.ChannelCount = aiTask.AIChannels.Count; //Verify the Task aiTask.Control(TaskAction.Verify); int channelCount = _staticConfig.ChannelCount; int readSamplePerTime = _staticConfig.BasicAITaskConifg.ClockConfig.ReadSamplePerTime; ReadData(aiTask, channelCount, readSamplePerTime); //idle -> ready AIState = Status.Ready; //开始任务 aiTask.Start(); } catch (DaqException ex) { //ex.Message goError(); throw ex; } } } }
public void GenerateWave(string device = "Dev1", double freq = 100, double amp = 2, AOFunctionGenerationType type = AOFunctionGenerationType.Sine) { try { if (myTask == null) { myTask = new NationalInstruments.DAQmx.Task(); if (amp < 0) { amp *= -1; } if (amp > 5) { amp = 5; } myTask.AOChannels.CreateFunctionGenerationChannel(device + "/fgen", "fgen", type, freq, //freq amp); //amplitude // verify the task before doing the waveform calculations myTask.Control(TaskAction.Verify); } else { myTask.Stop(); myTask.AOChannels[0].FunctionGenerationType = type; myTask.AOChannels[0].FunctionGenerationFrequency = freq; myTask.AOChannels[0].FunctionGenerationAmplitude = amp; } myTask.Start(); } catch (DaqException err) { MessageBox.Show(err.Message); myTask.Dispose(); myTask = null; } }
/// <summary> /// Indstiller DAQ til dataopsamling /// </summary> public void indstilDAQ() { try { analogInTask = new NationalInstruments.DAQmx.Task(); analogInTask.AIChannels.CreateVoltageChannel("Dev1/ai0", "myAIChannel", AITerminalConfiguration.Differential, 0, 5, AIVoltageUnits.Volts); analogInTask.Timing.ConfigureSampleClock("", 1000, SampleClockActiveEdge.Rising, SampleQuantityMode.ContinuousSamples, 100); analogInTask.Control(TaskAction.Verify); reader = new AnalogSingleChannelReader(analogInTask.Stream); reader.SynchronizeCallbacks = true; } catch (Exception) { throw; } }
//setup a current measurement public void setupMeasurement() { string channel = ""; try { myTask = new NationalInstruments.DAQmx.Task(); // Create a channels for (int i = 0; i < numOfChannels; i++) { double senseValue = senseOhms[i]; channel = string.Concat(NI6284, "/", channels[i]); //myTask.AIChannels.CreateVoltageChannel(channel, "", AIinput, rangeMins[i], rangeMaxs[i], NationalInstruments.DAQmx.AIVoltageUnits.Volts); myTask.AIChannels.CreateCurrentChannel(channel, "", NationalInstruments.DAQmx.AITerminalConfiguration.Differential, rangeMins[i], rangeMaxs[i], senseValue, AICurrentUnits.Amps); } // Configure Timing Specs myTask.Timing.ConfigureSampleClock("", sampleRate, SampleClockActiveEdge.Rising, SampleQuantityMode.FiniteSamples, totalSamples); try { myTask.Control(TaskAction.Verify); //validates setup is ok } catch (DaqException exception) { myTask.Dispose(); Console.WriteLine(exception.Message); } reader = new AnalogMultiChannelReader(myTask.Stream); //will get data back through this data = new double[numOfChannels, totalSamples]; //data container } catch (DaqException exception) { Console.WriteLine(exception.Message); } }
public void InitiateAsyncDaq(bool QueueMode) { _queueMode = QueueMode; if (runningTask == null) { try { // Create a new task myTask = new NationalInstruments.DAQmx.Task(); // Create a virtual channel myTask.AIChannels.CreateVoltageChannel(_daqSettingsDTO.physicalChannelName_, "", (AITerminalConfiguration)(-1), _daqSettingsDTO.MinValueVolt_, _daqSettingsDTO.MaxValueVolt, AIVoltageUnits.Volts); // Configure the timing parameters myTask.Timing.ConfigureSampleClock("", _daqSettingsDTO.SampleRate, // 1000 = frekvensen der læses med i hz SampleClockActiveEdge.Rising, SampleQuantityMode.ContinuousSamples, _daqSettingsDTO.SamplesPerChannel); // 100 = antal samples per læsning // Verify the Task myTask.Control(TaskAction.Verify); runningTask = myTask; analogInReader = new AnalogMultiChannelReader(myTask.Stream); analogCallback = new AsyncCallback(AnalogInCallback); // Use SynchronizeCallbacks to specify that the object // marshals callbacks across threads appropriately. analogInReader.SynchronizeCallbacks = true; analogInReader.BeginReadWaveform(_daqSettingsDTO.SamplesPerChannel, analogCallback, myTask); } catch (DaqException exception) { // Display Errors runningTask = null; myTask.Dispose(); } } }
private void button8_Click(object sender, EventArgs e) { try { mytask = new NationalInstruments.DAQmx.Task(); //voltage channel Configure AITerminalConfiguration -1 to Rse.. Check in NI MAX.. mytask.AIChannels.CreateVoltageChannel(comboBox2.Text, "", AITerminalConfiguration.Rse, -10, 10, AIVoltageUnits.Volts); mytask.Timing.ConfigureSampleClock("", Convert.ToDouble(textBox7.Text), (SampleClockActiveEdge.Rising), SampleQuantityMode.ContinuousSamples, 1000); mytask.Control(TaskAction.Verify); running_task = mytask; analogreader = new AnalogMultiChannelReader(mytask.Stream); analogreader.SynchronizeCallbacks = true; analogCallback = new AsyncCallback(analogInCallback); analogreader.BeginReadMultiSample(Convert.ToInt32(textBox8.Text), analogCallback, mytask); } catch { MessageBox.Show("error_1"); running_task = null; mytask.Dispose(); } }
public DAQ() { InitializeComponent(); operation.ItemsSource = operations; operation.SelectedIndex = 0; foreach (string s in DaqSystem.Local.Tasks) { try { using (NationalInstruments.DAQmx.Task t = DaqSystem.Local.LoadTask(s)) { t.Control(TaskAction.Verify); if (t.DIChannels.Count > 0 && t.Timing.SampleTimingType == SampleTimingType.OnDemand) { DI.Add(s); } else if (t.DOChannels.Count > 0 && t.Timing.SampleTimingType == SampleTimingType.OnDemand) { DO.Add(s); } else if (t.AIChannels.Count > 0) { AI.Add(s); } else if (t.AOChannels.Count > 0) { AO.Add(s); } } } catch (DaqException) { } } }
//아날로그 입력 연결 public bool Connect(ref string ErrorMsg) { bool flag = false; try { flag = true; Readtask.AIChannels.CreateVoltageChannel(ini.GetIniValue("NI", "Name") + "/ai0:7", "Analog Input", (AITerminalConfiguration.Rse), -10, 10, AIVoltageUnits.Volts); reader = new AnalogMultiChannelReader(Readtask.Stream); Readtask.Control(TaskAction.Verify); } catch (DaqException de) { ErrorMsg = de.Message; flag = false; } catch (Exception e) { ErrorMsg = e.Message; flag = false; } return(flag); }
/// <summary> /// Calling this metod will start a blocking sequnce of voltage meassurement at the NI USB-6009 DAQ. /// Before calling this metod you must have set the following properties /// sampleRateInHz (Default 205 Hz) /// rangeMinimumVolt (Default -1.0 Volt) /// rangeMaximumVolt (Default 1.0 Volt) /// samplesPerChannel (Default 3600) /// deviceName (Default "Dev2/ai0") /// seqTimeOut (Default infine ms) /// unless the default properties values goes. /// To get the last measurements use either /// currentVoltageSeq that returns a copy List<double> /// currentVoltageSeqArray that returns a copy in an double[] array /// </summary> public void getVoltageSeqBlocking() { try { // Create a new task readerTask = new NationalInstruments.DAQmx.Task(); //The background task reading // Create a channel readerTask.AIChannels.CreateVoltageChannel(deviceName, "", (AITerminalConfiguration)(-1), rangeMinimumVolt, rangeMaximumVolt, AIVoltageUnits.Volts); // Configure timing specs readerTask.Timing.ConfigureSampleClock("", sampleRateInHz, SampleClockActiveEdge.Rising, SampleQuantityMode.FiniteSamples, samplesPerChannel); readerTask.Stream.Timeout = seqTimeOut; // Verify the task readerTask.Control(TaskAction.Verify); //Preppare NI DAQ reader and a myTask to reader reader = new AnalogMultiChannelReader(readerTask.Stream); // Read the data data = reader.ReadWaveform(samplesPerChannel);//This call is a "Blocking call" dataToDataTable(data); } catch (DaqException exception) { System.Diagnostics.Debug.WriteLine(exception); } finally { readerTask.Dispose(); } }
private void firstMainPerformance(bool isref) { this.label_projectName.Content = Properties.Settings.Default.projectName; if (runningTask == null) { if (isref == true) { jobNumGrid.ColumnDefinitions[1].Width = new GridLength(1, GridUnitType.Star); jobNumGrid.ColumnDefinitions[0].Width = new GridLength(1, GridUnitType.Star); try { Properties.Settings.Default.jobNum = 1; duration = Properties.Settings.Default.jobDuration * 1000; try { string conStr = "Server=localhost;Database=" + Properties.Settings.Default.databaseName + ";Uid=" + Properties.Settings.Default.databaseID + ";Pwd=" + Properties.Settings.Default.databasePwd; MySqlConnection con = new MySqlConnection(conStr); MySqlCommand comm = con.CreateCommand(); MySqlDataReader Reader; con.Open(); comm.CommandText = "SELECT MAX(Measure_index) FROM `" + Properties.Settings.Default.databaseName + "`.`measured_data`"; Reader = comm.ExecuteReader(); Reader.Read(); measure_index = Convert.ToInt32(Reader[0]) + 1; con.Close(); } catch (Exception exc) { measure_index = 0; } try { string conStr = "Server=localhost;Database=" + Properties.Settings.Default.databaseName + ";Uid=" + Properties.Settings.Default.databaseID + ";Pwd=" + Properties.Settings.Default.databasePwd; MySqlConnection con = new MySqlConnection(conStr); MySqlCommand comm = con.CreateCommand(); MySqlDataReader Reader; con.Open(); comm.CommandText = "SELECT COUNT(*) FROM `" + Properties.Settings.Default.databaseName + "`.`measured_data`"; Reader = comm.ExecuteReader(); Reader.Read(); measured_id = Convert.ToInt32(Reader[0]) + 1; con.Close(); } catch (Exception exc) { measured_id = 0; } try { string conStr = "Server=localhost;Database=" + Properties.Settings.Default.databaseName + ";Uid=" + Properties.Settings.Default.databaseID + ";Pwd=" + Properties.Settings.Default.databasePwd; MySqlConnection con = new MySqlConnection(conStr); MySqlCommand comm = con.CreateCommand(); MySqlDataReader Reader; con.Open(); comm.CommandText = "SELECT COUNT(*) FROM `" + Properties.Settings.Default.databaseName + "`.`test_reference` WHERE Reference_id=" + Properties.Settings.Default.reference_id; Reader = comm.ExecuteReader(); Reader.Read(); numOfdata = Convert.ToInt32(Reader[0]); con.Close(); con.Open(); string commtext = "SELECT * FROM `" + Properties.Settings.Default.databaseName + "`.`test_reference` WHERE Reference_id=" + Properties.Settings.Default.reference_id; MySqlDataAdapter mda = new MySqlDataAdapter(commtext, con); DataSet ds = new DataSet(); mda.Fill(ds); refDataTable = ds.Tables[0]; con.Close(); } catch (Exception exc) { } int txtFilePathIndex = Properties.Settings.Default.textFilePathSetting.LastIndexOf("\\"); string path = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\" + "SF LWM\\" + Properties.Settings.Default.projectName + "\\" + DateTime.Now.ToString("yyyy MM dd") + "_" + DateTime.Now.ToString("HH mm ss"); Properties.Settings.Default.txtFilePath = path; DirectoryInfo f = new DirectoryInfo(path); if (f.Exists == false) f.Create(); countRows = 0; fault_count = 0; fault_stitch = ""; iswelding = false; current_stitch = 0; samplingVariable = Convert.ToInt32(1 / ((Properties.Settings.Default.samplesPerChannelNumeric * 100) / Properties.Settings.Default.rateNumeric)); this.label3.Content = Convert.ToString(Properties.Settings.Default.jobNum - 1); dataTable = new DataTable(); chart1.Series[0].Points.Clear(); chart2.Series[0].Points.Clear(); int numofGraphs = Properties.Settings.Default.physicalChannelCheckedIndex.Length; switch (numofGraphs) { case 0: break; case 1: chart1.ChartAreas[0].AxisX.Maximum = Convert.ToDouble(numOfdata); chart1.ChartAreas[0].AxisX.Minimum = 0; break; case 2: chart1.ChartAreas[0].AxisX.Maximum = Convert.ToDouble(numOfdata); chart1.ChartAreas[0].AxisX.Minimum = 0; chart2.ChartAreas[0].AxisX.Maximum = Convert.ToDouble(numOfdata); chart2.ChartAreas[0].AxisX.Minimum = 0; break; } // Create a new task myTask = new NationalInstruments.DAQmx.Task(); // Create a virtual channel myTask.AIChannels.CreateVoltageChannel(Properties.Settings.Default.physicalChannel, "", (AITerminalConfiguration)(-1), Convert.ToDouble(Properties.Settings.Default.minVoltage), Convert.ToDouble(Properties.Settings.Default.maxVoltage), AIVoltageUnits.Volts); // Configure the timing parameters myTask.Timing.ConfigureSampleClock("", Properties.Settings.Default.rateNumeric, SampleClockActiveEdge.Rising, SampleQuantityMode.ContinuousSamples, 100000); // Verify the Task myTask.Control(TaskAction.Verify); // Prepare the table for Data InitializeDataTable(myTask.AIChannels, ref dataTable); runningTask = myTask; analogInReader = new AnalogMultiChannelReader(myTask.Stream); analogCallback = new AsyncCallback(AnalogInCallback); // Use SynchronizeCallbacks to specify that the object // marshals callbacks across threads appropriately. analogInReader.SynchronizeCallbacks = true; analogInReader.BeginReadWaveform(Convert.ToInt32(Properties.Settings.Default.samplesPerChannelNumeric), analogCallback, myTask); } catch (DaqException exception) { // Display Errors MessageBox.Show(exception.Message, "기기 연결을 확인해주세요"); runningTask = null; myTask.Dispose(); } } else { jobNumGrid.ColumnDefinitions[1].Width = new GridLength(0); jobNumGrid.ColumnDefinitions[0].Width = new GridLength(1, GridUnitType.Star); try { Properties.Settings.Default.jobNum = 1; duration = Properties.Settings.Default.jobDuration * 1000; try { string conStr = "Server=localhost;Database=" + Properties.Settings.Default.databaseName + ";Uid=" + Properties.Settings.Default.databaseID + ";Pwd=" + Properties.Settings.Default.databasePwd; MySqlConnection con = new MySqlConnection(conStr); MySqlCommand comm = con.CreateCommand(); MySqlDataReader Reader; con.Open(); comm.CommandText = "SELECT MAX(Measure_index) FROM `" + Properties.Settings.Default.databaseName + "`.`measured_data`"; Reader = comm.ExecuteReader(); Reader.Read(); measure_index = Convert.ToInt32(Reader[0]) + 1; con.Close(); } catch (Exception exc) { measure_index = 0; } try { string conStr = "Server=localhost;Database=" + Properties.Settings.Default.databaseName + ";Uid=" + Properties.Settings.Default.databaseID + ";Pwd=" + Properties.Settings.Default.databasePwd; MySqlConnection con = new MySqlConnection(conStr); MySqlCommand comm = con.CreateCommand(); MySqlDataReader Reader; con.Open(); comm.CommandText = "SELECT COUNT(*) FROM `" + Properties.Settings.Default.databaseName + "`.`measured_data`"; Reader = comm.ExecuteReader(); Reader.Read(); measured_id = Convert.ToInt32(Reader[0]) + 1; con.Close(); } catch (Exception exc) { measured_id = 0; } numOfdata = Convert.ToInt32((Properties.Settings.Default.rateNumeric / Properties.Settings.Default.samplesPerChannelNumeric) * (duration / 1000)); int txtFilePathIndex = Properties.Settings.Default.textFilePathSetting.LastIndexOf("\\"); string path = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\" + "SF LWM\\" + Properties.Settings.Default.projectName + "\\" + DateTime.Now.ToString("yyyy MM dd") + "_" + DateTime.Now.ToString("HH mm ss"); Properties.Settings.Default.txtFilePath = path; DirectoryInfo f = new DirectoryInfo(path); if (f.Exists == false) f.Create(); countRows = 0; fault_count = 0; fault_stitch = ""; iswelding = false; current_stitch = 0; samplingVariable = Convert.ToInt32(1 / ((Properties.Settings.Default.samplesPerChannelNumeric * 100) / Properties.Settings.Default.rateNumeric)); this.label3.Content = Convert.ToString(Properties.Settings.Default.jobNum - 1); dataTable = new DataTable(); chart1.Series[0].Points.Clear(); chart2.Series[0].Points.Clear(); chart1.ChartAreas[0].AxisX.Maximum = Convert.ToDouble(numOfdata); chart1.ChartAreas[0].AxisX.Minimum = 0; chart2.ChartAreas[0].AxisX.Maximum = Convert.ToDouble(numOfdata); chart2.ChartAreas[0].AxisX.Minimum = 0; // Create a new task myTask = new NationalInstruments.DAQmx.Task(); // Create a virtual channel myTask.AIChannels.CreateVoltageChannel(Properties.Settings.Default.physicalChannel, "", (AITerminalConfiguration)(-1), Convert.ToDouble(Properties.Settings.Default.minVoltage), Convert.ToDouble(Properties.Settings.Default.maxVoltage), AIVoltageUnits.Volts); // Configure the timing parameters myTask.Timing.ConfigureSampleClock("", Properties.Settings.Default.rateNumeric, SampleClockActiveEdge.Rising, SampleQuantityMode.ContinuousSamples, 100000); // Verify the Task myTask.Control(TaskAction.Verify); // Prepare the table for Data InitializeDataTable(myTask.AIChannels, ref dataTable); runningTask = myTask; analogInReader = new AnalogMultiChannelReader(myTask.Stream); analogCallback = new AsyncCallback(AnalogInCallback2); // Use SynchronizeCallbacks to specify that the object // marshals callbacks across threads appropriately. analogInReader.SynchronizeCallbacks = true; analogInReader.BeginReadWaveform(Convert.ToInt32(Properties.Settings.Default.samplesPerChannelNumeric), analogCallback, myTask); } catch (DaqException exception) { // Display Errors MessageBox.Show(exception.Message, "기기 연결을 확인해주세요"); runningTask = null; myTask.Dispose(); } } } }
private void btnStart_Click(object sender, RoutedEventArgs e) { if (runningTask == null) { try { btnStop.IsEnabled = true; btnStart.IsEnabled = false; double rangeMinimum = Convert.ToDouble(edminimum.Text); double rangeMaximum = Convert.ToDouble(edmaximum.Text); double sampleRate = Convert.ToDouble(edRate.Text); int samplePerChannel = Convert.ToInt32(edchannel.Text); //// Create a new task //myTask = new ni.Task(); //// Create a virtual channel //myTask.AIChannels.CreateVoltageChannel(physicalChannelComboBox.Text, "", // (AITerminalConfiguration)(-1), rangeMinimum, // rangeMaximum, AIVoltageUnits.Volts); //// Configure the timing parameters //myTask.Timing.ConfigureSampleClock("", sampleRate, // SampleClockActiveEdge.Rising, SampleQuantityMode.ContinuousSamples, samplePerChannel * 10); //// Configure the Every N Samples Event //myTask.EveryNSamplesReadEventInterval = samplePerChannel; //myTask.EveryNSamplesRead += new EveryNSamplesReadEventHandler(myTask_EveryNSamplesRead); //// Verify the Task //myTask.Control(TaskAction.Verify); //// Prepare the table for Data //InitializeDataTable(myTask.AIChannels, ref dataTable); //runningTask = myTask; //analogInReader = new AnalogMultiChannelReader(myTask.Stream); //runningTask.SynchronizeCallbacks = true; //runningTask.Start(); // Create a new task ni.Task myTask = new ni.Task(); // Create a virtual channel myTask.AIChannels.CreateVoltageChannel(physicalChannelComboBox.Text, "", (ni.AITerminalConfiguration)(-1), rangeMinimum, rangeMaximum, ni.AIVoltageUnits.Volts); // Configure the timing parameters myTask.Timing.ConfigureSampleClock("", sampleRate, ni.SampleClockActiveEdge.Rising, ni.SampleQuantityMode.FiniteSamples, samplePerChannel * 10); myTask.Triggers.StartTrigger.ConfigureDigitalEdgeTrigger("/Dev4/PFI12", ni.DigitalEdgeStartTriggerEdge.Rising); myTask.Triggers.StartTrigger.Retriggerable = true; // Configure the Every N Samples Event myTask.EveryNSamplesReadEventInterval = samplePerChannel; myTask.EveryNSamplesRead += new EveryNSamplesReadEventHandler(myTask_EveryNSamplesRead); // Verify the Task myTask.Control(TaskAction.Verify); // Prepare the table for Data InitializeDataTable(myTask.AIChannels, ref dataTable); runningTask = myTask; analogInReader = new AnalogMultiChannelReader(myTask.Stream); runningTask.SynchronizeCallbacks = true; runningTask.Start(); } catch (DaqException exception) { // Display Errors MessageBox.Show(exception.Message); runningTask = null; btnStop.IsEnabled = false; btnStart.IsEnabled = true; } } }
public override decimal Get_Constant_Voltage(TTA_measurement myTTA, ATIM_MainWindow GUI) { //Konstante Spannung über mehrere Samples messen //1. Daten-Felder definieren*************************************************************************************** //Übergabe-Parameter für NI-Karte definieren IAsyncResult uebergabe_parameter_ReadWaveform_Constant = null; //Ausgangsdaten AnalogSingleChannelReader messInfo_NI_SinglePulse_Constant = null; // Task für Messung erzeugen NationalInstruments.DAQmx.Task myTask_NI_Constant = null; //2. NI-Karte scharf stellen*********************************************************************************** try { myTask_NI_Constant = new NationalInstruments.DAQmx.Task("myTask_Constant"); // Kanal erzeugen: //--------------------------------------------------------------------------------- //physicalChannelName As String: z.B. Dev1/ai3 //nameToAssignChannel As String: sollte leer bleiben (Zweck keine Ahnung) //terminalConfiguration As AITerminalConfiguration: Differential oder ähnlich //minimumValue As Double: z.B. -10 [V] untere Grenze //maximumValue As Double: z.B. 10 [V] //customScaleName As String: //--------------------------------------------------------------------------------- myTask_NI_Constant.AIChannels.CreateVoltageChannel(VISA_or_Channel_Name, "", AITerminalConfiguration.Differential, -Range / 1000, Range / 1000, AIVoltageUnits.Volts); // Timing-Parameter definieren: //--------------------------------------------------------------------------------- //signalSource As string: Wenn interne Clock verwendet wird "" //rate As double: Abtastfrequenz in Hz (Interne Clock) //activeEdge As SampleClockActiveEdge: Bei welcher Flanke der Clock abgetastet wird //sampleMode As SampleQuantityMode: Legt fest ob dauerhaft gemessen wird, oder bis // nur eine endliche Anzahl (nächster Parameter) //samplesPerChannel As int: Anzahl der Samples //--------------------------------------------------------------------------------- myTask_NI_Constant.Timing.ConfigureSampleClock("", Frequency, SampleClockActiveEdge.Rising, SampleQuantityMode.FiniteSamples, (int)Frequency / 1000); // Trigger definieren //--------------------------------------------------------------------------------- //Kein Trigger definieren --> Sofort starten //--------------------------------------------------------------------------------- myTask_NI_Constant.Triggers.StartTrigger.ConfigureNone(); //TimeOut anpassen myTask_NI_Constant.Stream.Timeout = 2000; // Verify the Task myTask_NI_Constant.Control(TaskAction.Verify); //Messwert-Ausgabe definieren messInfo_NI_SinglePulse_Constant = new AnalogSingleChannelReader(myTask_NI_Constant.Stream); // Use SynchronizeCallbacks to specify that the object // marshals callbacks across threads appropriately. messInfo_NI_SinglePulse_Constant.SynchronizeCallbacks = true; uebergabe_parameter_ReadWaveform_Constant = messInfo_NI_SinglePulse_Constant.BeginReadWaveform((int)Frequency / 1000, null, null); } catch (DaqException ex) { //Bei Daq Exception soll die Fehlermeldung ausgegeben werden (z.B. kein Kanal, ...) MessageBox.Show(ex.Message); //Task beenden myTask_NI_Constant.Dispose(); return(0); } //6. Daten auswerten******************************************************************************************* try { // vorhandene Daten auslesen AnalogWaveformSampleCollection <double> test = messInfo_NI_SinglePulse_Constant.EndReadWaveform(uebergabe_parameter_ReadWaveform_Constant).Samples; //Durchschnitt berechnen double average = 0; for (int counter = 0; counter < test.Count; counter++) { average += test[counter].Value; } return((decimal)average / test.Count / myTTA.MyRack.Gain + myTTA.MyRack.U_offset / 1000); } catch (DaqException ex) { //Bei Fehler -> Fehlermeldung ausgeben (hier z.B. Timeout) MessageBox.Show(ex.Message); return(0); } finally { // Task beenden myTask_NI_Constant.Dispose(); } }
/// <summary> /// 启动AI采集任务 /// </summary> public void TryArm() { if (AIState != Status.Idle) { throw new Exception("If you want to arm, the AI state must be 'Idle'!"); } else { if (aiTask == null) { try { //autoMapper //createMap时,输出enum直接是输入enum的值,所以不对 //不createMap时,使用name匹配,是我们需要的,输出enum是对应name的值,但是必须保证输入和输出enum的name完全对应 var config = new MapperConfiguration(cfg => { }); IMapper mapper = new Mapper(config); AITerminalConfiguration niTerminalConfig = mapper.Map <AITerminalConfiguration>(TerminalConfig); //Create a task that will be disposed after it has been used aiTask = new NationalInstruments.DAQmx.Task(); //Create a virtual channel aiTask.AIChannels.CreateVoltageChannel(channel, "", niTerminalConfig, MinimumVolt, MaximumVolt, AIVoltageUnits.Volts); //Trigger type switch (AITriggerType) { //softTrigger = start directly case TriggerType.SoftTrigger: break; case TriggerType.DigitalTrigger: var digitalTriggerEdge = mapper.Map <DigitalEdgeStartTriggerEdge>(AITriggerEdge); aiTask.Triggers.StartTrigger.ConfigureDigitalEdgeTrigger(TriggerSource, digitalTriggerEdge); break; case TriggerType.AnalogTrigger: var analogTriggerEdge = mapper.Map <AnalogEdgeStartTriggerSlope>(AITriggerEdge); aiTask.Triggers.StartTrigger.ConfigureAnalogEdgeTrigger(TriggerSource, analogTriggerEdge, AnalogTriggerLevel); break; default: break; } ////Timing SampleQuantityMode sampleQuantityMode = mapper.Map <SampleQuantityMode>(AISamplesMode); var sampleClockActiveEdge = mapper.Map <SampleClockActiveEdge>(ClkActiveEdge); //经过测试,对于aiTask.Timing.ConfigureSampleClock //有限采样时,采样SamplesPerChannel 个点 //连续采样时,一直采集,直到手动停止 aiTask.Timing.ConfigureSampleClock(ClkSource, SampleRate, sampleClockActiveEdge, sampleQuantityMode, SamplesPerChannel); //Verify the Task aiTask.Control(TaskAction.Verify); //将所有通道名赋给AllActiveChannels AllActiveChannels = new List <string>(); var channelCollection = aiTask.AIChannels; int numOfChannels = channelCollection.Count; for (int currentChannelIndex = 0; currentChannelIndex < numOfChannels; currentChannelIndex++) { AllActiveChannels.Add(channelCollection[currentChannelIndex].PhysicalName); } AIState = Status.Ready; //idle -> ready OnStatusChanged(); //SoftTrigger means start the task directly //if (AITriggerType == TriggerType.SoftTrigger) //{ // AIState = Status.Running; //} //read stream reader = new AnalogMultiChannelReader(aiTask.Stream); reader.SynchronizeCallbacks = false; aiReaderCallback = new AsyncCallback(aiCallback); reader.BeginReadMultiSample(ReadSamplePerTime, aiReaderCallback, aiTask); } catch (DaqException ex) { //ex.Message goError(); } } } }
//setups current hardware to be ready for measurement public void commitAI() { myTask.Control(TaskAction.Commit); }
private void runMainPerformance2() { if (runningTask == null) { try { duration = Properties.Settings.Default.jobDuration * 1000; countRows = 0; fault_count = 0; fault_stitch = ""; iswelding = false; current_stitch = 0; samplingVariable = Convert.ToInt32(1 / ((Properties.Settings.Default.samplesPerChannelNumeric * 100) / Properties.Settings.Default.rateNumeric)); //this.label3.Content = Convert.ToString(Properties.Settings.Default.jobNum - 1); //this.label5.Content = Convert.ToString(fault_num); dataTable = new DataTable(); // Create a new task myTask = new NationalInstruments.DAQmx.Task(); // Create a virtual channel myTask.AIChannels.CreateVoltageChannel(Properties.Settings.Default.physicalChannel, "", (AITerminalConfiguration)(-1), Convert.ToDouble(Properties.Settings.Default.minVoltage), Convert.ToDouble(Properties.Settings.Default.maxVoltage), AIVoltageUnits.Volts); // Configure the timing parameters myTask.Timing.ConfigureSampleClock("", Properties.Settings.Default.rateNumeric, SampleClockActiveEdge.Rising, SampleQuantityMode.ContinuousSamples, 100000); // Verify the Task myTask.Control(TaskAction.Verify); // Prepare the table for Data InitializeDataTable(myTask.AIChannels, ref dataTable); runningTask = myTask; analogInReader = new AnalogMultiChannelReader(myTask.Stream); analogCallback = new AsyncCallback(AnalogInCallback2); // Use SynchronizeCallbacks to specify that the object // marshals callbacks across threads appropriately. analogInReader.SynchronizeCallbacks = true; analogInReader.BeginReadWaveform(Convert.ToInt32(Properties.Settings.Default.samplesPerChannelNumeric), analogCallback, myTask); } catch (DaqException exception) { // Display Errors MessageBox.Show(exception.Message, "기기 연결을 확인해주세요"); runningTask = null; myTask.Dispose(); } } }
public override bool Measure_TTA_Several_Cycles(TTA_measurement myTTA, ATIM_MainWindow GUI) { //StatusBar anpassen GUI.StatusBar_TTA_Single(0, (int)myTTA.MyRack.Cycles); //1. Parameter für Messlänge senden******************************************************************************** //Sampelzahl und Abtastfrequenz definieren (Times sind in ms deswegen /1000) int anzahl_samples = Convert.ToInt32(Frequency) / 1000 * Decimal.ToInt32(myTTA.MyRack.Time_Heat + myTTA.MyRack.Time_Meas); //Sample überschuss, da Umschalten derzeit nicht richtig int sample_ueberschuss = 2000; //Trigger berechnen double trigger = decimal.ToDouble((numericUpDown_Trigger.Value - myTTA.MyRack.U_offset / 1000) * myTTA.MyRack.Gain); //2. Daten-Felder definieren*************************************************************************************** //Übergabe-Parameter für NI-Karte definieren IAsyncResult uebergabe_parameter_ReadWaveform = null; //Ausgangsdaten AnalogSingleChannelReader messInfo_NI_SinglePulse = null; //Feld für Daten definieren (mit 100x max- beginnen) myTTA.Creat_RowDataField(100 + anzahl_samples + sample_ueberschuss); //3. Loop********************************************************************************************************** for (int i = 0; i < myTTA.MyRack.Cycles; i++) { //4. NI-Karte scharf stellen*********************************************************************************** try { // Task für Messung erzeugen myTask_NI = new NationalInstruments.DAQmx.Task("myTask"); // Kanal erzeugen: //--------------------------------------------------------------------------------- //physicalChannelName As String: z.B. Dev1/ai3 //nameToAssignChannel As String: sollte leer bleiben (Zweck keine Ahnung) //terminalConfiguration As AITerminalConfiguration: Differential oder ähnlich //minimumValue As Double: z.B. -10 [V] untere Grenze //maximumValue As Double: z.B. 10 [V] //customScaleName As String: //--------------------------------------------------------------------------------- myTask_NI.AIChannels.CreateVoltageChannel(VISA_or_Channel_Name, "", AITerminalConfiguration.Differential, -Range / 1000, Range / 1000, AIVoltageUnits.Volts); // Timing-Parameter definieren: //--------------------------------------------------------------------------------- //signalSource As string: Wenn interne Clock verwendet wird "" //rate As double: Abtastfrequenz in Hz (Interne Clock) //activeEdge As SampleClockActiveEdge: Bei welcher Flanke der Clock abgetastet wird //sampleMode As SampleQuantityMode: Legt fest ob dauerhaft gemessen wird, oder bis // nur eine endliche Anzahl (nächster Parameter) //samplesPerChannel As int: Anzahl der Samples //--------------------------------------------------------------------------------- myTask_NI.Timing.ConfigureSampleClock("", Frequency, SampleClockActiveEdge.Rising, SampleQuantityMode.FiniteSamples, anzahl_samples + sample_ueberschuss); // Trigger definieren //--------------------------------------------------------------------------------- //source As String: Herkuft des Triggers. Hier gleich wie Daten (Dev1/ai3) //slope As AnalogEdgeStartTriggerSlope: Rising or Falling //level As Double: Trigger Level (vorher bestimmt //--------------------------------------------------------------------------------- myTask_NI.Triggers.StartTrigger.ConfigureAnalogEdgeTrigger(VISA_or_Channel_Name, AnalogEdgeStartTriggerSlope.Rising, trigger); //Hysterese festlegen (keine Ahnung ob das Wichtig ist) //--------------------------------------------------------------------------------- //Hysteresis as Double: Wert der Hysterese //--------------------------------------------------------------------------------- myTask_NI.Triggers.StartTrigger.AnalogEdge.Hysteresis = 0.05; //TimeOut anpassen myTask_NI.Stream.Timeout = (Int32)(1.2m * (myTTA.MyRack.Time_Heat + myTTA.MyRack.Time_Meas)); // Verify the Task myTask_NI.Control(TaskAction.Verify); //Messwert-Ausgabe definieren messInfo_NI_SinglePulse = new AnalogSingleChannelReader(myTask_NI.Stream); // Use SynchronizeCallbacks to specify that the object // marshals callbacks across threads appropriately. messInfo_NI_SinglePulse.SynchronizeCallbacks = true; uebergabe_parameter_ReadWaveform = messInfo_NI_SinglePulse.BeginReadWaveform(anzahl_samples + sample_ueberschuss, null, null); } catch (DaqException ex) { //Bei Daq Exception soll die Fehlermeldung ausgegeben werden (z.B. kein Kanal, ...) MessageBox.Show(ex.Message); //Task beenden myTask_NI.Dispose(); } //5. Puls starten********************************************************************************************** System.Threading.Thread.Sleep(300); myTTA.MyRack.SinglePuls_withDelay(); System.Threading.Thread.Sleep(1000); //6. Daten auswerten******************************************************************************************* try { // vorhandene Daten auslesen AnalogWaveformSampleCollection <double> test = messInfo_NI_SinglePulse.EndReadWaveform(uebergabe_parameter_ReadWaveform).Samples; double factor = Math.Pow(2, 15) / (Range / 1000); //Mit 100mal Minimalwert beginnen. (Für umschaltpunkt suche) for (int counter = 0; counter < 100; counter++) { myTTA.Binary_Raw_Files[i, counter] = short.MinValue; } //Daten in Binär (short umrechnen) & TTA übergeben for (int counter = 100; counter < test.Count; counter++) { double helping_Double = test[counter].Value * factor; myTTA.Binary_Raw_Files[i, counter] = (short)(helping_Double); } //Gleich in Graph ausgeben GUI.Add_Series_to_RAW(myTTA, i); } catch (DaqException ex) { //Bei Fehler -> Fehlermeldung ausgeben (hier z.B. Timeout) MessageBox.Show(ex.Message); return(false); } finally { // Task beenden myTask_NI.Dispose(); } //7. StatusBar anpassen**************************************************************************************** GUI.StatusBar_TTA_Single(i + 1, (int)myTTA.MyRack.Cycles); } return(true); }
public bool TTA_wait_for_Trigger() { //4. NI-Karte scharf stellen*********************************************************************************** try { // Task für Messung erzeugen myTask_NI = new NationalInstruments.DAQmx.Task("myTask"); // Kanal erzeugen: //--------------------------------------------------------------------------------- //physicalChannelName As String: z.B. Dev1/ai3 //nameToAssignChannel As String: sollte leer bleiben (Zweck keine Ahnung) //terminalConfiguration As AITerminalConfiguration: Differential oder ähnlich //minimumValue As Double: z.B. -10 [V] untere Grenze //maximumValue As Double: z.B. 10 [V] //customScaleName As String: //--------------------------------------------------------------------------------- myTask_NI.AIChannels.CreateVoltageChannel(Channel_Name, "", AITerminalConfiguration.Differential, -Range / 1000, Range / 1000, AIVoltageUnits.Volts); // Timing-Parameter definieren: //--------------------------------------------------------------------------------- //signalSource As string: Wenn interne Clock verwendet wird "" //rate As double: Abtastfrequenz in Hz (Interne Clock) //activeEdge As SampleClockActiveEdge: Bei welcher Flanke der Clock abgetastet wird //sampleMode As SampleQuantityMode: Legt fest ob dauerhaft gemessen wird, oder bis // nur eine endliche Anzahl (nächster Parameter) //samplesPerChannel As int: Anzahl der Samples //--------------------------------------------------------------------------------- myTask_NI.Timing.ConfigureSampleClock("", Frequency, SampleClockActiveEdge.Rising, SampleQuantityMode.FiniteSamples, (int)Samples); // Trigger definieren //--------------------------------------------------------------------------------- //source As String: Herkuft des Triggers. Hier gleich wie Daten (Dev1/ai3) //slope As AnalogEdgeStartTriggerSlope: Rising or Falling //level As Double: Trigger Level (vorher bestimmt //--------------------------------------------------------------------------------- myTask_NI.Triggers.StartTrigger.ConfigureAnalogEdgeTrigger(Channel_Name, AnalogEdgeStartTriggerSlope.Rising, Trigger_Level_UI); //Hysterese festlegen (keine Ahnung ob das Wichtig ist) //--------------------------------------------------------------------------------- //Hysteresis as Double: Wert der Hysterese //--------------------------------------------------------------------------------- myTask_NI.Triggers.StartTrigger.AnalogEdge.Hysteresis = 0.05; //TimeOut anpassen myTask_NI.Stream.Timeout = (Int32)(1.2m * (Samples * 1000 / Frequency)); // Verify the Task myTask_NI.Control(TaskAction.Verify); //Messwert-Ausgabe definieren messInfo_NI_SinglePulse = new AnalogSingleChannelReader(myTask_NI.Stream); // Use SynchronizeCallbacks to specify that the object // marshals callbacks across threads appropriately. messInfo_NI_SinglePulse.SynchronizeCallbacks = true; uebergabe_parameter_ReadWaveform = messInfo_NI_SinglePulse.BeginReadWaveform((int)Samples, null, null); return(true); } catch (DaqException ex) { //Bei Daq Exception soll die Fehlermeldung ausgegeben werden (z.B. kein Kanal, ...) MessageBox.Show(ex.Message); //Task beenden myTask_NI.Dispose(); return(false); } }
public DAQHandler(int s, int secLength) { sampleRate = s; // Setting up for accelerometers try { // Create a new task for DAQ dataTable = new DataTable { TableName = "DAQTest" };; myTask = new NationalInstruments.DAQmx.Task("sensors"); AIChannel[] aiChannel = new AIChannel[3]; aiChannel[0] = myTask.AIChannels.CreateAccelerometerChannel("cDAQ1Mod1/ai0", "", terminalConfiguration, rangeMinimum, rangeMaximum, sensitvity, sensitivityUnits, excitationSource, excitation, AIAccelerationUnits.G); aiChannel[1] = myTask.AIChannels.CreateAccelerometerChannel("cDAQ1Mod1/ai1", "", terminalConfiguration, rangeMinimum, rangeMaximum, sensitvity, sensitivityUnits, excitationSource, excitation, AIAccelerationUnits.G); aiChannel[2] = myTask.AIChannels.CreateAccelerometerChannel("cDAQ1Mod1/ai2", "", terminalConfiguration, rangeMinimum, rangeMaximum, sensitvity, sensitivityUnits, excitationSource, excitation, AIAccelerationUnits.G); // Setup the input coupling for (int i = 0; i < 3; i++) { aiChannel[i].Coupling = AICoupling.AC; } // Configure the timing parameters //myTask.Timing.ConfigureSampleClock("", sampleRate, //SampleClockActiveEdge.Rising, SampleQuantityMode.FiniteSamples, samplesPerChannel); myTask.Timing.ConfigureSampleClock("", sampleRate, SampleClockActiveEdge.Rising, SampleQuantityMode.ContinuousSamples, 1000); //// Configure the Analog Trigger //myTask.Triggers.StartTrigger.ConfigureAnalogEdgeTrigger(triggerSource, triggerSlope, triggerLevel); //myTask.Triggers.StartTrigger.AnalogEdge.Hysteresis = triggerHysteresis; // Verify the Task myTask.Control(TaskAction.Verify); //Prepare the table for Data InitializeDataTable(myTask.AIChannels, ref dataTable, secLength); signalLength = secLength * Convert.ToInt32(sampleRate); runningTask = myTask; reader = new AnalogMultiChannelReader(myTask.Stream); analogCallback = new AsyncCallback(AnalogInCallback); reader.SynchronizeCallbacks = true; reader.BeginReadWaveform(samplesPerChannel, analogCallback, myTask); } catch (DaqException exception) { // Display Errors Console.WriteLine(exception.Message); runningTask = null; myTask.Dispose(); } }
private void StartAcquisitionBtn_Click(object sender, EventArgs e) { try { _log.Info("Starts to Data acquisition."); deviceDescription = DeviceIDtextBox.Text; string DAQinputrange = InputrangecomboBox.Text; string DAQaisignaltype = ConnecttypecomboBox.Text; convertClkRate = int.Parse(SamplingTextbox.Text); sectionLength = int.Parse(DataLengthtextBox.Text); startChannel = int.Parse(ChanneltextBox.Text); lowcutoff = int.Parse(Lowcutoffbox.Text); highcutoff = int.Parse(highcutoffbox.Text); bool trigger = triggerbox.Checked; int pretriggersamples = int.Parse(pretriggerSamples.Text); try { _log.Info("Load DAQ parameter"); //mapping inputrange - 5 to 5 V // -10 to 10 V // -1 to 1 V // 4 to 20 mA switch (DAQinputrange) { case "-1 to 1 V": maxinputrange = 1; mininputrange = -1; break; case "-5 to 5 V": maxinputrange = 5; mininputrange = -5; break; case "-10 to 10 V": maxinputrange = 10; mininputrange = -10; break; default: break; } if (runningTask == null) { try { // Create a new task myTask = new NationalInstruments.DAQmx.Task(); // Create a virtual channel myTask.AIChannels.CreateVoltageChannel(deviceDescription, "", AITerminalConfiguration.Pseudodifferential, mininputrange, maxinputrange, AIVoltageUnits.Volts); // Configure the timing parameters myTask.Timing.ConfigureSampleClock("", convertClkRate, SampleClockActiveEdge.Rising, SampleQuantityMode.ContinuousSamples, 100000); ptSaved = 0; myTask.AIChannels.All.Coupling = AICoupling.AC; if (IEPEcheckBox.Checked == true) { //Ai Channel 0 IEPE function output & set AC coupling myTask.AIChannels.All.ExcitationVoltageOrCurrent = AIExcitationVoltageOrCurrent.Current; myTask.AIChannels.All.ExcitationSource = AIExcitationSource.Internal; myTask.AIChannels.All.ExcitationValue = 0.0021; } // Verify the Task myTask.Control(TaskAction.Verify); runningTask = myTask; //Data buffer prepared if (pretriggersamples <= sectionLength) { pretrigger = new double[myTask.AIChannels.Count, sectionLength]; ptSize = sectionLength; } else { // Make the size of the pretrigger buffer the smallest multiple of samples that is greater // than the requested pretrigger samples ptSize = ((int)(pretriggersamples / sectionLength) + 1) * sectionLength; pretrigger = new double[myTask.AIChannels.Count, ptSize]; } if (trigger == true) { reader = new AnalogMultiChannelReader(myTask.Stream); // Use SynchronizeCallbacks to specify that the object // marshals callbacks across threads appropriately. reader.SynchronizeCallbacks = true; reader.BeginReadMultiSample(Convert.ToInt32(sectionLength), new AsyncCallback(ReadData), myTask); } else { analogInReader = new AnalogMultiChannelReader(myTask.Stream); analogCallback = new AsyncCallback(AnalogInCallback); // Use SynchronizeCallbacks to specify that the object // marshals callbacks across threads appropriately. analogInReader.SynchronizeCallbacks = true; analogInReader.BeginReadWaveform(sectionLength, analogCallback, myTask); } //Continue acquisition } catch (NationalInstruments.DAQmx.DaqException exception) { // Display Errors MessageBox.Show(exception.Message); runningTask = null; myTask.Dispose(); } } } catch (Exception err) { _log.Error("Faile to Load DAQ parameter message is---" + err.Message); } Console.WriteLine(" StreamingAI is in progress... any key to quit !\n"); // Step 7: The device is acquiring data. // step 8: Stop the operation if it is running. SamplingTextbox.Enabled = false; DataLengthtextBox.Enabled = false; ChanneltextBox.Enabled = false; FreqrangetextBox.Enabled = false; DeviceIDtextBox.Enabled = false; FreqMintextBox.Enabled = false; FreqMaxtextBox.Enabled = false; StartAcquisitionBtn.Enabled = false; StopAcquisitionBtn.Enabled = true; acquisitionstatus.Text = "Status : Start reading"; acquisitionbar.Style = System.Windows.Forms.ProgressBarStyle.Marquee; _log.Info("Start Data Collection"); } catch (Exception err) { // errorCode = waveformAiCtrl.Stop(); //waveformAiCtrl.Dispose(); SamplingTextbox.Enabled = true; DataLengthtextBox.Enabled = true; ChanneltextBox.Enabled = true; FreqrangetextBox.Enabled = true; DeviceIDtextBox.Enabled = true; FreqMintextBox.Enabled = true; FreqMaxtextBox.Enabled = true; StartAcquisitionBtn.Enabled = true; StopAcquisitionBtn.Enabled = false; acquisitionstatus.Text = "Status : Stop"; acquisitionbar.Style = System.Windows.Forms.ProgressBarStyle.Blocks; _log.Error("Start acquisition failed---" + err.Message); // If something wrong in this execution, print the error code on screen for tracking. MessageBox.Show(err.Message); } }