Exemplo n.º 1
0
        public void Start()
        {
            try
            {
                mQueue.Clear();

                // Verify the Task
                mTask.Control(TaskAction.Verify);

                if (mTask.AIChannels.Count < 1)
                {
                    return;
                }
                //mAsyncResult = mAiReader.BeginReadWaveform(mNumSamplesPerCh, analogInWorker, mTask);

                //mAiReader = new AnalogMultiChannelReader(mTask.Stream);
                //mAiReader.SynchronizeCallbacks = false;

                mAsyncResult = mAiReader.BeginReadMultiSample(mNumSamplesPerCh, analogInWorker, mTask);
            }
            catch (Exception ex)
            {
                var msg = ex.Message;
                throw ex;
            }
        }
Exemplo n.º 2
0
        public void startSampling()
        {
            try
            {
                myTask.Timing.ConfigureSampleClock("", sampleRate, SampleClockActiveEdge.Rising, SampleQuantityMode.ContinuousSamples, 1000);

                //Verify the Task
                myTask.Control(TaskAction.Verify);

                runningTask    = myTask;
                myAnalogReader = new AnalogMultiChannelReader(myTask.Stream);

                myAnalogReader.SynchronizeCallbacks = true;


                myAsyncCallback = new AsyncCallback(AnalogInCallback);
                myAnalogReader.BeginReadMultiSample(Convert.ToInt32(samplesPerCallback), myAsyncCallback,
                                                    myTask);
            }

            catch (Exception exception)
            {
                //Display Errors
                if (MessageBox.Show("Can't connect to USB-DAQ. Continue? ", "Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Error) == DialogResult.Cancel)
                {
                    Environment.Exit(0);
                }
                myTask.Dispose();

                runningTask = null;
            }
        }
Exemplo n.º 3
0
        private void AnalogInCallback(IAsyncResult ar)
        {
            try
            {
                if (runningTask == ar.AsyncState)
                {
                    //Read the available data from the channels
                    data = myAnalogReader.EndReadMultiSample(ar);


                    NewSamplesEventDelegate temp = NewSamplesEvent;
                    if (temp != null)
                    {
                        temp(this, null);
                    }

                    myAnalogReader.BeginReadMultiSample(Convert.ToInt32(samplesPerCallback), myAsyncCallback, myTask);
                }
            }
            catch (DaqException exception)
            {
                //Display Errors
                MessageBox.Show(exception.Message);
                myTask.Dispose();
                runningTask = null;
            }
        }
Exemplo n.º 4
0
/*
 *              public DeviceTaskPack(double sampleRate, string deviceName, string[] channelNames, double[] minVol, double[] maxVol, double[,] wave, TaskDoneEventHandler done) {
 *                      waveArray = wave;
 *                      task = new Task();
 *                      for (int ch = 0; ch < channelNames.Length; ch++) {
 *                              string name = channelNames[ch];
 *                              string vname = "Voltage" + ch;
 *                              task.AOChannels.CreateVoltageChannel(name, vname, minVol[ch], maxVol[ch], AOVoltageUnits.Volts);
 *                      }
 *                      task.Timing.ConfigureSampleClock("", sampleRate, SampleClockActiveEdge.Rising, SampleQuantityMode.FiniteSamples, waveArray.GetLength(1));
 *                      task.Done += done;
 *                      task.Control(TaskAction.Verify);
 *                      aowriter = new AnalogMultiChannelWriter(task.Stream);
 *              }*/
        public void execute()
        {
            task.Control(TaskAction.Start);
            if (aireader != null)
            {
                readAsync = aireader.BeginReadMultiSample(sampleLength, null, null);
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// 用于读AI数据的回调函数
        /// </summary>
        /// <param name="ar"></param>
        private void aiCallback(IAsyncResult ar)
        {
            try
            {
                if (aiTask == ar.AsyncState)
                {
                    if (AIState == Status.Ready)
                    {
                        AIState = Status.Running;
                        //ready -> running
                        OnStatusChanged();
                    }

                    if (aiTask.IsDone)
                    {
                        System.Diagnostics.Debug.WriteLine("任务结束,开始 " + DateTime.Now.ToString("mm-ss.fffffff"));
                        //任务结束,把数据读完
                        double[,] readData = reader.EndReadMultiSample(ar);
                        OnDataArrival(readData);
                        System.Diagnostics.Debug.WriteLine("任务结束,结束 " + DateTime.Now.ToString("mm-ss.fffffff"));
                        //产生任务结束事件
                        //在该事件处理函数中结束当前任务
                        OnStopped();
                    }
                    else
                    {
                        //任务未结束
                        //read data
                        //EndReadMultiSample返回值中第0维代表了通道数,第1维对应各个通道的数据

                        System.Diagnostics.Debug.WriteLine("读取开始 " + testNo + " " + DateTime.Now.ToString("mm-ss.fffffff"));
                        double[,] readData = reader.EndReadMultiSample(ar);
                        System.Diagnostics.Debug.WriteLine("读取结束 " + testNo + " " + DateTime.Now.ToString("mm-ss.fffffff"));
                        //OnDataArrival(new double[, ] { { 1 }, { 1 }, { 1 }, { 1 }, { 1 }, { 1 }, { 1 }, { 1 } , { 1 }, { 1 }, { 1 }, { 1 }, { 1 }, { 1 }, { 1 }, { 1 } });
                        OnDataArrival(readData);
                        System.Diagnostics.Debug.WriteLine("事件结束 " + testNo + " " + DateTime.Now.ToString("mm-ss.fffffff"));

                        testNo++;

                        //iteration
                        reader.BeginReadMultiSample(ReadSamplePerTime, aiReaderCallback, aiTask);
                    }
                }
            }
            catch (DaqException ex)
            {
                //ex.Message
                goError();
                throw ex;
            }
        }
Exemplo n.º 6
0
    public double[,] getChannelsValuesContinuous(int lineStart, int lineStop, int numOfSamples)
    {
        Task      task        = new Task();
        string    devFullname = string.Format("{0}/ai{1}:{2}", name, lineStart, lineStop);
        AIChannel channel     = task.AIChannels.CreateVoltageChannel(devFullname, "", AITerminalConfiguration.Rse, 0.0, 10.0, AIVoltageUnits.Volts);

        task.Start();
        AnalogMultiChannelReader reader = new AnalogMultiChannelReader(task.Stream);
        IAsyncResult             result = reader.BeginReadMultiSample(numOfSamples, null, null); // 2d array 2xN when lineStart=0, lineStop=1

        double[,] values = reader.EndReadMultiSample(result);                                    // 2d array 3xN when lineStart=0, lineStop=2
        task.Stop();
        return(values);
    }
Exemplo n.º 7
0
    public double[,] getChannelValues(int line)
    {
        Task      task        = new Task();
        string    devFullname = string.Format("{0}/ai{1}", name, line);
        AIChannel channel     = task.AIChannels.CreateVoltageChannel(devFullname, "", AITerminalConfiguration.Rse, 0.0, 10.0, AIVoltageUnits.Volts);

        task.Start();
        AnalogMultiChannelReader reader = new AnalogMultiChannelReader(task.Stream);
        IAsyncResult             result = reader.BeginReadMultiSample(1000, null, null);

        double[,] values = reader.EndReadMultiSample(result);
        task.Stop();
        return(values);
    }
Exemplo n.º 8
0
        public override IObservable <Mat> Generate()
        {
            return(Observable.Create <Mat>(observer =>
            {
                var task = new Task();
                foreach (var channel in channels)
                {
                    task.AIChannels.CreateVoltageChannel(channel.PhysicalChannel, channel.ChannelName, channel.TerminalConfiguration, channel.MinimumValue, channel.MaximumValue, channel.VoltageUnits);
                }

                task.Timing.ConfigureSampleClock(SignalSource, SampleRate, ActiveEdge, SampleMode, BufferSize);
                task.Control(TaskAction.Verify);
                var analogInReader = new AnalogMultiChannelReader(task.Stream);
                AsyncCallback analogCallback = null;
                analogCallback = new AsyncCallback(result =>
                {
                    var data = analogInReader.EndReadMultiSample(result);
                    var dataHandle = GCHandle.Alloc(data, GCHandleType.Pinned);
                    try
                    {
                        var output = new Mat(data.GetLength(0), data.GetLength(1), Depth.F64, 1, dataHandle.AddrOfPinnedObject());
                        observer.OnNext(output.Clone());
                        analogInReader.BeginReadMultiSample(SamplesPerRead < 0 ? BufferSize : SamplesPerRead, analogCallback, null);
                    }
                    finally { dataHandle.Free(); }
                });

                analogInReader.SynchronizeCallbacks = true;
                analogInReader.BeginReadMultiSample(SamplesPerRead < 0 ? BufferSize : SamplesPerRead, analogCallback, null);
                return Disposable.Create(() =>
                {
                    task.Stop();
                    task.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();
     }
 }
Exemplo n.º 10
0
        private void analogInCallback(IAsyncResult ar)
        {
            try
            {
                if (running_task != null && running_task == ar.AsyncState)
                {
                    Voltage_Data     = analogreader.EndReadMultiSample(ar);
                    value_for_graphs = Voltage_Data;
                }
                Invoke((MethodInvoker) delegate {
                    textBox9.Text  = Voltage_Data[0, 0].ToString("f3");  //1
                    textBox10.Text = Voltage_Data[1, 0].ToString("f3");  //2
                    textBox11.Text = Voltage_Data[2, 0].ToString("f3");  //3
                    textBox12.Text = Voltage_Data[3, 0].ToString("f3");  //4
                    textBox13.Text = Voltage_Data[4, 0].ToString("f3");  //5
                    textBox14.Text = Voltage_Data[5, 0].ToString("f3");  //6
                    textBox15.Text = Voltage_Data[6, 0].ToString("f3");  //7
                    textBox16.Text = Voltage_Data[7, 0].ToString("f3");  //8
                    textBox17.Text = Voltage_Data[8, 0].ToString("f3");  //9
                    textBox18.Text = Voltage_Data[9, 0].ToString("f3");  //10
                    textBox19.Text = Voltage_Data[10, 0].ToString("f3"); //11
                    textBox20.Text = Voltage_Data[11, 0].ToString("f3"); //12
                    textBox21.Text = Voltage_Data[12, 0].ToString("f3"); //13
                    textBox22.Text = Voltage_Data[13, 0].ToString("f3"); //14
                    textBox23.Text = Voltage_Data[14, 0].ToString("f3"); //15
                    textBox24.Text = Voltage_Data[15, 0].ToString("f3"); //16

                    //Setting depending on the number of Data Acqusition port
                });
                analogreader.BeginReadMultiSample(Convert.ToInt32(textBox8.Text), analogCallback, mytask);
            }
            catch
            {
                MessageBox.Show("Callback_Error");
                running_task = null;
                mytask.Dispose();
            }
        }
Exemplo n.º 11
0
        /// <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();
                    }
                }
            }
        }
Exemplo n.º 12
0
        private void ReadData(IAsyncResult ar)
        {
            try
            {
                if (runningTask != null && runningTask == ar.AsyncState)
                {
                    // Read the data
                    double[,] data = reader.EndReadMultiSample(ar);

                    // Get the channel index
                    int index = 0;

                    if (index < 0 || index >= myTask.AIChannels.Count)
                    {
                        MessageBox.Show("Invalid channel index.");
                        MessageBox.Show(myTask.AIChannels.Count + "");
                        myTask.Dispose();
                        runningTask = null;
                        return;
                    }
                    string DAQinputrange   = InputrangecomboBox.Text;
                    string DAQaisignaltype = ConnecttypecomboBox.Text;
                    convertClkRate = int.Parse(SamplingTextbox.Text);
                    sectionLength  = int.Parse(DataLengthtextBox.Text);
                    startChannel   = int.Parse(ChanneltextBox.Text);
                    bool trigger           = triggerbox.Checked;
                    int  pretriggersamples = int.Parse(pretriggerSamples.Text);
                    // Analyze the data for a start trigger
                    double level           = Convert.ToDouble(levelbox.Text);
                    double window          = Convert.ToDouble(0.1);
                    int    triggerLocation = FindTrigger(data, index, level, window);

                    //buffer setting
                    List <double> pretriggerbuffer = new List <double> {
                    };
                    List <double> currentbuffer    = new List <double> {
                    };
                    List <double> remainbuffer     = new List <double> {
                    };
                    List <double> totaldata        = new List <double> {
                    };

                    // Read the next set of data
                    if (triggerLocation != -1)
                    {
                        // Found a trigger
                        int iDisplay = 0;
                        // Display pretrigger samples
                        if (pretriggersamples > triggerLocation)
                        {
                            // Figure out how many samples we need from the pretrigger buffer
                            int deficit = pretriggersamples - triggerLocation;

                            // Display samples from pretrigger buffer
                            for (int iData = 0; iData < deficit; iData++)
                            {
                                for (int iChan = 0; iChan < myTask.AIChannels.Count; iChan++)
                                {
                                    currentbuffer.Add(pretrigger[iChan, iData + ptSize - deficit]);
                                }

                                iDisplay++;
                            }

                            // Now include all samples up to the trigger location in data
                            for (int iData = 0; iData < triggerLocation; iData++)
                            {
                                for (int iChan = 0; iChan < myTask.AIChannels.Count; iChan++)
                                {
                                    remainbuffer.Add(data[iChan, iData]);
                                }

                                iDisplay++;
                            }
                            foreach (var item in currentbuffer)
                            {
                                totaldata.Add(item);
                            }
                            foreach (var item in remainbuffer)
                            {
                                totaldata.Add(item);
                            }
                            if (ptSaved + triggerLocation > pretriggersamples)
                            {
                                pretriggerAcquiredNumeric.Value = pretriggersamples;
                            }
                            else
                            {
                                pretriggerAcquiredNumeric.Value = ptSaved + triggerLocation;
                            }
                        }
                        else // pretriggerSamples <= triggerLocation
                        {
                            double[,] bufferdata;


                            // We have enough pretrigger samples in the current data array
                            for (int iData = 0; iData < pretriggersamples; iData++)
                            {
                                for (int iChan = 0; iChan < myTask.AIChannels.Count; iChan++)
                                {
                                    pretriggerbuffer.Add(data[iChan, iData + triggerLocation - pretriggersamples]);
                                }

                                iDisplay++;
                            }

                            pretriggerAcquiredNumeric.Value = pretriggersamples;
                        }
                        // Display data after the trigger
                        for (int iData = triggerLocation; iData < sectionLength; iData++)
                        {
                            for (int iChan = 0; iChan < myTask.AIChannels.Count; iChan++)
                            {
                                currentbuffer.Add(data[iChan, iData]);
                            }

                            iDisplay++;
                        }

                        // Read more data
                        data = reader.ReadMultiSample(triggerLocation);
                        // Display additional data after trigger
                        for (int iData = 0; iData < triggerLocation; iData++)
                        {
                            for (int iChan = 0; iChan < myTask.AIChannels.Count; iChan++)
                            {
                                remainbuffer.Add(data[iChan, iData]);
                            }

                            iDisplay++;
                        }

                        foreach (var item in pretriggerbuffer)
                        {
                            totaldata.Add(item);
                        }
                        foreach (var item in currentbuffer)
                        {
                            totaldata.Add(item);
                        }
                        foreach (var item in remainbuffer)
                        {
                            totaldata.Add(item);
                        }
                        DoChart1update(totaldata.ToArray());
                        // Stop the task

                        /*
                         * myTask.Dispose();
                         * startButton.Enabled = true;
                         * stopButton.Enabled = false;
                         * EnableControls(true);
                         * runningTask = null;
                         */
                    }
                    else // triggerLocation == -1
                    {
                        // Trigger not found; save pretrigger samples
                        if (pretriggersamples <= sectionLength)
                        {
                            // Save only one iteration (over all channels)
                            for (int iChan = 0; iChan < myTask.AIChannels.Count; iChan++)
                            {
                                for (int iData = 0; iData < sectionLength; iData++)
                                {
                                    pretrigger[iChan, iData] = data[iChan, iData];
                                }
                            }
                        }
                        else // pretriggerSamples > samples
                        {
                            // Save over multiple iterations
                            int offset = ptSize - sectionLength;

                            // Shift elements in the array (discarding the first samples of data)
                            for (int iChan = 0; iChan < myTask.AIChannels.Count; iChan++)
                            {
                                for (int iData = 0; iData < offset; iData++)
                                {
                                    pretrigger[iChan, iData] = pretrigger[iChan, iData + sectionLength];
                                }
                            }

                            // Copy the new data into the array
                            for (int iChan = 0; iChan < myTask.AIChannels.Count; iChan++)
                            {
                                for (int iData = 0; iData < sectionLength; iData++)
                                {
                                    pretrigger[iChan, iData + offset] = data[iChan, iData];
                                }
                            }
                        }

                        ptSaved += sectionLength;

                        // Read the next set of samples
                        reader.BeginReadMultiSample(Convert.ToInt32(sectionLength), new AsyncCallback(ReadData), myTask);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                myTask.Dispose();
                // Display Errors
                runningTask = null;
            }
        }
Exemplo n.º 13
0
        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);
            }
        }
        public void startSampling()
        {
            try
            {
                myTask.Timing.ConfigureSampleClock("", sampleRate, SampleClockActiveEdge.Rising, SampleQuantityMode.ContinuousSamples, 1000);

                //Verify the Task
                myTask.Control(TaskAction.Verify);

                runningTask = myTask;
                myAnalogReader = new AnalogMultiChannelReader(myTask.Stream);

                myAnalogReader.SynchronizeCallbacks = true;

                myAsyncCallback = new AsyncCallback(AnalogInCallback);
                myAnalogReader.BeginReadMultiSample(Convert.ToInt32(samplesPerCallback), myAsyncCallback,
                    myTask);
            }

            catch (Exception exception)
            {
                //Display Errors
                if (MessageBox.Show("Can't connect to USB-DAQ. Continue? ", "Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Error) == DialogResult.Cancel)
                {
                    Environment.Exit(0);
                }
                myTask.Dispose();

                runningTask = null;
            }
        }