Example #1
0
        private void ConfigureReadAI(int numberOfMeasurements, double sampleRate, bool triggerSense, bool autostart) //AND CAVITY VOLTAGE!!!
        {
            readAIsTask = new Task("readAIsTask");

            foreach (string inputName in analogInputs)
            {
                AnalogInputChannel channel = (AnalogInputChannel)Environs.Hardware.AnalogInputChannels[inputName];
                channel.AddToTask(readAIsTask, 0, 10);
            }

            SampleClockActiveEdge       clockEdge   = SampleClockActiveEdge.Rising;
            DigitalEdgeStartTriggerEdge triggerEdge = triggerSense ? DigitalEdgeStartTriggerEdge.Rising : DigitalEdgeStartTriggerEdge.Falling;

            if (!autostart)
            {
                // Use internal clock
                readAIsTask.Timing.ConfigureSampleClock("", sampleRate, clockEdge, SampleQuantityMode.FiniteSamples, numberOfMeasurements);
                readAIsTask.Triggers.StartTrigger.ConfigureDigitalEdgeTrigger(trigger, triggerEdge);
            }

            readAIsTask.Control(TaskAction.Verify);
            analogReader = new AnalogMultiChannelReader(readAIsTask.Stream);


            // Commiting now apparently saves time when we actually run the task
            readAIsTask.Control(TaskAction.Commit);
        }
Example #2
0
        /// <summary>
        ///     Constructs a DAQ object.
        /// </summary>
        /// <param name="normalChannelId">The channel of the normal force probe</param>
        /// <param name="shearChannelId">The channel of the shear force probe</param>
        public DAQ(string normalChannelId, string shearChannelId)
        {
            Console.WriteLine("RUN INIT");
            //Initialize lists
            dataPoints = new List <dataPoint>();
            start      = DateTime.Now;
            try
            {
                //Define channels
                normalForceChannel = analogInTask.AIChannels.CreateVoltageChannel(normalChannelId,
                                                                                  Constants.NORMALCHANNELNAME, AITerminalConfiguration.Differential, 0, 5, AIVoltageUnits.Volts);
                shearForceChannel = analogInTask.AIChannels.CreateVoltageChannel(shearChannelId,
                                                                                 Constants.SHEARCHANNELNAME, AITerminalConfiguration.Differential, 0, 5, AIVoltageUnits.Volts);

                //Define reader
                reader = new AnalogMultiChannelReader(analogInTask.Stream);

                var dataCollection = new Thread(beginTrial);
                dataCollection.IsBackground = true;
                dataCollection.Start();

                beginTrial();
            }
            catch (DaqException e)
            {
                Console.Write("DAQEXCEPTION: " + e.Message);
                MessageBox.Show(
                    "Failed to connect to force probes. Please check that they are connected properly and that all required drivers are installed.");
                var data = new dataPoint();
                data.time        = -1;
                data.normalForce = 0;
                data.shearForce  = 0;
                dataPoints.Add(data);
            }
        }
        private async System.Threading.Tasks.Task ReadData(NationalInstruments.DAQmx.Task aiTask, int channelCount, int readSamplePerTime)
        {
            await System.Threading.Tasks.Task.Run(() =>
            {
                AnalogMultiChannelReader reader = new AnalogMultiChannelReader(aiTask.Stream);
                int totalReadDataLength         = 0;
                do
                {
                    double[,] readData = new double[channelCount, readSamplePerTime];
                    int actualLength;
                    reader.MemoryOptimizedReadMultiSample(readSamplePerTime, ref readData, ReallocationPolicy.DoNotReallocate, out actualLength);

                    System.Diagnostics.Debug.WriteLine("Data arrival!" + actualLength + " Thread no: " + Thread.CurrentThread.ManagedThreadId.ToString());

                    OnDataArrival(readData);
                    totalReadDataLength += readSamplePerTime;
                    if (AIState == Status.Ready)
                    {
                        //ready -> running
                        AIState = Status.Running;
                    }
                    //当读够数据则停止
                    if (aiTask.IsDone)
                    {
                        OnAITaskStopped();
                        break;
                    }
                }while (true);
            });
        }
Example #4
0
        public override void DoWork(System.ComponentModel.BackgroundWorker worker)
        {
            while (!worker.CancellationPending)
            {
                try
                {
                    this.Connect();

                    using (myTask = new Task())
                    {
                        //Create a virtual channel
                        myTask.AIChannels.CreateVoltageChannel(CHANNEL, Name,
                            AITerminalConfiguration.Rse, Convert.ToDouble(0),
                                Convert.ToDouble(5), AIVoltageUnits.Volts);

                        AnalogMultiChannelReader reader = new AnalogMultiChannelReader(myTask.Stream);

                        //Verify the Task
                        myTask.Control(TaskAction.Verify);
                        double[] data;
                        double angle;
                        while (!worker.CancellationPending)
                        {
                            data = reader.ReadSingleSample();
                            angle = 60.5 * data[0] - 150; //Console.Write(string.Format("{0:0.00}\r", angle));
                            samplebox.Add(angle);
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("{0} Read Failed.\nReason: {1}", Name, e);
                }
            }
        }
Example #5
0
        //The photodiode inputs have been bundled into one task. We never read one photodiode without reading
        //the other.
        public void ConfigureReadAI(int numberOfMeasurements, bool autostart) //AND CAVITY VOLTAGE!!!
        {
            readAIsTask = new Task("readAI");

            channels = new Dictionary <string, AnalogInputChannel>();
            foreach (string s in analogInputs)
            {
                AnalogInputChannel channel = (AnalogInputChannel)Environs.Hardware.AnalogInputChannels[s];
                channels.Add(s, channel);
            }

            foreach (KeyValuePair <string, AnalogInputChannel> pair in channels)
            {
                pair.Value.AddToTask(readAIsTask, 0, 10);
            }

            if (autostart == false)
            {
                readAIsTask.Timing.ConfigureSampleClock(
                    "",
                    40000,
                    SampleClockActiveEdge.Rising,
                    SampleQuantityMode.FiniteSamples, numberOfMeasurements);
                readAIsTask.Triggers.StartTrigger.ConfigureDigitalEdgeTrigger(
                    (string)Environs.Hardware.GetInfo(trigger),
                    DigitalEdgeStartTriggerEdge.Rising);
            }
            readAIsTask.Control(TaskAction.Verify);
            analogReader = new AnalogMultiChannelReader(readAIsTask.Stream);
        }
Example #6
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;
            }
        }
        public DeviceAccession()
        {
            //Az attributumok elérésénél a lockhoz a szinkronizációs objektum
            lockAttributes = new object();

            DAQ = DaqSystem.Local.LoadDevice("Dev1");
            DAQ.SelfCalibrate();

            ditask = new Task();
            dotask = new Task();
            aitask = new Task();

            chLeftEnd = ditask.DIChannels.CreateChannel("Dev1/port0/line0", "Left End", ChannelLineGrouping.OneChannelForEachLine);
            chRightEnd = ditask.DIChannels.CreateChannel("Dev1/port0/line1", "Right End", ChannelLineGrouping.OneChannelForEachLine);

            chMoveToLeft = dotask.DOChannels.CreateChannel("Dev1/port1/line0", "Move to the Left", ChannelLineGrouping.OneChannelForEachLine);
            chMoveToRight = dotask.DOChannels.CreateChannel("Dev1/port1/line1", "Move to the Right", ChannelLineGrouping.OneChannelForEachLine);

            chAngle = aitask.AIChannels.CreateVoltageChannel("Dev1/ai0", "Angle", AITerminalConfiguration.Rse, -10, 10, AIVoltageUnits.Volts);
            chPosition = aitask.AIChannels.CreateVoltageChannel("Dev1/ai1", "Position", AITerminalConfiguration.Rse, -10, 10, AIVoltageUnits.Volts);

            ditask.Start();
            dotask.Start();
            aitask.Start();

            digreader = new DigitalMultiChannelReader(ditask.Stream);
            digwriter = new DigitalMultiChannelWriter(dotask.Stream);
            anreader = new AnalogMultiChannelReader(aitask.Stream);
        }
Example #8
0
        ///* THIS VERSION FOR He/Kr */
        //// this sets up the scanned analog inputs. It's complicated a bit by the fact that
        //// each input would ideally have a different clock rate and gateLength. The board
        //// doesn't support that though.
        //public void MapAnalogInputs()
        //{
        //    inputs = new ScannedAnalogInputCollection();
        //    inputs.RawSampleRate = 100000;
        //    inputs.GateStartTime = (int)scanMaster.GetShotSetting("gateStartTime");
        //    inputs.GateLength = 300;

        //    // this code should be used for normal running
        //    ScannedAnalogInput pmt = new ScannedAnalogInput();
        //    pmt.Channel = (AnalogInputChannel)Environs.Hardware.AnalogInputChannels["pmt"];
        //    pmt.ReductionMode = DataReductionMode.Chop;
        //    pmt.ChopStart = 180;
        //    pmt.ChopLength = 120;
        //    pmt.LowLimit = 0;
        //    pmt.HighLimit = 10;
        //    pmt.Calibration = 0.209145; // calibration from 5-8-08, b14. p52, high gain setting
        //    inputs.Channels.Add(pmt);

        //    ScannedAnalogInput normPMT = new ScannedAnalogInput();
        //    normPMT.Channel = (AnalogInputChannel)Environs.Hardware.AnalogInputChannels["norm"];
        //    normPMT.ReductionMode = DataReductionMode.Chop;
        //    normPMT.ChopStart = 0;
        //    normPMT.ChopLength = 40;
        //    normPMT.LowLimit = 0;
        //    normPMT.HighLimit = 10;
        //    normPMT.Calibration = 0.0406658; // calibration from 5-8-08, b14. p52, high gain setting
        //    inputs.Channels.Add(normPMT);

        //    ScannedAnalogInput mag = new ScannedAnalogInput();
        //    mag.ReductionMode = DataReductionMode.Average;
        //    mag.Channel = (AnalogInputChannel)Environs.Hardware.AnalogInputChannels["magnetometer"];
        //    mag.AverageEvery = 20;
        //    mag.LowLimit = -10;
        //    mag.HighLimit = 10;
        //    mag.Calibration = 0.00001;
        //    inputs.Channels.Add(mag);

        //    ScannedAnalogInput gnd = new ScannedAnalogInput();
        //    gnd.Channel = (AnalogInputChannel)Environs.Hardware.AnalogInputChannels["gnd"];
        //    gnd.ReductionMode = DataReductionMode.Average;
        //    gnd.AverageEvery = 20;
        //    gnd.LowLimit = -1;
        //    gnd.HighLimit = 1;
        //    gnd.Calibration = 1;
        //    inputs.Channels.Add(gnd);

        //    ScannedAnalogInput battery = new ScannedAnalogInput();
        //    battery.Channel = (AnalogInputChannel)Environs.Hardware.AnalogInputChannels["battery"];
        //    battery.ReductionMode = DataReductionMode.Chop;
        //    battery.ChopStart = 180;
        //    battery.ChopLength = 120;
        //    battery.LowLimit = 0;
        //    battery.HighLimit = 10;
        //    battery.Calibration = 1;
        //    inputs.Channels.Add(battery);
        //}
        #endregion

        private void ConfigureSinglePointAnalogInputs()
        {
            // here we configure the scan of analog inputs that happens after each shot.
            singlePointInputTask = new Task("Blockhead single point inputs");
            //Note, thise single points are actually read from HC, so i'll get rid of them
            //AddChannelToSinglePointTask("probePD");
            //AddChannelToSinglePointTask("pumpPD");
            //AddChannelToSinglePointTask("miniFlux1");
            //AddChannelToSinglePointTask("miniFlux2");
            //AddChannelToSinglePointTask("miniFlux3");
            //AddChannelToSinglePointTask("northLeakage");
            AddChannelToSinglePointTask("ground");
            //AddChannelToSinglePointTask("southLeakage");
            //AddChannelToSinglePointTask("ground");

            //singlePointInputTask.Timing.ConfigureSampleClock(
            //        "",
            //        1000,
            //        SampleClockActiveEdge.Rising,
            //        SampleQuantityMode.FiniteSamples,
            //        1
            //     );

            //singlePointInputTask.Triggers.StartTrigger.ConfigureNone();

            if (!Environs.Debug)
            {
                singlePointInputTask.Control(TaskAction.Verify);
            }
            singlePointInputReader = new AnalogMultiChannelReader(singlePointInputTask.Stream);
        }
        //AND CAVITY VOLTAGE!!!
        //The photodiode inputs have been bundled into one task. We never read one photodiode without reading
        //the other.
        public void ConfigureReadAI(int numberOfMeasurements, bool autostart)
        {
            readAIsTask = new Task("readAI");

            channels = new Dictionary<string, AnalogInputChannel>();
            foreach (string s in analogInputs)
            {
                AnalogInputChannel channel = (AnalogInputChannel)Environs.Hardware.AnalogInputChannels[s];
                channels.Add(s, channel);
            }

            foreach (KeyValuePair<string, AnalogInputChannel> pair in channels)
            {
                pair.Value.AddToTask(readAIsTask, 0, 10);
            }

            if (autostart == false)
            {
                 readAIsTask.Timing.ConfigureSampleClock(
                    "",
                    40000,
                    SampleClockActiveEdge.Rising,
                    SampleQuantityMode.FiniteSamples, numberOfMeasurements);
                readAIsTask.Triggers.StartTrigger.ConfigureDigitalEdgeTrigger(
                    (string)Environs.Hardware.GetInfo(trigger),
                    DigitalEdgeStartTriggerEdge.Rising);
            }
            readAIsTask.Control(TaskAction.Verify);
            analogReader = new AnalogMultiChannelReader(readAIsTask.Stream);
        }
Example #10
0
        public void DAQAI()
        {
            //foreach (string s in DaqSystem.Local.Tasks)
            //{
            //    try
            //    {
            //        using (NationalInstruments.DAQmx.Task t = DaqSystem.Local.LoadTask(s))
            //        {
            //            t.Control(TaskAction.Verify);

            //            if (t.AIChannels.Count > 0)
            //            {
            //                AI.Add(s);
            //            }
            //        }
            //    }
            //    catch (DaqException)
            //    {
            //    }
            //}
            //string taskName = AI[0];
            NationalInstruments.DAQmx.Task analogReadTask = DaqSystem.Local.LoadTask("Voltage_Read_Multi");
            AnalogMultiChannelReader       AI_Channel     = new AnalogMultiChannelReader(analogReadTask.Stream);

            do
            {
                Global.AI = AI_Channel.ReadSingleSample();
            } while (exit == false);
        }
Example #11
0
        public void InitializeSidebandRead()
        {
            foreach (string channel in sidebandChannelList)
            {
                ((AnalogInputChannel)Environs.Hardware.AnalogInputChannels[channel]).AddToTask(
                    sidebandMonitorTask,
                    0, 10);
            }

            // internal clock, finite acquisition
            sidebandMonitorTask.Timing.ConfigureSampleClock(
                "",
                sidebandMonitorSampleRate,
                SampleClockActiveEdge.Rising,
                SampleQuantityMode.FiniteSamples,
                sidebandMonitorSamplesPerChannel);

            sidebandMonitorTask.Triggers.StartTrigger.ConfigureDigitalEdgeTrigger(
                (string)Environs.Hardware.GetInfo("usbAnalogTrigger"),
                DigitalEdgeStartTriggerEdge.Rising);

            sidebandMonitorTask.Control(TaskAction.Verify);

            sidebandReader = new AnalogMultiChannelReader(sidebandMonitorTask.Stream);
        }
Example #12
0
        public void ConfigureAI(DAQmxParameters p)
        {
            parameters  = p;
            data        = new DataSet();
            readAIsTask = new Task("readAI");

            for (int i = 0; i < parameters.AINames.Length; i++)
            {
                readAIsTask.AIChannels.CreateVoltageChannel(parameters.AIAddresses[i], parameters.AINames[i], AITerminalConfiguration.Rse, -10, 10, AIVoltageUnits.Volts);
            }

            readAIsTask.Timing.ConfigureSampleClock(
                "",
                parameters.SampleRate,
                SampleClockActiveEdge.Rising,
                SampleQuantityMode.FiniteSamples);

            if (parameters.AutoStart == false)
            {
                readAIsTask.Triggers.StartTrigger.ConfigureDigitalEdgeTrigger(
                    parameters.TriggerAddress,
                    DigitalEdgeStartTriggerEdge.Rising);
            }
            readAIsTask.Stream.Timeout = -1;
            readAIsTask.Control(TaskAction.Verify);
            analogReader = new AnalogMultiChannelReader(readAIsTask.Stream);
        }
Example #13
0
        void ReadThreadRun(AutoResetEvent stop, long maxRead)
        {
            //maxRead < 0 indicates "unlimited" reads
            if (maxRead < 0)
            {
                maxRead = long.MaxValue;
            }
            Task readTask = new Task("EphysRead");

            readTask.AIChannels.CreateVoltageChannel(HardwareSettings.DAQ.DeviceName + "/" + HardwareSettings.DAQ.Ch1Read, "Electrode1", AITerminalConfiguration.Differential, -10, 10, AIVoltageUnits.Volts);
            readTask.AIChannels.CreateVoltageChannel(HardwareSettings.DAQ.DeviceName + "/" + HardwareSettings.DAQ.Ch2Read, "Electrode2", AITerminalConfiguration.Differential, -10, 10, AIVoltageUnits.Volts);
            readTask.AIChannels.CreateVoltageChannel(HardwareSettings.DAQ.DeviceName + "/" + HardwareSettings.DAQ.Ch1ModeRead, "Mode1", AITerminalConfiguration.Differential, -10, 10, AIVoltageUnits.Volts);
            readTask.AIChannels.CreateVoltageChannel(HardwareSettings.DAQ.DeviceName + "/" + HardwareSettings.DAQ.Ch2ModeRead, "Mode2", AITerminalConfiguration.Differential, -10, 10, AIVoltageUnits.Volts);
            readTask.AIChannels.CreateVoltageChannel(HardwareSettings.DAQ.DeviceName + "/" + HardwareSettings.DAQ.Ch1CommandRead, "Command1", AITerminalConfiguration.Differential, -10, 10, AIVoltageUnits.Volts);
            readTask.AIChannels.CreateVoltageChannel(HardwareSettings.DAQ.DeviceName + "/" + HardwareSettings.DAQ.Ch2CommandRead, "Command2", AITerminalConfiguration.Differential, -10, 10, AIVoltageUnits.Volts);
            readTask.AIChannels.CreateVoltageChannel(HardwareSettings.DAQ.DeviceName + "/" + HardwareSettings.DAQ.LaserRead, "LaserRead", AITerminalConfiguration.Differential, -10, 10, AIVoltageUnits.Volts);
            readTask.Timing.ConfigureSampleClock("", HardwareSettings.DAQ.Rate, SampleClockActiveEdge.Rising, SampleQuantityMode.ContinuousSamples);
            long sampleIndex = 0;

            _writeThreadReady.WaitOne();


            try
            {
                readTask.Start();
                AnalogMultiChannelReader dataReader = new AnalogMultiChannelReader(readTask.Stream);


                while (!stop.WaitOne(0) && sampleIndex < maxRead)
                {
                    var nsamples = readTask.Stream.AvailableSamplesPerChannel;

                    if (nsamples >= 10)
                    {
                        double[,] read = dataReader.ReadMultiSample((int)nsamples);
                        var tail_voltages = new Tuple <double, double>(read[0, 0], read[1, 0]);
                        voltage_buffer.Post(tail_voltages);
                        if (ReadDone != null)
                        {
                            ReadDone.Invoke(new ReadDoneEventArgs(read, sampleIndex));
                        }
                        //Update our running index
                        sampleIndex += nsamples;
                    }
                }
            }
            finally
            {
                readTask.Stop();
                readTask.Dispose();
                Console.WriteLine("Got to Pipe Close");
                //Signal to subscribers that we exited
                //Note: Has to be asynchronous so that we leave here before stop gets called
                if (ReadThreadFinished != null)
                {
                    ReadThreadFinished.BeginInvoke(null, null);
                }
            }
        }
Example #14
0
        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;
            }
        }
Example #15
0
        public int ReadAnalogChannel(string lines, string name, AITerminalConfiguration config, ref double[] channelData, double min, double max)
        {
            //Create a task such that it will be disposed after
            //we are done using it.
            Task      analogReadTask = new Task();
            AIChannel ch             = null;

            //channelData = new double[analogReadTask.AIChannels.Count];
            //double[] channelData2 = new double[analogReadTask.AIChannels.Count];
            double[] channelData2 = null;

            if (max == 0)
            {
                max = 10;
            }

            try
            {
                //If min > ai.Minimum And max < ai.Maximum Then
                //Create a virtual channel
                ch = analogReadTask.AIChannels.CreateVoltageChannel(lines, "", config, min, max, AIVoltageUnits.Volts);

                //Verify the Task
                analogReadTask.Control(TaskAction.Verify);
                //InitializeDataTable(myTask.AIChannels, DataTable)

                channelData  = new double[analogReadTask.AIChannels.Count];
                channelData2 = new double[analogReadTask.AIChannels.Count];

                AnalogMultiChannelReader reader = new AnalogMultiChannelReader(analogReadTask.Stream);

                analogReadTask.Start();
                channelData2 = reader.ReadSingleSample();
                analogReadTask.Stop();

                for (int i = 0; i < analogReadTask.AIChannels.Count; i++)
                {
                    Debug.Print(channelData2[0].ToString("#0.00"));
                }
                //return 0;
                //Else

                //End If

                //Update the Acquired Sample Table
                //dataToDataTable(data, DataTable)
                //acquisitionDataGrid.DataSource = DataTable
            }
            catch (DaqException ex) {
                DaqError(ex.Message);
            }
            finally {
                //analogReadTask.Dispose();
                Array.Copy(channelData2, channelData, analogReadTask.AIChannels.Count);
                channelData = channelData2;
            }
            return(0);
        }
Example #16
0
        public void Setup_USB6008()
        {
            //Resets and configures the NI USB6008 Daq boards
            Device dev = DaqSystem.Local.LoadDevice(loc);//added to reset the DAQ boards if they fail to comunicate giving error code 50405

            dev.Reset();
            AIChannel StrainChannel, CurrentChannel;
            AOChannel LateralMotorChannel, TraverseMotorChannel;

            try
            {
                //Setting up NI DAQ for Axial Force Measurment via Strain Circuit and current Measurment of Spindle Motor for torque
                USB6008_AITask = new NationalInstruments.DAQmx.Task();

                StrainChannel = USB6008_AITask.AIChannels.CreateVoltageChannel(
                    loc + "/ai0",                         //Physical name of channel
                    "strainChannel",                      //The name to associate with this channel
                    AITerminalConfiguration.Differential, //Differential Wiring
                    -0.1,                                 //-0.1v minimum
                    NIMaxVolt,                            //1v maximum
                    AIVoltageUnits.Volts                  //Use volts
                    );
                CurrentChannel = USB6008_AITask.AIChannels.CreateVoltageChannel(
                    loc + "/ai1",                         //Physical name of channel
                    "CurrentChannel",                     //The name to associate with this channel
                    AITerminalConfiguration.Differential, //Differential Wiring
                    -0.1,                                 //-0.1v minimum
                    10,                                   //10v maximum
                    AIVoltageUnits.Volts                  //Use volts
                    );
                USB6008_Reader = new AnalogMultiChannelReader(USB6008_AITask.Stream);
                ////////////////////////////////////////////////////////////
                USB6008_AOTask       = new NationalInstruments.DAQmx.Task();
                TraverseMotorChannel = USB6008_AOTask.AOChannels.CreateVoltageChannel(
                    loc + "/ao0",            //Physical name of channel)
                    "TravverseMotorChannel", //The name to associate with this channel
                    0,                       //0v minimum
                    5,                       //5v maximum
                    AOVoltageUnits.Volts
                    );
                LateralMotorChannel = USB6008_AOTask.AOChannels.CreateVoltageChannel(
                    loc + "/ao1",          //Physical name of channel)
                    "LateralMotorChannel", //The name to associate with this channel
                    0,                     //0v minimum
                    5,                     //5v maximum
                    AOVoltageUnits.Volts
                    );
                USB6008_Analog_Writter = new AnalogMultiChannelWriter(USB6008_AOTask.Stream);
                ////////////////////////////////////////////////////////////
                USB6008_DOTask = new NationalInstruments.DAQmx.Task();
                USB6008_DOTask.DOChannels.CreateChannel(loc + "/port0", "port0", ChannelLineGrouping.OneChannelForAllLines);
                USB6008_Digital_Writter = new DigitalSingleChannelWriter(USB6008_DOTask.Stream);
            }
            catch (NationalInstruments.DAQmx.DaqException e)
            {
                Console.WriteLine("Error?\n\n" + e.ToString(), "NI USB 6008 1 Error");
            }
        }
        public override void AcquisitionStarting()
        {
            // configure the analog input
            inputTask1 = new Task("analog gatherer 1 -" /*+ (string)settings["channel"]*/);
            inputTask2 = new Task("analog gatherer 2 -" /*+ (string)settings["channel"]*/);

            // new analog channel, range -10 to 10 volts
            if (!Environs.Debug)
            {
                string   channelList = (string)settings["channel"];
                string[] channels    = channelList.Split(new char[] { ',' });

                foreach (string channel in channels)
                {
                    ((AnalogInputChannel)Environs.Hardware.AnalogInputChannels[channel]).AddToTask(
                        inputTask1,
                        (double)settings["inputRangeLow"],
                        (double)settings["inputRangeHigh"]
                        );
                    ((AnalogInputChannel)Environs.Hardware.AnalogInputChannels[channel]).AddToTask(
                        inputTask2,
                        (double)settings["inputRangeLow"],
                        (double)settings["inputRangeHigh"]
                        );
                }


                // internal clock, finite acquisition
                inputTask1.Timing.ConfigureSampleClock(
                    "",
                    (int)settings["sampleRate"],
                    SampleClockActiveEdge.Rising,
                    SampleQuantityMode.FiniteSamples,
                    (int)settings["gateLength"]);

                inputTask2.Timing.ConfigureSampleClock(
                    "",
                    (int)settings["sampleRate"],
                    SampleClockActiveEdge.Rising,
                    SampleQuantityMode.FiniteSamples,
                    (int)settings["gateLength"]);

                // trigger off PFI0 (with the standard routing, that's the same as trig1)
                inputTask1.Triggers.StartTrigger.ConfigureDigitalEdgeTrigger(
                    (string)Environs.Hardware.GetInfo("analogTrigger0"),
                    DigitalEdgeStartTriggerEdge.Rising);
                // trigger off PFI1 (with the standard routing, that's the same as trig2)
                inputTask2.Triggers.StartTrigger.ConfigureDigitalEdgeTrigger(
                    (string)Environs.Hardware.GetInfo("analogTrigger1"),
                    DigitalEdgeStartTriggerEdge.Rising);

                inputTask1.Control(TaskAction.Verify);
                inputTask2.Control(TaskAction.Verify);
            }
            reader1 = new AnalogMultiChannelReader(inputTask1.Stream);
            reader2 = new AnalogMultiChannelReader(inputTask2.Stream);
        }
Example #18
0
        /// <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;
                    }
                }
            }
        }
 //The photodiode inputs have been bundled into one task. We never read one photodiode without reading
 //the other.
 public void ConfigureReadPhotodiodes(int numberOfMeasurements, bool autostart)
 {
     readPhotodiodesTask   = new Task("ReadPhotodiodes");
     referenceLaserChannel = (AnalogInputChannel)Environs.Hardware.AnalogInputChannels[masterPDChannelName];
     lockingLaserChannel   = (AnalogInputChannel)Environs.Hardware.AnalogInputChannels[slavePDChannelName];
     referenceLaserChannel.AddToTask(readPhotodiodesTask, 0, 10);
     lockingLaserChannel.AddToTask(readPhotodiodesTask, 0, 10);
     readPhotodiodesTask.Control(TaskAction.Verify);
     photodiodesReader = new AnalogMultiChannelReader(readPhotodiodesTask.Stream);
 }
Example #20
0
        void initTask()
        {
            mTask?.Stop();
            mTask?.Dispose();

            // Create a new task
            mTask     = new Task();
            mAiReader = new AnalogMultiChannelReader(mTask.Stream);
            mAiReader.SynchronizeCallbacks = false;
        }
Example #21
0
        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);
        }
Example #22
0
        public int ReadWaveformAnalogChannel(string lines, string name, AITerminalConfiguration config, ref AnalogWaveform <double>[] channelData, double min, double max, int nsamples)
        {
            //Create a task such that it will be disposed after
            //we are done using it.
            Task      analogReadTask = new Task();
            AIChannel ch             = null;

            AnalogWaveform <double>[] channelData2 = new AnalogWaveform <double> [analogReadTask.AIChannels.Count];

            if (max == 0)
            {
                max = 10;
            }
            if (nsamples == 0)
            {
                nsamples = -1;
            }

            try
            {
                //If min > ai.Minimum And max < ai.Maximum Then
                //Create a virtual channel
                ch = analogReadTask.AIChannels.CreateVoltageChannel(lines, "", config, min, max, AIVoltageUnits.Volts);

                //Verify the Task
                analogReadTask.Control(TaskAction.Verify);
                //InitializeDataTable(myTask.AIChannels, DataTable)

                AnalogMultiChannelReader reader = new AnalogMultiChannelReader(analogReadTask.Stream);

                analogReadTask.Start();
                channelData2 = reader.ReadWaveform(nsamples);
                analogReadTask.Stop();

                Debug.Print(String.Format("0x{0:X}", channelData2));
                return(0);
                //Else

                //End If

                //Update the Acquired Sample Table
                //dataToDataTable(data, DataTable)
                //acquisitionDataGrid.DataSource = DataTable
            }
            catch (DaqException ex) {
                DaqError(ex.Message);
            }
            finally {
                analogReadTask.Dispose();
                Array.Copy(channelData2, channelData, analogReadTask.AIChannels.Count);
                channelData = channelData2;
            }
            return(0);
        }
Example #23
0
        // constructor
        public DAQManager(String _device, int [] _channels)
        {
            acquisitionTask = new Task();

            matrixSize = _channels.Length;

            // initialize channels
            for (int i = 0; i < _channels.Length; ++i)
            {
                try
                {
                    acquisitionTask.AIChannels.CreateVoltageChannel(
                        _device + "/ai" + _channels[i].ToString(),
                        "Channel_" + _channels[i].ToString(),
                        (AITerminalConfiguration)(-1),
                        -10,
                        10,
                        AIVoltageUnits.Volts
                        );
                } catch (DaqException de)
                {
                    throw de;
                }
            }

            // initialize Channel Reader
            analogMultiChannelReader = new AnalogMultiChannelReader(acquisitionTask.Stream);

            // set rate to conventional value 0; If not set later (ConfigureContinuousAcquisitionClockRate)
            // a default value will be used for continuous acquisition
            rate = 0;

            // copied from examples
            acquisitionTask.Control(TaskAction.Verify);

            // create condition variable for data available
            dataAvailable = new AutoResetEvent(false);
            // create condition variable for data consumed
            dataConsumed = new AutoResetEvent(true);

            // set callback for continuous acquisition handling
            onContinuousDataAcquiredCallback = new AsyncCallback(OnContinuousDataAcquired);
            analogMultiChannelReader.SynchronizeCallbacks = true;

            // create acquisition lock object
            acquisitionLock = new object();

            // no data at start
            data = null;

            calibrationMatrix = new double[matrixSize, matrixSize];
            biasVector        = new double[matrixSize];
            IsBiasSet         = false;
        }
Example #24
0
 public void addAnalogInputChannels(string[] channelNames, double[] minVol, double[] maxVol)
 {
     for (int ch = 0; ch < channelNames.Length; ch++) {
         string name = channelNames[ch];
         analogInputChannelNameList.Add(channelNames[ch]);
         string vname = "VoltageIn" + ch;
         task.AIChannels.CreateVoltageChannel(name, vname,AITerminalConfiguration.Differential, minVol[ch], maxVol[ch], AIVoltageUnits.Volts);
     }
     aireader = new AnalogMultiChannelReader(task.Stream);
     aireader.SynchronizeCallbacks = false;
 }
Example #25
0
 public void Analog_Disconnect()
 {
     if (task != null)
     {
         task.Dispose();
         task = null;
         if (Reader != null)
         {
             Reader = null;
         }
     }
 }
Example #26
0
 public void addAnalogInputChannels(string[] channelNames, double[] minVol, double[] maxVol)
 {
     for (int ch = 0; ch < channelNames.Length; ch++)
     {
         string name = channelNames[ch];
         analogInputChannelNameList.Add(channelNames[ch]);
         string vname = "VoltageIn" + ch;
         task.AIChannels.CreateVoltageChannel(name, vname, AITerminalConfiguration.Differential, minVol[ch], maxVol[ch], AIVoltageUnits.Volts);
     }
     aireader = new AnalogMultiChannelReader(task.Stream);
     aireader.SynchronizeCallbacks = false;
 }
Example #27
0
        // configure hardware and start the pattern output
        private void AcquisitionStarting()
        {
            // iterate through the channels and ready them
            foreach (SwitchedChannel s in switchedChannels)
            {
                s.AcquisitionStarting();
            }

            // copy running parameters into the BlockConfig
            StuffConfig();

            // prepare the inputs
            inputTask = new Task("BlockHead analog input");

            foreach (ScannedAnalogInput i in inputs.Channels)
            {
                i.Channel.AddToTask(
                    inputTask,
                    i.LowLimit,
                    i.HighLimit
                    );
            }

            inputTask.Timing.ConfigureSampleClock(
                "",
                inputs.RawSampleRate,
                SampleClockActiveEdge.Rising,
                SampleQuantityMode.FiniteSamples,
                inputs.GateLength * inputs.Channels.Count
                );

            inputTask.Triggers.StartTrigger.ConfigureDigitalEdgeTrigger(
                (string)Environs.Hardware.GetInfo("analogTrigger0"),
                DigitalEdgeStartTriggerEdge.Rising
                );

            if (!Environs.Debug)
            {
                inputTask.Control(TaskAction.Verify);
            }
            inputReader = new AnalogMultiChannelReader(inputTask.Stream);

            ConfigureSinglePointAnalogInputs();

            // set the leakage monitor measurement time to 5ms.
            // With this setting it actually takes 26ms total to acquire two channels.
            //hardwareController.LeakageMonitorMeasurementTime = 0.005;
            hardwareController.ReconfigureIMonitors();
            // Start the first asynchronous acquisition
            //hardwareController.UpdateIMonitorAsync();
        }
Example #28
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);
    }
Example #29
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);
    }
Example #30
0
        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);
            }
        }
Example #31
0
        public override void DoWork(BackgroundWorker worker)
        {
            timer.Interval = 100;
            timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Tick);
            timer.Start();

            while (!worker.CancellationPending)
            {
                try
                {
                    this.Connect();

                    System.Console.WriteLine("Initializing DAQ stuff");
                    using (Task myTask = new Task())
                    {
                        //Create a virtual channel
                        myTask.AIChannels.CreateVoltageChannel(Channel, Name,
                            AITerminalConfiguration.Rse, Convert.ToDouble(0),
                                Convert.ToDouble(5), AIVoltageUnits.Volts);
                        AnalogMultiChannelReader reader = new AnalogMultiChannelReader(myTask.Stream);
                        //Verify the Task
                        myTask.Control(TaskAction.Verify);

                        //completed initialization.
                        //Now to read some stuff
                        System.Console.WriteLine("Initialized DAQ stuff");

                        double[] data;
                        double angle;
                        while (!worker.CancellationPending)
                        {
                            if (!sendData) continue;

                            //data = reader.ReadSingleSample();
                            data = DoRead(reader);

                            angle = -(data[0]/(4.4/270) - 270/2);
                            angle /= 2;
                            base.TriggerReadEvent(angle);
                            System.Console.Write("Sending {0:0.00}", Math.Round(angle, 2));
                             sendData = false;
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("{0} Read Failed.\nReason: {1}", Name, e);
                }
            }
        }
Example #32
0
        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;
                }
            }
        }
Example #33
0
        public static void TestSingleAcquisition()
        {
            Task acquisitionTask;

            acquisitionTask = new Task();
            try{
                for (int i = 0; i < 6; ++i)
                {
                    acquisitionTask.AIChannels.CreateVoltageChannel(
                        "Dev2/ai" + i.ToString(),
                        "Acq" + i.ToString(),
                        (AITerminalConfiguration)(-1),
                        -10,
                        10,
                        AIVoltageUnits.Volts
                        );
                }


                /*String[] channelNames = new String[acquisitionTask.AIChannels.Count];
                 * int i = 0;
                 * foreach (AIChannel a in acquisitionTask.AIChannels)
                 * {
                 *  channelNames[i++] = a.PhysicalName;
                 * }*/

                AnalogMultiChannelReader analogMultiChannelReader =
                    new AnalogMultiChannelReader(acquisitionTask.Stream);

                acquisitionTask.Control(TaskAction.Verify);

                double[] data =
                    analogMultiChannelReader.ReadSingleSample();

                foreach (double d in data)
                {
                    Console.WriteLine(d);
                }
            } catch (DaqException de) {
                Console.WriteLine(de);
                System.Threading.Thread.Sleep(1000);
            }


            //Console.WriteLine("Trovato Dispositivo: Dev2/ai0");
            System.Threading.Thread.Sleep(10000);
            Console.ReadLine();
        }
Example #34
0
        public static IEnumerable <double> GetCurrentResults()
        {
            var analogTask = new Task();
            var devices    = DaqSystem.Local.Devices;

            var analogChannels = GetAnalogChannels(devices);

            AddAnalogChannelsToTask(analogTask, analogChannels);
            analogTask.Control(TaskAction.Verify);

            var channelReader = new AnalogMultiChannelReader(analogTask.Stream);

            double[] results = channelReader.ReadSingleSample();

            return(FormatResults(results));
        }
Example #35
0
        static public double[] Read_MultiAi(uint[] linenums)
        {
            using (Task analogReaderTask = new Task())
            {
                //  Create channel and name it.
                for (uint i = 0; i < linenums.Length; i++)
                {
                    string linestr = string.Format("{0}", get_PhysicalAIChannel((int)i));
                    string name    = string.Format("ai{0}", i);
                    analogReaderTask.AIChannels.CreateVoltageChannel(linestr, name, AITerminalConfiguration.Rse, 0, 5, AIVoltageUnits.Volts);
                }
                AnalogMultiChannelReader reader = new AnalogMultiChannelReader(analogReaderTask.Stream);

                double[] values = reader.ReadSingleSample();
                return(values);
            }
        }
Example #36
0
        public NiInterface(string deviceAddress, int sampleFrequency, int seconds)
        {
            //try
            //{
            Seconds = seconds;
            SampleFrequency = sampleFrequency;

            //NationalInstruments.DAQmx.
            // Create a new task
            _myTask = new Task();

            // Create a virtual channel

            AIChannel chan = _myTask.AIChannels.CreateVoltageChannel(deviceAddress, "",
                AITerminalConfiguration.Differential, Convert.ToDouble(-20),
                Convert.ToDouble(20), AIVoltageUnits.Volts);

            // Configure the timing parameters
            _myTask.Timing.ConfigureSampleClock("", SampleFrequency,
                SampleClockActiveEdge.Rising, SampleQuantityMode.FiniteSamples, SampleFrequency * Seconds);

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

            _analogInReader = new AnalogMultiChannelReader(_myTask.Stream);
            _analogCallback = new AsyncCallback(AnalogInCallback);

            _analogInReader.SynchronizeCallbacks = true;

            _singleValueTask = new Task();

            _singleValueTask.AIChannels.CreateVoltageChannel(deviceAddress, "", AITerminalConfiguration.Differential,
                                                           Convert.ToDouble(-10), Convert.ToDouble(10),
                                                           AIVoltageUnits.Volts);

            _singleValueTask.Control(TaskAction.Verify);

            _singleValueReader = new AnalogMultiChannelReader(_singleValueTask.Stream);
            //}
            //catch (Exception ex)
            //{
            //    //MainWindow.ShowError(ex.Message, true);
            //}
        }
Example #37
0
        public override void DoWork(BackgroundWorker worker)
        {
            updateTimer = new System.Timers.Timer();
            updateTimer.Interval = 100;
            updateTimer.Elapsed += new System.Timers.ElapsedEventHandler(UpdateTimer_Tick);
            updateTimer.Start();

            while (!worker.CancellationPending)
            {
                try
                {
                    //this.Connect();

                    System.Console.WriteLine("Initializing DAQ stuff");
                    using (Task myTask = new Task())
                    {
                        //Create a virtual channel
                        myTask.AIChannels.CreateVoltageChannel(Channel, Name,
                            AITerminalConfiguration.Rse, Convert.ToDouble(0),
                                Convert.ToDouble(5), AIVoltageUnits.Volts);
                        AnalogMultiChannelReader reader = new AnalogMultiChannelReader(myTask.Stream);
                        //Verify the Task
                        myTask.Control(TaskAction.Verify);

                        //completed initialization.
                        //Now to read some stuff
                        System.Console.WriteLine("Initialized DAQ stuff");

                        double[] data;
                        while (!worker.CancellationPending)
                        {
                            data = DoRead(reader);
                            signal = Math.Round(data.First(), 2);
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("{0} Read Failed.\nReason: {1}", Name, e);
                }
            }
        }
        public override void AcquisitionStarting()
        {
            // configure the analog input
            inputTask = new Task("analog inputs");

            string[] channels = ((String)settings["channelList"]).Split(',');
            if (!Environs.Debug)
            {
                foreach (string channel in channels)
                {
                    ((AnalogInputChannel)Environs.Hardware.AnalogInputChannels[channel]).AddToTask(
                        inputTask,
                        (double)settings["inputRangeLow"],
                        (double)settings["inputRangeHigh"]
                        );
                    }
                inputTask.Control(TaskAction.Verify);
            }
            reader = new AnalogMultiChannelReader(inputTask.Stream);
        }
 //AND CAVITY VOLTAGE!!!
 //The photodiode inputs have been bundled into one task. We never read one photodiode without reading
 //the other.
 public void ConfigureReadAI(int numberOfMeasurements, bool autostart)
 {
     readAIsTask = new Task("readAI");
     referenceLaserChannel = (AnalogInputChannel)Environs.Hardware.AnalogInputChannels[masterPDChannelName];
     lockingLaserChannel = (AnalogInputChannel)Environs.Hardware.AnalogInputChannels[slavePDChannelName];
     cavityVoltageChannel = (AnalogInputChannel)Environs.Hardware.AnalogInputChannels[cavityReadChannelName];
     referenceLaserChannel.AddToTask(readAIsTask, 0, 10);
     lockingLaserChannel.AddToTask(readAIsTask, 0, 10);
     cavityVoltageChannel.AddToTask(readAIsTask, 0, 10);
     if (autostart == false)
     {
          readAIsTask.Timing.ConfigureSampleClock(
             "",
             66000,
             SampleClockActiveEdge.Rising,
             SampleQuantityMode.FiniteSamples, numberOfMeasurements);
         readAIsTask.Triggers.StartTrigger.ConfigureDigitalEdgeTrigger(
             (string)Environs.Hardware.GetInfo(AITriggerInputName),
             DigitalEdgeStartTriggerEdge.Rising);
     }
     readAIsTask.Control(TaskAction.Verify);
     analogReader = new AnalogMultiChannelReader(readAIsTask.Stream);
 }
Example #40
0
 protected double[] DoRead(AnalogMultiChannelReader reader)
 {
     lock (DAQmx_ADC)
     {
         return reader.ReadSingleSample();
     }
 }
        public override void AcquisitionStarting()
        {
            //remoting connection
            camera = (CameraControllable)Activator.GetObject(typeof(CameraControllable),
              "tcp://localhost:1178/controller.rem");

            // configure the analog input
            inputTask1 = new Task("analog gatherer 1 -" /*+ (string)settings["channel"]*/);
            inputTask2 = new Task("analog gatherer 2 -" /*+ (string)settings["channel"]*/);

            // new analog channel, range -10 to 10 volts
            //			if (!Environs.Debug)
            //			{
            string channelList = (string)settings["channel"];
            string[] channels = channelList.Split(new char[] { ',' });

            foreach (string channel in channels)
            {
                ((AnalogInputChannel)Environs.Hardware.AnalogInputChannels[channel]).AddToTask(
                    inputTask1,
                    (double)settings["inputRangeLow"],
                    (double)settings["inputRangeHigh"]
                    );
                ((AnalogInputChannel)Environs.Hardware.AnalogInputChannels[channel]).AddToTask(
                    inputTask2,
                    (double)settings["inputRangeLow"],
                    (double)settings["inputRangeHigh"]
                    );
            }

            // internal clock, finite acquisition
            inputTask1.Timing.ConfigureSampleClock(
                "",
                (int)settings["sampleRate"],
                SampleClockActiveEdge.Rising,
                SampleQuantityMode.FiniteSamples,
                (int)settings["gateLength"]);
            inputTask2.Timing.ConfigureSampleClock(
                "",
                (int)settings["sampleRate"],
                SampleClockActiveEdge.Rising,
                SampleQuantityMode.FiniteSamples,
                (int)settings["gateLength"]);

            // trigger off PFI0 (with the standard routing, that's the same as trig1, pin 11)
            inputTask1.Triggers.StartTrigger.ConfigureDigitalEdgeTrigger(
                (string)Environs.Hardware.GetInfo("analogTrigger0"),
                DigitalEdgeStartTriggerEdge.Rising);
            // trigger off PFI1 (with the standard routing, that's the same as trig2, pin 10)
            inputTask2.Triggers.StartTrigger.ConfigureDigitalEdgeTrigger(
                (string)Environs.Hardware.GetInfo("analogTrigger1"),
                DigitalEdgeStartTriggerEdge.Rising);

            inputTask1.Control(TaskAction.Verify);
            inputTask2.Control(TaskAction.Verify);

            reader1 = new AnalogMultiChannelReader(inputTask1.Stream);
            reader2 = new AnalogMultiChannelReader(inputTask2.Stream);

             //   camera.PrepareRemoteCameraControl();
        }
        public override void AcquisitionStarting()
        {
            // configure the analog input
            inputTask = new Task("analog gatherer " /*+ (string)settings["channel"]*/);

            // new analog channel, range -10 to 10 volts
            //			if (!Environs.Debug)
            //			{
                string channelList = (string)settings["channel"];
                string[] channels = channelList.Split(new char[] {','});

                foreach (string channel in channels)
                    ((AnalogInputChannel)Environs.Hardware.AnalogInputChannels[channel]).AddToTask(
                        inputTask,
                        (double)settings["inputRangeLow"],
                        (double)settings["inputRangeHigh"]
                        );

                // internal clock, finite acquisition
                inputTask.Timing.ConfigureSampleClock(
                    "",
                    (int)settings["sampleRate"],
                    SampleClockActiveEdge.Rising,
                    SampleQuantityMode.FiniteSamples,
                    (int)settings["gateLength"]);

                inputTask.Triggers.StartTrigger.ConfigureDigitalEdgeTrigger(
                    (string)Environs.Hardware.GetInfo("analogTrigger0"),
                    DigitalEdgeStartTriggerEdge.Rising);

                inputTask.Control(TaskAction.Verify);
            //			}
            reader = new AnalogMultiChannelReader(inputTask.Stream);
        }
Example #43
0
        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();
                    }
                }
            }
        }
Example #44
0
        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();
                }
            }
        }
        private IEnumerable<KeyValuePair<Channel, double[]>> ReadAnalog(IList<Channel> input, int nsamples,
                                                                      CancellationToken token)
        {
            if (input.Count != DAQTasks.AIChannels.Count)
                throw new DaqException("Analog input count must match the number of configured analog channels.");

            int nIn = 0;

            var inputSamples = new double[input.Count, 2 * nsamples];

            int transferBlock = Math.Min(nsamples, TRANSFER_BLOCK_SAMPLES);
            var inputData = new double[input.Count, transferBlock];

            var reader = new AnalogMultiChannelReader(DAQTasks.AIStream);
            var ar = reader.BeginMemoryOptimizedReadMultiSample(transferBlock, null, null, inputData);

            while (nIn < nsamples && input.Any())
            {
                if (token.IsCancellationRequested)
                    break;

                bool blockAvailable = DAQTasks.AIStream.AvailableSamplesPerChannel >= transferBlock;
                if (blockAvailable)
                {
                    int nRead;
                    inputData = reader.EndMemoryOptimizedReadMultiSample(ar, out nRead);

                    for (int i = 0; i < input.Count; i++)
                    {
                        for (int j = 0; j < nRead; j++)
                        {
                            inputSamples[i, nIn + j] = inputData[i, j];
                        }
                    }
                    nIn += nRead;

                    if (nIn < nsamples)
                    {
                        ar = reader.BeginMemoryOptimizedReadMultiSample(transferBlock, null, null, inputData);
                    }
                }
            }

            var result = new Dictionary<Channel, double[]>();
            var chans = DAQTasks.AIChannels.Cast<AIChannel>().ToList();

            foreach (Channel i in input)
            {
                var inData = new double[nIn];
                int chanIndex = chans.FindIndex(c => c.PhysicalName == i.PhysicalName);

                for (int j = 0; j < nIn; j++)
                {
                    inData[j] = inputSamples[chanIndex, j];
                }

                result[i] = inData;
            }

            return result;
        }
        private void StartAcquisition()
        {
            if (runningTask == null)
            {
                try
                {
                    // Create a new task
                    myTask = new Task();

                    // Create a virtual channel
                    myTask.AIChannels.CreateVoltageChannel(channelName, "",
                        (AITerminalConfiguration)(-1), Convert.ToDouble(minimumValue),
                        Convert.ToDouble(maximumValue), AIVoltageUnits.Volts);

                    // Configure the timing parameters
                    myTask.Timing.ConfigureSampleClock("", Convert.ToDouble(sampleRate),
                        SampleClockActiveEdge.Rising, SampleQuantityMode.ContinuousSamples, 1000);

                    // 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(Convert.ToInt32(sampleRead),
                        analogCallback, myTask);

                    bitsPerSample = myTask.AIChannels[0].Resolution;
                }
                catch (DaqException exception)
                {
                    // Display Errors
                    MessageBox.Show(exception.Message);
                    runningTask = null;
                    myTask.Dispose();
                }
            }
        }
        /// <summary>
        /// read data and average it. 
        /// </summary>
        /// <param name="settings"></param>
        /// <param name="worker"></param>
        /// <param name="e"></param>
        /// <returns></returns>
        private double GetDataAfterEachStep(CalibrationSettings settings, BackgroundWorker worker, DoWorkEventArgs e)
        {
            double[,] dataAquired=null;
            AnalogMultiChannelReader reader = new AnalogMultiChannelReader(m_activeTriggeredTask.Stream);

            dataAquired = reader.ReadMultiSample(-1);

            if (settings.ChannelsSettings.ActiveChannels.Count != dataAquired.GetLength(0))
            {
                throw new SBJException("Number of data channels doesn't fit the recieved data.");
            }

            return AverageOverOneRawMatrix(dataAquired);
        }
Example #48
0
        public void WatchTrigger()
        {
            //Create a virtual channel
            using (Task dirTask = new Task())
            {
                dirTask.AIChannels.CreateVoltageChannel("Dev1/ai3", "TriggerRead",
                                AITerminalConfiguration.Rse, Convert.ToDouble(0),
                                    Convert.ToDouble(5), AIVoltageUnits.Volts);
                //initialize the reader
                AnalogMultiChannelReader reader = new AnalogMultiChannelReader(dirTask.Stream);

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

                bool signal = false;

                while (true)
                {
                    signal = (Math.Round(DoRead(reader).First(), 2) > 0);
                    //Console.WriteLine("Shit is:" + DoRead(reader).First());
                    trigger = (signal) ? -1 : 1;
                    Thread.Sleep(50);
                }
            }
        }
Example #49
0
        private static void startButton_Click()
        {
            try
            {
                continuousTask = DaqSystem.Local.LoadTask(taskName);

                runningTask = continuousTask;
                continuousTask.Start();
                reader = new AnalogMultiChannelReader(continuousTask.Stream);

                callBack = new AsyncCallback(ReadCallBack);

                reader.SynchronizeCallbacks = true;
                reader.BeginReadWaveform(Convert.ToInt32(continuousTask.Timing.SamplesPerChannel), callBack, continuousTask);
                while (true)
                {
                }

            }
            catch (DaqException ex)
            {
                continuousTask.Dispose();
            }
        }
        public override void AcquisitionStarting()
        {
            //connect to the hardware controller
            hardwareControl = new DecelerationHardwareControl.Controller();

            // configure the analog input
            inputTask = new Task("analog inputs");

            string[] channels = ((String)settings["channelList"]).Split(',');
            // check whether the lock cavity is in the list
            bool cavityFound = false;
            lockCavityChannel = 0;
            while (!cavityFound && lockCavityChannel < channels.Length)
            {
                if (channels[lockCavityChannel] == "lockcavity") cavityFound = true;
                else lockCavityChannel++;
            }
            // check whether the reference cavity is in the list
            bool refcavityFound = false;
            refCavityChannel = 0;
            while (!refcavityFound && refCavityChannel < channels.Length)
            {
                if (channels[refCavityChannel] == "refcavity") refcavityFound = true;
                else refCavityChannel++;
            }
            if (!Environs.Debug)
            {
                foreach (string channel in channels)
                {
                    ((AnalogInputChannel)Environs.Hardware.AnalogInputChannels[channel]).AddToTask(
                        inputTask,
                        (double)settings["inputRangeLow"],
                        (double)settings["inputRangeHigh"]
                        );
                }
                // Add the lockcavity if it's not already there
                if (!cavityFound)
                {
                    ((AnalogInputChannel)Environs.Hardware.AnalogInputChannels["lockcavity"]).AddToTask(
                        inputTask,
                        (double)settings["inputRangeLow"],
                        (double)settings["inputRangeHigh"]
                        );
                }
                inputTask.Control(TaskAction.Verify);
                // Add the refcavity if it's not already there
                if (!refcavityFound)
                {
                    ((AnalogInputChannel)Environs.Hardware.AnalogInputChannels["refcavity"]).AddToTask(
                        inputTask,
                        (double)settings["inputRangeLow"],
                        (double)settings["inputRangeHigh"]
                        );
                }
                inputTask.Control(TaskAction.Verify);
            }
            reader = new AnalogMultiChannelReader(inputTask.Stream);

            // block the ADC to all other applications
            hardwareControl.AnalogInputsAvailable = false;
        }
        //The photodiode inputs have been bundled into one task. We never read one photodiode without reading
        //the other.
        public void ConfigureReadPhotodiodes(int numberOfMeasurements, bool autostart)
        {
            readPhotodiodesTask = new Task("ReadPhotodiodes");
            referenceLaserChannel = (AnalogInputChannel)Environs.Hardware.AnalogInputChannels[masterPDChannelName];
            lockingLaserChannel = (AnalogInputChannel)Environs.Hardware.AnalogInputChannels[slavePDChannelName];
            referenceLaserChannel.AddToTask(readPhotodiodesTask, 0, 10);
            lockingLaserChannel.AddToTask(readPhotodiodesTask, 0, 10);

            if (!autostart)
            {
                readPhotodiodesTask.Timing.ConfigureSampleClock(
                   "",
                   500,
                   SampleClockActiveEdge.Rising,
                   SampleQuantityMode.FiniteSamples, 2 * numberOfMeasurements);
                readPhotodiodesTask.Triggers.StartTrigger.ConfigureDigitalEdgeTrigger(
                    (string)Environs.Hardware.GetInfo(photodiodeTriggerInputName),
                    DigitalEdgeStartTriggerEdge.Rising);
            }
            readPhotodiodesTask.AIChannels[0].DataTransferMechanism = AIDataTransferMechanism.UsbBulk;
            readPhotodiodesTask.AIChannels[1].DataTransferMechanism = AIDataTransferMechanism.UsbBulk;
            readPhotodiodesTask.Control(TaskAction.Verify);
            photodiodesReader = new AnalogMultiChannelReader(readPhotodiodesTask.Stream);
        }
Example #52
0
        // configure hardware and start the pattern output
        private void AcquisitionStarting()
        {
            // iterate through the channels and ready them
            foreach (SwitchedChannel s in switchedChannels) s.AcquisitionStarting();

            // copy running parameters into the BlockConfig
            StuffConfig();

            // prepare the inputs
            inputTask = new Task("BlockHead analog input");

            foreach (ScannedAnalogInput i in inputs.Channels)
                i.Channel.AddToTask(
                    inputTask,
                    i.LowLimit,
                    i.HighLimit
                    );

            inputTask.Timing.ConfigureSampleClock(
                "",
                inputs.RawSampleRate,
                SampleClockActiveEdge.Rising,
                SampleQuantityMode.FiniteSamples,
                inputs.GateLength * inputs.Channels.Count
                );

            inputTask.Triggers.StartTrigger.ConfigureDigitalEdgeTrigger(
                (string)Environs.Hardware.GetInfo("analogTrigger0"),
                DigitalEdgeStartTriggerEdge.Rising
                );

            if (!Environs.Debug) inputTask.Control(TaskAction.Verify);
            inputReader = new AnalogMultiChannelReader(inputTask.Stream);

            ConfigureSinglePointAnalogInputs();

            // set the leakage monitor measurement time to 5ms.
            // With this setting it actually takes 26ms total to acquire two channels.
            //hardwareController.LeakageMonitorMeasurementTime = 0.005;
            hardwareController.ReconfigureIMonitors();
            // Start the first asynchronous acquisition
            //hardwareController.UpdateIMonitorAsync();
        }
        /// <summary>
        /// This method should be run after setSettings and setSequence to ensure sane data.
        /// </summary>
        /// <param name="listIterationNumber"></param>
        /// <returns></returns>
        public override BufferGenerationStatus generateBuffers(int listIterationNumber)
        {
            lock (remoteLockObj)
            {
                clientFinishedRun = false;

                lock (taskFinishTimeClicks)
                {
                    taskFinishTimeClicks.Clear();
                }

                expectedNumberOfSamplesGenerated = new Dictionary<string, long>();

                try
                {

                    messageLog(this, new MessageEvent("Stopping and cleaning up old tasks."));
                    if (!stopAndCleanupTasks())
                        return BufferGenerationStatus.Failed_Buffer_Underrun;

                    messageLog(this, new MessageEvent("Generating buffers."));
                    if (settings == null)
                    {
                        messageLog(this, new MessageEvent("Unable to generate buffers. Null settings."));
                        displayError();
                        return BufferGenerationStatus.Failed_Settings_Null;
                    }
                    if (sequence == null)
                    {
                        messageLog(this, new MessageEvent("Unable to generate buffers. Null sequence."));
                        displayError();
                        return BufferGenerationStatus.Failed_Sequence_Null;
                    }

                    // This is redundant.
                    sequence.ListIterationNumber = listIterationNumber;

                    #region Generate variable timebase FPGA task

                    if (serverSettings.UseOpalKellyFPGA)
                    {
                        fpgaTasks = new Dictionary<string, FpgaTimebaseTask>();
                        foreach (DeviceSettings fsettings in myServerSettings.myDevicesSettings.Values)
                        {
                            if (fsettings.IsFPGADevice)
                            {
                                if (fsettings.DeviceEnabled)
                                {
                                    if (fsettings.UsingVariableTimebase)
                                    {
                                        if (opalKellyDeviceNames.Contains(fsettings.DeviceName))
                                        {
                                            messageLog(this, new MessageEvent("Creating Variable Timebase Task on fpga device " + fsettings.DeviceName + "."));
                                            int nSegs = 0;
                                            FpgaTimebaseTask ftask = new FpgaTimebaseTask(fsettings,
                                                opalKellyDevices[opalKellyDeviceNames.IndexOf(fsettings.DeviceName)],
                                                sequence,
                                                Common.getPeriodFromFrequency(fsettings.SampleClockRate),
                                                out nSegs,
                                                myServerSettings.UseFpgaRfModulatedClockOutput,
                                                myServerSettings.UseFpgaAssymetricDutyCycleClocking);
                                            fpgaTasks.Add(fsettings.DeviceName, ftask);
                                            messageLog(this, new MessageEvent("...Done (" + nSegs + " segments total)"));
                                        }
                                        else
                                        {
                                            messageLog(this, new MessageEvent("FPGA device " + fsettings.DeviceName + " is not programmed. Please press the refresh hardware button to program it. Or, if variable timebase on this device is not desired, set DeviceEnabled to false in this device's settings."));
                                            messageLog(this, new MessageEvent("Unable to create variable timebase output on FPGA device. Aborting buffer generation."));
                                            displayError();
                                            return BufferGenerationStatus.Failed_Invalid_Data;
                                        }
                                    }
                                }
                            }
                        }
                    }

                    #endregion

                    #region Generate variable timebase clock output task

                    // If a variable timebase is to be generated by a NI digital output,
                    // then generate the variable timebase output task.
                    if (serverSettings.VariableTimebaseOutputChannel != null && serverSettings.VariableTimebaseOutputChannel != "")
                    {
                        messageLog(this, new MessageEvent("Generating Variable Timebase output clock buffer."));

                        bool otherChannelsOnVariableTimebaseDeviceAlsoUsed = false;
                        foreach (HardwareChannel hc in usedDigitalChannels.Values)
                        {
                            // if the digital channel for the variable timebase is also bound to a logical channel,
                            // complain
                            if (hc.physicalChannelName().ToUpper() == serverSettings.VariableTimebaseOutputChannel)
                            {
                                messageLog(this, new MessageEvent("The variable timebase clock output channel also has a sequence-specified channel bound to it. This is not allowed."));
                                displayError();
                                return BufferGenerationStatus.Failed_Invalid_Data;
                            }

                            // detect if the variable timebase output channel is on a device which also has other
                            // used digital channels.
                            if (hc.DeviceName.ToUpper() == HardwareChannel.parseDeviceNameStringFromPhysicalChannelString(serverSettings.VariableTimebaseOutputChannel).ToUpper())
                            {
                                otherChannelsOnVariableTimebaseDeviceAlsoUsed = true;
                            }
                        }

                        // if the variable timebase output is on the same
                        // device as other digital output channels,
                        // then create the variable timebase task
                        // with the fancy function that can create a shared buffer
                        // for the variable timebase and for the digital output.
                        // Otherwise, use the simpler function which cannot.
                        // NOTE: The above comment is currently incorrect. The variable timebase output
                        // cannot currently exist on the same task as other used channels. Atticus will
                        // complain in a descriptive way if this is attempted.
                        if (otherChannelsOnVariableTimebaseDeviceAlsoUsed)
                        {

                            string variableTimebaseOutputDevice = HardwareChannel.parseDeviceNameStringFromPhysicalChannelString(serverSettings.VariableTimebaseOutputChannel);

                            if (!variableTimebaseOutputDevice.Contains("Dev"))
                            {
                                messageLog(this, new MessageEvent("******* You are using a NI device named " + variableTimebaseOutputDevice + ". This does not follow the convention of naming your devices Dev1, Dev2, Dev3, etc. Unpredictable results are possible! Not recommended! *******"));
                                displayError();
                            }

                            // NOTE! This call will modify useDigitalChannels. Those digital channels which
                            // get their buffers generated within this task will be removed. This is useful,
                            // because we may later in generateBuffers() do another
                            // call to generate another task on this device, but
                            // we want that call to only generate buffers for the remaining digital channels.

                            int nDigitals = usedDigitalChannels.Count;

                            if (myServerSettings.myDevicesSettings.ContainsKey(variableTimebaseOutputDevice))
                            {
                                messageLog(this, new MessageEvent("Variable timebase output device [" + variableTimebaseOutputDevice + "]"));

                                variableTimebaseClockTask = DaqMxTaskGenerator.createDaqMxDigitalOutputAndVariableTimebaseSource(
                                    serverSettings.VariableTimebaseOutputChannel,
                                    null,
                                    serverSettings.VariableTimebaseMasterFrequency,
                                    sequence,
                                    serverSettings.VariableTimebaseType,
                                    variableTimebaseOutputDevice,
                                    serverSettings.myDevicesSettings[variableTimebaseOutputDevice],
                                    settings,
                                    usedDigitalChannels,
                                    serverSettings);
                            }
                            else
                            {
                                messageLog(this, new MessageEvent("***** Server does not contain device named " + variableTimebaseOutputDevice));
                                displayError();
                                return BufferGenerationStatus.Failed_Invalid_Data;
                            }

                            variableTimebaseClockTask.Done += new TaskDoneEventHandler(aTaskFinished);

                            int consumedChannels = nDigitals - usedDigitalChannels.Count;
                            messageLog(this, new MessageEvent(consumedChannels.ToString() + " output buffers also generated. Note, buffer generation on device " + variableTimebaseOutputDevice + " may skip due to no additional channels."));
                        }
                        else
                        {

                            string variableTimebaseOutputDevice = HardwareChannel.parseDeviceNameStringFromPhysicalChannelString(serverSettings.VariableTimebaseOutputChannel);

                            if (myServerSettings.myDevicesSettings.ContainsKey(variableTimebaseOutputDevice))
                            {
                                messageLog(this, new MessageEvent("Variable timebase output device [" + variableTimebaseOutputDevice + "]"));

                                variableTimebaseClockTask = DaqMxTaskGenerator.createDaqMxVariableTimebaseSource(
                                    serverSettings.VariableTimebaseOutputChannel,
                                    serverSettings.VariableTimebaseMasterFrequency,
                                    sequence,
                                    serverSettings.VariableTimebaseType,
                                    serverSettings,
                                    serverSettings.myDevicesSettings[variableTimebaseOutputDevice]);
                            }
                            else
                            {
                                messageLog(this, new MessageEvent("***** Server does not contain device named " + variableTimebaseOutputDevice));
                                displayError();
                                return BufferGenerationStatus.Failed_Invalid_Data;
                            }

                            variableTimebaseClockTask.Done += new TaskDoneEventHandler(aTaskFinished);
                        }

                        try
                        {

                            messageLog(this, new MessageEvent("Variable timebase output clock buffer generated successfully. " + variableTimebaseClockTask.Stream.Buffer.OutputBufferSize + " samples per channel. On board buffer size: " + variableTimebaseClockTask.Stream.Buffer.OutputOnBoardBufferSize + " samples per channel."));
                        }
                        catch (Exception)
                        {
                            messageLog(this, new MessageEvent("Unable to poll task for buffer information. This is probably not a problem."));
                        }
                    }
                    else
                    {
                        variableTimebaseClockTask = null;
                    }

                    #endregion

                    #region Analog and Digital NI device generation (daqMx)

                    /// Is multi-threaded buffer generation enabled?
                    if (!serverSettings.UseMultiThreadedDaqmxBufferGeneration)
                    {
                        // if not, generate each buffer sequentially, in this thread.
                        foreach (string dev in usedDaqMxDevices)
                        {
                            if (!dev.Contains("Dev"))
                            {
                                messageLog(this, new MessageEvent("******* You are using a NI device named " + dev + ". This does not follow the convention of naming your devices Dev1, Dev2, Dev3, etc. Unpredictable results are possible! Not recommended! *******"));
                                displayError();
                            }

                            generateDaqMxTaskOnDevice(dev);
                        }
                    }
                    else
                    {
                        // if yes, generate each buffer in a parallel thread.

                        List<Thread> generateThreads = new List<Thread>();
                        try
                        {

                            messageLog(this, new MessageEvent("Generating buffers in parallel..."));
                            foreach (string dev in usedDaqMxDevices)
                            {
                                if (!dev.Contains("Dev"))
                                {
                                    messageLog(this, new MessageEvent("******* You are using a NI device named " + dev + ". This does not follow the convention of naming your devices Dev1, Dev2, Dev3, etc. Unpredictable results are possible! Not recommended! *******"));
                                    displayError();
                                }
                                Thread thread = new Thread(generateDaqMxTaskOnDevice);
                                generateThreads.Add(thread);

                                thread.Start(dev);
                            }
                            // wait for threads to all complete.

                            foreach (Thread thread in generateThreads)
                            {
                                thread.Join();
                            }
                            messageLog(this, new MessageEvent("...done."));
                        }
                        finally
                        {
                            foreach (Thread thread in generateThreads)
                            {
                                thread.Abort();
                            }
                        }

                    }

                    #endregion

                    // This is where the analog input task is defined
                    #region Analog In Task

                    //First we determine if an analog in task should be created
                    foreach (DeviceSettings ds in AtticusServer.server.serverSettings.myDevicesSettings.Values)
                    {
                        analogInCardDetected |= (ds.DeviceDescription.Contains("6259") || ds.DeviceDescription.Contains("6363")) && ds.AnalogInEnabled; // program will also support PXIe-6363 cards
                    }

                    if (analogInCardDetected)
                    {
                        // Creates the analog in task
                        analogS7ReadTask = new Task();
                        analogS7ReadTask.SynchronizeCallbacks = false;
                        analog_in_names = new List<string>();
                        // bool isUsed; // adareau : now obsolete

                        #region Old Code
                       // // Obtains a list of the analog in channels to be included in the task, and their name
                       // AnalogInChannels the_channels = AtticusServer.server.serverSettings.AIChannels[0];
                       // AnalogInNames the_names = AtticusServer.server.serverSettings.AINames[0];

                       //// We use part of the channels as single ended, and part as differential. He channels are added here. The task is created on Slot 7. This shouldn't be hard coded and will be changed.
                       // #region Single ended
                       // for (int analog_index = 0; analog_index < 10; analog_index++)
                       // {
                       //     PropertyInfo the_channel = the_channels.GetType().GetProperty("AS" + analog_index.ToString());
                       //     isUsed = (bool)the_channel.GetValue(the_channels, null);
                       //     if (isUsed)
                       //     {
                       //         if (analog_index < 5)
                       //         {
                       //             analogS7ReadTask.AIChannels.CreateVoltageChannel("PXI1Slot7/ai" + analog_index.ToString(), "",
                       //                 AITerminalConfiguration.Nrse, -10, 10, AIVoltageUnits.Volts);
                       //         }
                       //         else
                       //         {
                       //             analogS7ReadTask.AIChannels.CreateVoltageChannel("PXI1Slot7/ai" + (analog_index + 3).ToString(), "",
                       //                 AITerminalConfiguration.Nrse, -10, 10, AIVoltageUnits.Volts);
                       //         }
                       //         string theName = (string)(the_names.GetType().GetProperty("AS" + analog_index.ToString()).GetValue(the_names, null));
                       //         if (theName == "")
                       //             analog_in_names.Add("AIS" + analog_index.ToString());
                       //         else
                       //             analog_in_names.Add(theName);
                       //     }
                       // }
                       // #endregion

                       // #region Differential
                       // for (int analog_index = 0; analog_index < 11; analog_index++)
                       // {
                       //     PropertyInfo the_channel = the_channels.GetType().GetProperty("AD" + NamingFunctions.number_to_string(analog_index, 2));
                       //     isUsed = (bool)the_channel.GetValue(the_channels, null);

                       //     if (isUsed)
                       //     {
                       //         if (analog_index < 3)
                       //         {
                       //             analogS7ReadTask.AIChannels.CreateVoltageChannel("PXI1Slot7/ai" + (analog_index + 5).ToString(), "",
                       //                 AITerminalConfiguration.Differential, -10, 10, AIVoltageUnits.Volts);
                       //         }
                       //         else
                       //         {
                       //             analogS7ReadTask.AIChannels.CreateVoltageChannel("PXI1Slot7/ai" + (analog_index + 13).ToString(), "",
                       //                 AITerminalConfiguration.Differential, -10, 10, AIVoltageUnits.Volts);
                       //         }
                       //         string theName = (string)(the_names.GetType().GetProperty("AD" + NamingFunctions.number_to_string(analog_index, 2)).GetValue(the_names, null));
                       //         if (theName == "")
                       //             analog_in_names.Add("AID" + analog_index.ToString());
                       //         else
                       //             analog_in_names.Add(theName);
                       //     }
                       // }
                       // #endregion

                        #endregion

                        #region New Code

                        List<AnalogInChannels> channels_list = AtticusServer.server.serverSettings.AIChannels;

                        foreach (AnalogInChannels aiChannel in channels_list)
                        {
                            if (aiChannel.UseChannel)
                            {
                                if (aiChannel.AnalogInChannelType == AnalogInChannels.AnalogInChannelTypeList.SingleEnded)
                                {
                                    analogS7ReadTask.AIChannels.CreateVoltageChannel(AtticusServer.server.serverSettings.AIDev + "/" + aiChannel.ChannelName, "",
                                      AITerminalConfiguration.Nrse, -10, 10, AIVoltageUnits.Volts);
                                }

                                else if (aiChannel.AnalogInChannelType == AnalogInChannels.AnalogInChannelTypeList.Differential)
                                {
                                    analogS7ReadTask.AIChannels.CreateVoltageChannel(AtticusServer.server.serverSettings.AIDev + "/" + aiChannel.ChannelName, "",
                                     AITerminalConfiguration.Differential, -10, 10, AIVoltageUnits.Volts);
                                }

                                string theName = aiChannel.SaveName;
                                analog_in_names.Add(theName);

                            }

                        }

                        #endregion

                        // Configure timing specs of the analog In task. Again these things shouldn't be hard coded and will be changed
                        analogS7ReadTask.Timing.ConfigureSampleClock("", (double)(AtticusServer.server.serverSettings.AIFrequency), SampleClockActiveEdge.Rising,
                            SampleQuantityMode.FiniteSamples, sequence.nSamples(1 / ((double)(AtticusServer.server.serverSettings.AIFrequency))));

                        //analogS7ReadTask.Timing.ReferenceClockSource = "/PXI1Slot7/PXI_Trig7"; // adareau : with my configuration, declaring a ReferenceClockSource was generating errors. I remove this for now...

                        if (AtticusServer.server.serverSettings.UseAITaskTriggering) //AD
                        {

                            DigitalEdgeStartTriggerEdge triggerEdge = DigitalEdgeStartTriggerEdge.Rising;  // AD : see below
                            analogS7ReadTask.Triggers.StartTrigger.ConfigureDigitalEdgeTrigger(AtticusServer.server.serverSettings.AITriggerSource, triggerEdge); // AD : to fix synchronization problem between analog in and output tasks, I trigger
                                                                                                                                                                 //  the analog in task, using the variable timebase source signal (available on PXI_Trig0)
                                                                                                                                                                 // the task starts with the first signal sent by the VT source...
                        }
                        analogS7ReadTask.Timing.ReferenceClockRate = 20000000;
                        analogS7ReadTask.Stream.Timeout = Convert.ToInt32(sequence.SequenceDuration * 1000) + 10000;

                        reader_analog_S7 = new AnalogMultiChannelReader(analogS7ReadTask.Stream);

                    }
                    #endregion

                    #region Watchdog Timer stuff -- NOT FINISHED YET, THUS COMMENTED OUT

                    if (serverSettings.UseWatchdogTimerMonitoringTask)
                    {
                        messageLog(this, new MessageEvent("Watchdog Timer tasks no longer supported. Ignoring serverSettings.UseWatchdogTimerMonitoringTask"));
                        /*
                        if (daqMxTasks.ContainsKey(serverSettings.DeviceToSyncSoftwareTimedTasksTo))
                        {
                            messageLog(this, new MessageEvent("Creating watchdog timer monitoring task"));
                            WatchdogTimerTask wtask = new WatchdogTimerTask(sequence, myServerSettings.myDevicesSettings[serverSettings.DeviceToSyncSoftwareTimedTasksTo].SampleClockRate, daqMxTasks[serverSettings.DeviceToSyncSoftwareTimedTasksTo], .2);
                        }
                        else
                        {
                            messageLog(this, new MessageEvent("Unable to create watchdog timer monitoring task, since the hardware-timed device it was to be synched to is not being used. Continuing without watchdog."));
                        }*/
                    }

                    #endregion

                    #region GPIB device and masquerading gpib channels (like rfsg channels)

                    foreach (int gpibID in usedGpibChannels.Keys)
                    {
                        HardwareChannel gpibChannel = usedGpibChannels[gpibID];
                        if (!gpibChannel.gpibMasquerade)
                        {
                            messageLog(this, new MessageEvent("Generating gpib buffer for gpib ID " + gpibID));

                            NationalInstruments.NI4882.Device gpibDevice = new NationalInstruments.NI4882.Device(
                                gpibChannel.gpibBoardNumber(),
                                new NationalInstruments.NI4882.Address(gpibChannel.GpibAddress.PrimaryAddress, gpibChannel.GpibAddress.SecondaryAddress));
                            GpibTask gpibTask = new GpibTask(gpibDevice);
                            gpibTask.generateBuffer(sequence, myServerSettings.myDevicesSettings[gpibChannel.DeviceName],
                                gpibChannel, gpibID, myServerSettings.GpibRampConverters);
                            gpibTask.Done += new TaskDoneEventHandler(aTaskFinished);
                            gpibTasks.Add(gpibChannel, gpibTask);
                            messageLog(this, new MessageEvent("Done."));

                        }
                        else
                        {
                            switch (gpibChannel.myGpibMasqueradeType)
                            {
                                case HardwareChannel.GpibMasqueradeType.NONE:
                                    messageLog(this, new MessageEvent("********** Error. GPIB channel with ID " + gpibID + " has its masquerading bit set to true, but has its masquerading type set to NONE. **********"));
                                    displayError();
                                    break;
                                case HardwareChannel.GpibMasqueradeType.RFSG:
                                    messageLog(this, new MessageEvent("Generating RFSG buffer for gpib ID " + gpibID));
                                    RfsgTask rftask = new RfsgTask(sequence, settings, gpibID, gpibChannel.DeviceName, serverSettings.myDevicesSettings[gpibChannel.DeviceName]);
                                    rftask.Done += new TaskDoneEventHandler(aTaskFinished);
                                    rfsgTasks.Add(gpibChannel, rftask);
                                    messageLog(this, new MessageEvent("Done."));
                                    break;
                            }
                        }
                    }

                    #endregion

                    #region RS 232 Devices
                    foreach (int rs232ID in usedRS232Channels.Keys)
                    {
                        if (sequence.rs232ChannelUsed(rs232ID))
                        {
                            messageLog(this, new MessageEvent("Generating rs232 buffer for rs232 ID " + rs232ID));
                            HardwareChannel hc = usedRS232Channels[rs232ID];
                            //NationalInstruments.VisaNS.SerialSession device = new NationalInstruments.VisaNS.SerialSession(hc.ChannelName);

                            NationalInstruments.VisaNS.SerialSession device;

                            try
                            {
                                device = getSerialSession(hc);
                            }
                            catch (Exception e)
                            {
                                messageLog(this, new MessageEvent("Caught exception when attempting to open serial device for rs232 channel #" + rs232ID + ". Exception: " + e.Message + e.StackTrace));
                                return BufferGenerationStatus.Failed_Out_Of_Memory;
                            }

                            //                NationalInstruments.VisaNS.RegisterBasedSession device = (NationalInstruments.VisaNS.RegisterBasedSession) NationalInstruments.VisaNS.ResourceManager.GetLocalManager().Open(hc.ChannelName);

                            RS232Task rs232task = new RS232Task(device);
                            rs232task.generateBuffer(sequence, myServerSettings.myDevicesSettings["Serial"], hc, rs232ID);
                            rs232task.Done += new TaskDoneEventHandler(aTaskFinished);
                            rs232Tasks.Add(hc, rs232task);
                            messageLog(this, new MessageEvent("Done."));
                        }
                        else
                        {
                            messageLog(this, new MessageEvent("Skipping rs232 channel ID " + rs232ID + ", that channel is not used in this sequence."));
                        }
                    }

                    #endregion

                    makeTerminalConnections();

                    // Try to clean up as much memory as possible so that there wont be any garbage collection
                    // during the run. Suspect that GCs during the run may be the cause of sporadic buffer underruns.
                    // Note: This is likely wrong. Most of these buffer underruns were eventually fixed with the
                    // data transfer mechanism tweaks described in the user manual. However, no harm in doing some
                    // GC here.
                    System.GC.Collect();
                    System.GC.Collect();
                    System.GC.Collect();
                    System.GC.WaitForPendingFinalizers();

                    messageLog(this, new MessageEvent("Buffers generated succesfully."));

                    return BufferGenerationStatus.Success;

                }
                catch (Exception e)
                {
                    messageLog(this, new MessageEvent("Failed buffer generation due to exception: " + e.Message + "\n" + e.StackTrace));
                    displayError();
                    return BufferGenerationStatus.Failed_Invalid_Data;
                }
            }
        }
Example #54
0
        public override void DoWork(BackgroundWorker worker)
        {
            while (!worker.CancellationPending)
            {
                try
                {
                    //connect to the server first.
                    this.Connect();
                    this.SetupClock();
                    if (FORWARD_ONLY)
                    {
                        this.StartTriggerWatcher();
                    }

                    using (myTask = new Task())
                    {
                        //Create a virtual channel
                        myTask.AIChannels.CreateCurrentChannel(Channel, Name,
                            AITerminalConfiguration.Rse, Convert.ToDouble(-0.004),
                                Convert.ToDouble(0.004), SHUNT_RESISTANCE, AICurrentUnits.Amps);

                        //initialize the reader
                        AnalogMultiChannelReader reader = new AnalogMultiChannelReader(myTask.Stream);

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

                        //initialize loop parameters and start timers.
                        double[] previousData = null;
                        stopwatch.Start();
                        updateTimer.Start();

                        //keep reading
                        while (!worker.CancellationPending)
                        {
                            //double[] data = reader.ReadSingleSample();
                            double[] data = DoRead(reader);

                            //Console.Write("\r({0})", data[0]);

                            //TODO: Add computations for direction.             SUCKSEED
                            //TODO: Find a way to check for zero-speed.         SUCKSEED
                            //TODO: Fix the interval vs. absolute time issue.   SUCKSEED

                            //check if sample is different.
                            if (!data.InSampleWindow(previousData))
                            {
                                //get the current time and store the elapsed stuff.
                                State currentState = GetState(data[0]);
                                if (currentState != PreviousState)
                                {
                                    //put in the elapsed time in seconds.
                                    Metrics[PreviousState] = (stopwatch.ElapsedMilliseconds - lastUpdate);

                                    //ensure that no anomalies in read times b/n north and south pulses occur.
                                    if (Direction == Direction.Forward && currentState == State.SouthState)
                                    {
                                        if (Metrics[State.SouthState] > Metrics[State.NorthState])
                                        {
                                            Metrics[State.SouthState] = Metrics[State.NorthState] - 1;
                                        }
                                    }
                                    else if (Direction == Direction.Backward && currentState == State.NorthState)
                                    {
                                        if (Metrics[State.NorthState] > Metrics[State.SouthState])
                                        {
                                            Metrics[State.NorthState] = Metrics[State.SouthState] - 1;
                                        }
                                    }

                                    lastUpdate = stopwatch.ElapsedMilliseconds;
                                    PreviousState = currentState;

                                    //calculate the direction and speed.
                                    CalculateVelocity();
                                }

                                //assign reference values
                                previousData = data;
                            }
                            else if ((stopwatch.ElapsedMilliseconds - lastUpdate) > INACTIVITY_THRESHOLD)
                            {
                                //when inactivity time is exceeded, set it to zero.
                                CurrentSpeed = 0d;
                                lastUpdate = stopwatch.ElapsedMilliseconds;

                                //add to the samplebox
                                samplebox.Add(FORWARD_ONLY ? CurrentSpeed : CurrentSpeed);
                            }
                        }
                    }
                }
                catch (DaqException e){
                    Console.WriteLine(e.Message);
                }
                catch (Exception e) { Console.WriteLine(e.Message); }
            }
        }
Example #55
0
        public void InitializeSidebandRead()
        {
            foreach (string channel in sidebandChannelList)
                ((AnalogInputChannel)Environs.Hardware.AnalogInputChannels[channel]).AddToTask(
                    sidebandMonitorTask,
                    0, 10);

            // internal clock, finite acquisition
            sidebandMonitorTask.Timing.ConfigureSampleClock(
                "",
                sidebandMonitorSampleRate,
                SampleClockActiveEdge.Rising,
                SampleQuantityMode.FiniteSamples,
                sidebandMonitorSamplesPerChannel);

            sidebandMonitorTask.Triggers.StartTrigger.ConfigureDigitalEdgeTrigger(
                (string)Environs.Hardware.GetInfo("usbAnalogTrigger"),
                DigitalEdgeStartTriggerEdge.Rising);

            sidebandMonitorTask.Control(TaskAction.Verify);

            sidebandReader = new AnalogMultiChannelReader(sidebandMonitorTask.Stream);
        }
Example #56
0
        private void startButton_Click(object sender, EventArgs e)
        {
            try
            {
                //  Update the UI.
                startButton.Enabled = false;
                stopButton.Enabled = true;
                bufNumTextBox.Text = "";
                //pixelValTextBox.Text = "";
                interfaceTextBox.Enabled = false;
                numImages.Enabled = false;
                volumeDepthTextBox.Enabled = false;
                thresholdDeltaVoltageTextBox.Enabled = false;
#if ACQDATA
                // TODO: Params from UI
                // Create a new task
                myTask = new Task();
                physicalChannelText = "Dev1/ai0";
                minimumValue = -10.00;
                maximumValue = 10.00;
                rateValue = 10000.00;
                samplesPerChannelValue = 1000;

                // Create a virtual channel
                myTask.AIChannels.CreateVoltageChannel(physicalChannelText, "",
                    (AITerminalConfiguration)(-1), Convert.ToDouble(minimumValue),
                    Convert.ToDouble(maximumValue), AIVoltageUnits.Volts);

                analogInReader = new AnalogMultiChannelReader(myTask.Stream);

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

                //  Create a session.
                _session = new ImaqSession(interfaceTextBox.Text);

                //  Configure the image viewer.
                displayImage = new VisionImage((ImageType)_session.Attributes[ImaqStandardAttribute.ImageType].GetValue());
                imageViewer.Attach(displayImage);

                //  Create a buffer collection for the acquisition with the requested
                //  number of images, and configure the buffers to loop continuously.
                int numberOfImages = (int)numImages.Value;
                bufList = _session.CreateBufferCollection(numberOfImages, ImaqBufferCollectionType.PixelValue2D);
                for (int i = 0; i < bufList.Count; ++i)
                {
                    bufList[i].Command = (i == bufList.Count - 1) ? ImaqBufferCommand.Loop : ImaqBufferCommand.Next;
                }

                //  Configure and start the acquisition.
                _session.Acquisition.Configure(bufList);
                _session.Acquisition.AcquireAsync();

                _thresholdDeltaVoltage = Convert.ToDouble(thresholdDeltaVoltageTextBox.Text);
                _volumeDepth = Convert.ToInt32(volumeDepthTextBox.Text);
#endif

                RenderUIArgs renderUIArgs;
                renderUIArgs.rotxTextBox = rotxTextBox;
                renderUIArgs.rotyTextBox = rotyTextBox;
                renderUIArgs.rotzTextBox = rotzTextBox;
                renderUIArgs.transxTextBox = transxTextBox;
                renderUIArgs.transyTextBox = transyTextBox;
                renderUIArgs.transzTextBox = transzTextBox;
                renderUIArgs.densityTextBox = densityTextBox;
                renderUIArgs.brightnessTextBox = brightnessTextBox;
                renderUIArgs.transoffsetTextBox = transoffsetTextBox;
                renderUIArgs.transscaleTextBox = transscaleTextBox;
                renderUIArgs.linfilterCheckBox = linfilterCheckBox;

                //  Start the background worker threads
                acquisitionWorker.RunWorkerAsync(subCheckBox);
                renderWorker.RunWorkerAsync(renderUIArgs);
            }
            catch (ImaqException ex)
            {
                MessageBox.Show(ex.Message, "NI-IMAQ Error");
                Cleanup();
            }
            catch (FormatException ex)
            {
                MessageBox.Show(ex.Message, "Format Error");
                Cleanup();
            }
        }
Example #57
0
        private void ConfigureSinglePointAnalogInputs()
        {
            // here we configure the scan of analog inputs that happens after each shot.
            singlePointInputTask = new Task("Blockhead single point inputs");
            //Note, thise single points are actually read from HC, so i'll get rid of them
            //AddChannelToSinglePointTask("probePD");
            //AddChannelToSinglePointTask("pumpPD");
            //AddChannelToSinglePointTask("miniFlux1");
            //AddChannelToSinglePointTask("miniFlux2");
            //AddChannelToSinglePointTask("miniFlux3");
            //AddChannelToSinglePointTask("northLeakage");
            AddChannelToSinglePointTask("ground");
            //AddChannelToSinglePointTask("southLeakage");
            //AddChannelToSinglePointTask("ground");

            //singlePointInputTask.Timing.ConfigureSampleClock(
            //        "",
            //        1000,
            //        SampleClockActiveEdge.Rising,
            //        SampleQuantityMode.FiniteSamples,
            //        1
            //     );

            //singlePointInputTask.Triggers.StartTrigger.ConfigureNone();

            if (!Environs.Debug) singlePointInputTask.Control(TaskAction.Verify);
            singlePointInputReader = new AnalogMultiChannelReader(singlePointInputTask.Stream);
        }
        // Method to set up the recording side of neurorighter
        private bool NRAcquisitionSetup()
        {
            lock (this)
            {
                if (!taskRunning)
                {
                    try
                    {

                        this.Cursor = Cursors.WaitCursor;
                       if (switch_record.Value)
                        {
                            // Create file name
                            if (filenameBase == null) //user hasn't specified a file
                                button_BrowseOutputFile_Click(null, null); //call file selection routine
                            if (filenameBase == null) //this happens if the user pressed cancel for the dialog
                            {
                                MessageBox.Show("An output file must be selected before recording."); //display an error message
                                this.Cursor = Cursors.Default;
                                return true;
                            }

                            // If the user is just doing repeated recordings
                            if (checkbox_repeatRecord.Checked || Properties.Settings.Default.useFidTimeStamp)
                            {
                                DateTime nowDate = DateTime.Now;//Get current time (local to computer);
                                string datePrefix = nowDate.ToString("'-'yyyy'-'MM'-'dd'-'HH'-'mm'-'ss");
                                filenameBase = originalNameBase + datePrefix;
                            }

                            // Look for old files with same name
                            string[] matchFiles;
                            try
                            {
                                matchFiles = Directory.GetFiles(currentSaveDir, currentSaveFile + "*");
                            }
                            catch
                            {
                                matchFiles = new string[0];
                            }

                            if (matchFiles.Length > 0)
                            {
                                DialogResult dr = MessageBox.Show("File " + filenameBase + " exists. Overwrite?",
                                    "NeuroRighter Warning", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning);

                                if (dr == DialogResult.No)
                                    button_BrowseOutputFile_Click(null, null); //call file selection routine
                                else if (dr == DialogResult.Cancel)
                                {
                                    this.Cursor = Cursors.Default;
                                    return true;
                                }
                            }

                            // Set file base name + number of channels
                            recordingSettings.SetFID(filenameBase);
                            recordingSettings.SetNumElectrodes(numChannels);
                        }

                        // Find out how many devs and channels/dev we are going to need
                        int numDevices = (numChannels > 32 ? Properties.Settings.Default.AnalogInDevice.Count : 1);
                        numChannelsPerDev = (numChannels < 32 ? numChannels : 32);

                        // Set spike buffer lengths
                        spikeBufferLength = Convert.ToInt32(Properties.Settings.Default.ADCPollingPeriodSec * Properties.Settings.Default.RawSampleFrequency);
                        lfpBufferLength = Convert.ToInt32(Properties.Settings.Default.ADCPollingPeriodSec * Properties.Settings.Default.LFPSampleFrequency);

                        // Create spike aquisition task list
                        spikeTask = new List<Task>(numDevices);
                        Properties.Settings.Default.numSpikeTasks = numDevices;
                        NRAIChannelCollection spikeAqSet = new NRAIChannelCollection(numDevices, numChannelsPerDev);
                        spikeAqSet.SetupSpikeCollection(ref spikeTask);

                        // Check audio and video properties
                        if (Properties.Settings.Default.UseSingleChannelPlayback)
                            spikeOutTask = new Task("spikeOutTask"); //For audio output
                        if (checkBox_video.Checked) //NB: This can't be checked unless video is enabled (no need to check properties)
                            triggerTask = new Task("triggerTask");

                        // Set MUA sample rate
                        double muaSamplingRate = spikeSamplingRate / MUA_DOWNSAMPLE_FACTOR;

                        //Add LFP channels, if configured
                        if (Properties.Settings.Default.SeparateLFPBoard && Properties.Settings.Default.UseLFPs)
                        {
                            lfpTask = new Task("lfpTask");
                            for (int i = 0; i < Properties.Settings.Default.NumChannels; ++i)
                                lfpTask.AIChannels.CreateVoltageChannel(Properties.Settings.Default.LFPDevice + "/ai" + i.ToString(), "",
                                    AITerminalConfiguration.Nrse, -10.0, 10.0, AIVoltageUnits.Volts);
                            setGain(lfpTask, Properties.Settings.Default.LFPgain);
                            lfpTask.Control(TaskAction.Verify);
                        }

                        //Add EEG channels, if configured
                        if (Properties.Settings.Default.UseEEG)
                        {

                            eegTask = new Task("eegTask");
                            for (int i = 0; i < Properties.Settings.Default.EEGNumChannels; ++i)
                                eegTask.AIChannels.CreateVoltageChannel(Properties.Settings.Default.EEGDevice + "/ai" +
                                    (i).ToString(), "", AITerminalConfiguration.Nrse, -10.0, 10.0, AIVoltageUnits.Volts);
                            setGain(eegTask, (double)Properties.Settings.Default.EEGGain);
                            eegTask.Control(TaskAction.Verify);
                            eegSamplingRate = Properties.Settings.Default.EEGSamplingRate;
                        }

                        //Add channel to control Cineplex, if configured
                        if (checkBox_video.Checked)
                            triggerTask.DOChannels.CreateChannel(Properties.Settings.Default.CineplexDevice + "/Port0/line0:7", "",
                                ChannelLineGrouping.OneChannelForAllLines);

                        //Change gain based on comboBox values (1-100)
                        for (int i = 0; i < spikeTask.Count; ++i)
                            setGain(spikeTask[i], Properties.Settings.Default.A2Dgain);

                        //Verify the Tasks
                        for (int i = 0; i < spikeTask.Count; ++i)
                            spikeTask[i].Control(TaskAction.Verify);
                        //if (Properties.Settings.Default.UseSingleChannelPlayback)
                        //    spikeOutTask.Control(TaskAction.Verify);

                        //Get sampling rates, set to private variables
                        spikeSamplingRate = Properties.Settings.Default.RawSampleFrequency;
                        lfpSamplingRate = Properties.Settings.Default.LFPSampleFrequency;

                        //Version with videoTask as master clock
                        if (Properties.Settings.Default.UseCineplex)
                        {
                            for (int i = 0; i < spikeTask.Count; ++i)
                            {
                                spikeTask[i].Timing.ReferenceClockSource = videoTask.Timing.ReferenceClockSource;
                                spikeTask[i].Timing.ReferenceClockRate = videoTask.Timing.ReferenceClockRate;
                            }
                        }
                        else
                        {
                            string masterclock = "/" + Properties.Settings.Default.AnalogInDevice[0].ToString() + "/10MhzRefClock";//"OnboardClock";//
                            if (!Properties.Settings.Default.UseStimulator)
                            {
                                //Deal with non M-series devices (these can't use "ReferenceClockSource"
                                Device analogInDevice = DaqSystem.Local.LoadDevice(Properties.Settings.Default.AnalogInDevice[0]);

                                if (analogInDevice.ProductCategory == ProductCategory.MSeriesDaq || analogInDevice.ProductCategory == ProductCategory.XSeriesDaq)
                                    spikeTask[0].Timing.ReferenceClockSource = masterclock; //This will be the master clock
                            }
                            else
                            {

                                spikeTask[0].Timing.ReferenceClockSource = masterclock;//stimPulseTask.Timing.ReferenceClockSource;
                                spikeTask[0].Timing.ReferenceClockRate = 10000000.0; //stimPulseTask.Timing.ReferenceClockRate;
                            }
                            for (int i = 1; i < spikeTask.Count; ++i) //Set other analog in tasks to master clock
                            {
                                spikeTask[i].Timing.ReferenceClockSource = spikeTask[0].Timing.ReferenceClockSource;
                                spikeTask[i].Timing.ReferenceClockRate = spikeTask[0].Timing.ReferenceClockRate;
                            }
                        }
                        spikeTask[0].Timing.ConfigureSampleClock("", spikeSamplingRate,
                                SampleClockActiveEdge.Rising, SampleQuantityMode.ContinuousSamples, Convert.ToInt32(Properties.Settings.Default.RawSampleFrequency / 2));
                        for (int i = 1; i < spikeTask.Count; ++i)
                        {
                            //Pipe ai dev0's sample clock to slave devices
                            spikeTask[i].Timing.ConfigureSampleClock("/" + Properties.Settings.Default.AnalogInDevice[0] + "/ai/SampleClock", spikeSamplingRate,
                                SampleClockActiveEdge.Rising, SampleQuantityMode.ContinuousSamples, Convert.ToInt32(Properties.Settings.Default.RawSampleFrequency / 2));

                            //Trigger off of ai dev0's trigger
                            spikeTask[i].Triggers.StartTrigger.ConfigureDigitalEdgeTrigger("/" + Properties.Settings.Default.AnalogInDevice[0] +
                                "/ai/StartTrigger", DigitalEdgeStartTriggerEdge.Rising);

                            // Manually allocate buffer memory
                            //spikeTask[i].Stream.Buffer.InputBufferSize = DAQ_BUFFER_SIZE_SAMPLES;
                        }

                        if (Properties.Settings.Default.SeparateLFPBoard && Properties.Settings.Default.UseLFPs)
                        {
                            lfpTask.Timing.ReferenceClockSource = spikeTask[0].Timing.ReferenceClockSource;
                            lfpTask.Timing.ReferenceClockRate = spikeTask[0].Timing.ReferenceClockRate;
                            lfpTask.Timing.ConfigureSampleClock("", lfpSamplingRate,
                                SampleClockActiveEdge.Rising, SampleQuantityMode.ContinuousSamples, Convert.ToInt32(Properties.Settings.Default.LFPSampleFrequency / 2));

                            // Manually allocate buffer memory
                            //lfpTask.Stream.Buffer.InputBufferSize = DAQ_BUFFER_SIZE_SAMPLES;
                        }
                        else
                        {
                            Properties.Settings.Default.numLFPTasks = Properties.Settings.Default.numSpikeTasks;
                        }

                        if (Properties.Settings.Default.UseEEG)
                        {
                            eegTask.Timing.ReferenceClockSource = spikeTask[0].Timing.ReferenceClockSource;
                            eegTask.Timing.ReferenceClockRate = spikeTask[0].Timing.ReferenceClockRate;
                            eegTask.Timing.ConfigureSampleClock("", eegSamplingRate,
                                SampleClockActiveEdge.Rising, SampleQuantityMode.ContinuousSamples, Convert.ToInt32(Convert.ToDouble(Properties.Settings.Default.EEGSamplingRate) / 2));

                            // Manually allocate buffer memory
                            //eegTask.Stream.Buffer.InputBufferSize = DAQ_BUFFER_SIZE_SAMPLES;
                        }

                        if (Properties.Settings.Default.UseCineplex)
                        {
                            if (checkBox_video.Checked)
                            {
                                triggerTask.Timing.ConfigureSampleClock("/" + Properties.Settings.Default.AnalogInDevice[0] + "/ai/SampleClock",
                                    spikeSamplingRate, SampleClockActiveEdge.Rising, SampleQuantityMode.FiniteSamples,
                                    3);
                            }
                            if (Properties.Settings.Default.SeparateLFPBoard && Properties.Settings.Default.UseLFPs)
                            {
                                lfpTask.Triggers.StartTrigger.ConfigureDigitalEdgeTrigger("/" +
                                    Properties.Settings.Default.AnalogInDevice[0] + "/ai/StartTrigger",
                                    DigitalEdgeStartTriggerEdge.Rising);
                            }
                            if (Properties.Settings.Default.UseEEG)
                            {
                                eegTask.Triggers.StartTrigger.ConfigureDigitalEdgeTrigger("/" +
                                    Properties.Settings.Default.AnalogInDevice[0] + "/ai/StartTrigger",
                                    DigitalEdgeStartTriggerEdge.Rising);
                            }
                        }

                        if (Properties.Settings.Default.UseStimulator && Properties.Settings.Default.RecordStimTimes)
                        {
                            try
                            {

                                numStimReads = new List<int>(numDevices);
                                for (int i = 0; i < spikeTask.Count; ++i)
                                    numStimReads.Add(0);
                                stimTimeTask = new Task("stimTimeTask");
                                stimTimeTask.AIChannels.CreateVoltageChannel(Properties.Settings.Default.StimInfoDevice + "/ai16", "",
                                    AITerminalConfiguration.Nrse, -10.0, 10.0, AIVoltageUnits.Volts);
                                stimTimeTask.AIChannels.CreateVoltageChannel(Properties.Settings.Default.StimInfoDevice + "/ai0", "", AITerminalConfiguration.Nrse,
                                    -10.0, 10.0, AIVoltageUnits.Volts); //For triggers

                                // Pipe the spikeTasks sample clock to PFI14 on the stim board
                                DaqSystem.Local.ConnectTerminals(spikeTask[0].Timing.ReferenceClockSource,
                                    "/" + Properties.Settings.Default.StimulatorDevice.ToString() + "/PFI0");

                                if (isNormalRecording)
                                    stimTimeTask.Timing.ReferenceClockSource = "/" + Properties.Settings.Default.StimulatorDevice.ToString() + "/PFI0";
                                else
                                    stimTimeTask.Timing.ReferenceClockSource = spikeTask[0].Timing.ReferenceClockSource;
                                stimTimeTask.Timing.ReferenceClockRate = spikeTask[0].Timing.ReferenceClockRate;
                                stimTimeTask.Timing.ConfigureSampleClock("", spikeSamplingRate,
                                    SampleClockActiveEdge.Rising, SampleQuantityMode.ContinuousSamples, Convert.ToInt32(Properties.Settings.Default.RawSampleFrequency / 2));
                                stimTimeTask.Triggers.StartTrigger.ConfigureDigitalEdgeTrigger(
                                    "/" + Properties.Settings.Default.AnalogInDevice[0] + "/ai/StartTrigger", DigitalEdgeStartTriggerEdge.Rising);
                                stimTimeTask.Control(TaskAction.Verify);

                                // stim Timing Channel settings object
                                StringCollection stimTimePhysChan = new StringCollection();
                                for (int i = 0; i < stimTimeTask.AIChannels.Count; ++i)
                                {
                                    stimTimePhysChan.Add(stimTimeTask.AIChannels[i].PhysicalName);
                                }

                                // Write down the indicies corresponding to the portion of this task that will
                                // actually record stimulus infromation instead of aux analog input
                                stimTimeChanSet = new NRAIChannelCollection(stimTimePhysChan);
                                int[] stimTimeChannels = new int[] { 0, 1 };
                                stimTimeChanSet.SetupNumericalChannelOnly(stimTimeChannels);

                                // Manually allocate buffer memory
                                //stimTimeTask.Stream.Buffer.InputBufferSize = DAQ_BUFFER_SIZE_SAMPLES;

                                Console.WriteLine("NRAcquisitionSetup complete");
                            }
                            catch (Exception e)
                            {
                                MessageBox.Show(e.Message);
                            }
                        }

                        //Setup scaling coefficients (to convert digital values to voltages)
                        scalingCoeffsSpikes = new List<double[]>(spikeTask.Count);
                        for (int i = 0; i < spikeTask.Count; ++i)
                            scalingCoeffsSpikes.Add(spikeTask[0].AIChannels[0].DeviceScalingCoefficients);
                        if (Properties.Settings.Default.SeparateLFPBoard)
                            scalingCoeffsLFPs = lfpTask.AIChannels[0].DeviceScalingCoefficients;
                        if (Properties.Settings.Default.UseEEG)
                            scalingCoeffsEEG = eegTask.AIChannels[0].DeviceScalingCoefficients;

                        // Setup auxiliary recording tasks
                        if (Properties.Settings.Default.useAuxAnalogInput)
                        {
                            // Set up the aux channel set
                            auxChanSet = new NRAIChannelCollection(Properties.Settings.Default.auxAnalogInChan);

                            if (Properties.Settings.Default.auxAnalogInDev == Properties.Settings.Default.StimInfoDevice
                                && Properties.Settings.Default.RecordStimTimes)
                            {
                                // In this case we are recording both stimulus times and aux analog input times on the same
                                // DAQ, so we need to just make the auxAnInTask reference the stimulus timing task
                                twoAITasksOnSingleBoard = true;
                                auxAnInTask = stimTimeTask;
                                auxChanSet.SetupAuxCollection(ref auxAnInTask);
                            }
                            else
                            {
                                // In this case there is no conflict for AI, so we can create a dedicated task for aux analog input
                                twoAITasksOnSingleBoard = false;
                                auxAnInTask = new Task("AuxiliaryAnalogInput");
                                auxChanSet.SetupAuxCollection(ref auxAnInTask);

                                auxAnInTask.Timing.ReferenceClockSource = spikeTask[0].Timing.ReferenceClockSource;
                                auxAnInTask.Timing.ReferenceClockRate = spikeTask[0].Timing.ReferenceClockRate;

                                //Pipe ai dev0's sample clock to slave devices
                                auxAnInTask.Timing.ConfigureSampleClock("", spikeSamplingRate,
                                    SampleClockActiveEdge.Rising, SampleQuantityMode.ContinuousSamples, Convert.ToInt32(Properties.Settings.Default.RawSampleFrequency / 2));
                                auxAnInTask.Triggers.StartTrigger.ConfigureDigitalEdgeTrigger("/Dev1/ai/StartTrigger", DigitalEdgeStartTriggerEdge.Rising);

                                // Manually allocate buffer memory
                                // auxAnInTask.Stream.Buffer.InputBufferSize = DAQ_BUFFER_SIZE_SAMPLES;

                                // Create space for the buffer
                                auxAnData = new double[auxChanSet.numericalChannels.Length, spikeBufferLength];

                            }

                        }

                        if (Properties.Settings.Default.useAuxDigitalInput)
                        {
                            auxDigInTask = new Task("AuxiliaryDigitalInput");
                            auxDigInTask.DIChannels.CreateChannel(Properties.Settings.Default.auxDigitalInPort,
                                "Auxiliary Digitial In", ChannelLineGrouping.OneChannelForAllLines);

                            auxDigInTask.Timing.ConfigureSampleClock("", spikeSamplingRate,
                                SampleClockActiveEdge.Rising, SampleQuantityMode.ContinuousSamples, Convert.ToInt32(Properties.Settings.Default.RawSampleFrequency / 2));
                            auxDigInTask.Timing.SampleClockSource = spikeTask[0].Timing.SampleClockTerminal;

                            // Manually allocate buffer memory
                            // auxDigInTask.Stream.Buffer.InputBufferSize = DAQ_BUFFER_SIZE_SAMPLES;
                        }

                        #region Setup_Plotting

                        numSnipsDisplayed = (int)numericUpDown_NumSnipsDisplayed.Value;

                        #region PlotData_Buffers
                        //***********************
                        //Make PlotData buffers
                        //***********************
                        int downsample, numRows, numCols;
                        const double spikeplotlength = 0.25; //in seconds
                        switch (Properties.Settings.Default.NumChannels)
                        {
                            case 16:
                                numRows = numCols = 4;
                                downsample = 10;
                                break;
                            case 32:
                                numRows = numCols = 6;
                                downsample = 15;
                                break;
                            case 64:
                                numRows = numCols = 8;
                                downsample = 20; //if this gets really small, LFP data won't plot
                                break;
                            default:
                                numRows = numCols = 4;
                                downsample = 5;
                                break;
                        }

                        //Create plot colormap
                        NRBrainbow = (64).GenerateBrainbow();
                        NRSnipBrainbow = (64).GenerateSnipBrainbow();
                        NRUnitBrainbow = (64).GenerateUnitBrainbow();

                        //Initialize graphs
                        if (spikeGraph != null) { spikeGraph.Dispose(); spikeGraph = null; }
                        spikeGraph = new GridGraph();
                        int samplesPerPlot = (int)(Math.Ceiling(Properties.Settings.Default.ADCPollingPeriodSec * spikeSamplingRate / downsample) * (spikeplotlength / Properties.Settings.Default.ADCPollingPeriodSec));
                        spikeGraph.setup(numRows, numCols, samplesPerPlot, false, 1 / 4.0, spikeTask[0].AIChannels.All.RangeHigh * 2.0);
                        spikeGraph.setMinMax(0, (float)(samplesPerPlot * numCols) - 1,
                            (float)(spikeTask[0].AIChannels.All.RangeLow * (numRows * 2 - 1)), (float)(spikeTask[0].AIChannels.All.RangeHigh));
                        spikeGraph.Dock = DockStyle.Fill;
                        spikeGraph.Parent = tabPage_spikes;

                        if (Properties.Settings.Default.UseLFPs)
                        {
                            if (lfpGraph != null) { lfpGraph.Dispose(); lfpGraph = null; }
                            lfpGraph = new RowGraph();
                            lfpGraph.setup(numChannels, (int)((Math.Ceiling(Properties.Settings.Default.ADCPollingPeriodSec * lfpSamplingRate / downsample) * (5 / Properties.Settings.Default.ADCPollingPeriodSec))),
                                5.0, spikeTask[0].AIChannels.All.RangeHigh * 2.0);
                            if (Properties.Settings.Default.SeparateLFPBoard)
                                lfpGraph.setMinMax(0, 5 * (int)(Math.Ceiling(Properties.Settings.Default.ADCPollingPeriodSec * lfpSamplingRate / downsample) / Properties.Settings.Default.ADCPollingPeriodSec) - 1,
                                    (float)(lfpTask.AIChannels.All.RangeLow * (numChannels * 2 - 1)), (float)(lfpTask.AIChannels.All.RangeHigh));
                            else
                                lfpGraph.setMinMax(0, 5 * (int)(Math.Ceiling(Properties.Settings.Default.ADCPollingPeriodSec * lfpSamplingRate / downsample) / Properties.Settings.Default.ADCPollingPeriodSec) - 1,
                                    (float)(spikeTask[0].AIChannels.All.RangeLow * (numChannels * 2 - 1)), (float)(spikeTask[0].AIChannels.All.RangeHigh));
                            lfpGraph.Dock = DockStyle.Fill;
                            lfpGraph.Parent = tabPage_LFPs;
                        }

                        if (Properties.Settings.Default.ProcessMUA)
                        {
                            if (muaGraph != null) { muaGraph.Dispose(); muaGraph = null; }
                            muaGraph = new RowGraph();
                            muaGraph.setup(numChannels, (int)((Math.Ceiling(Properties.Settings.Default.ADCPollingPeriodSec * muaSamplingRate / downsample) * (5 / Properties.Settings.Default.ADCPollingPeriodSec))),
                                5.0, spikeTask[0].AIChannels.All.RangeHigh * 2.0);
                            muaGraph.setMinMax(0, 5 * (int)(Math.Ceiling(Properties.Settings.Default.ADCPollingPeriodSec * muaSamplingRate / downsample) / Properties.Settings.Default.ADCPollingPeriodSec) - 1,
                                    (float)(spikeTask[0].AIChannels.All.RangeLow * (numChannels * 2 - 1)), (float)(spikeTask[0].AIChannels.All.RangeHigh));
                            muaGraph.Dock = DockStyle.Fill;
                            muaGraph.Parent = tabPage_MUA;

                            muaPlotData = new PlotDataRows(numChannels, downsample, (int)(muaSamplingRate * 5), muaSamplingRate,
                                    (float)spikeTask[0].AIChannels.All.RangeHigh * 2F, 0.5, 5, Properties.Settings.Default.ADCPollingPeriodSec);
                            //muaPlotData.setGain(Properties.Settings.Default.LFPDisplayGain);

                            //muaGraph.setDisplayGain(Properties.Settings.Default.LFPDisplayGain);
                            muaPlotData.dataAcquired += new PlotData.dataAcquiredHandler(muaPlotData_dataAcquired);
                        }

                        if (Properties.Settings.Default.UseEEG)
                        {
                            if (eegGraph != null) { eegGraph.Dispose(); eegGraph = null; }
                            eegGraph = new RowGraph();
                            eegGraph.setup(Properties.Settings.Default.EEGNumChannels, (int)((Math.Ceiling(Properties.Settings.Default.ADCPollingPeriodSec * eegSamplingRate / downsample) * (5 / Properties.Settings.Default.ADCPollingPeriodSec))),
                                5.0, eegTask.AIChannels.All.RangeHigh * 2.0);
                            eegGraph.setMinMax(0, 5 * (int)(Math.Ceiling(Properties.Settings.Default.ADCPollingPeriodSec * eegSamplingRate / downsample) / Properties.Settings.Default.ADCPollingPeriodSec) - 1,
                                    (float)(eegTask.AIChannels.All.RangeLow * (Properties.Settings.Default.EEGNumChannels * 2 - 1)), (float)(eegTask.AIChannels.All.RangeHigh));
                            eegGraph.Dock = DockStyle.Fill;
                            eegGraph.Parent = tabPage_EEG;
                        }

                        resetSpkWfm(); //Take care of spike waveform graph

                        double ampdec = (1 / Properties.Settings.Default.PreAmpGain);

                        spikePlotData = new PlotDataGrid(numChannels, downsample, (int)(spikeSamplingRate), spikeSamplingRate,
                            (float)(spikeTask[0].AIChannels.All.RangeHigh * 2.0), numRows, numCols, spikeplotlength,
                            Properties.Settings.Default.ChannelMapping, Properties.Settings.Default.ADCPollingPeriodSec);
                        spikePlotData.dataAcquired += new PlotData.dataAcquiredHandler(spikePlotData_dataAcquired);
                        spikePlotData.setGain(Properties.Settings.Default.SpikeDisplayGain);
                        spikeGraph.setDisplayGain(Properties.Settings.Default.SpikeDisplayGain);

                        if (Properties.Settings.Default.UseLFPs)
                        {
                            if (Properties.Settings.Default.SeparateLFPBoard)
                                lfpPlotData = new PlotDataRows(numChannels, downsample, (int)(lfpSamplingRate * 5), lfpSamplingRate,
                                    (float)lfpTask.AIChannels.All.RangeHigh * 2F, 0.5, 5, Properties.Settings.Default.ADCPollingPeriodSec);
                            else lfpPlotData = new PlotDataRows(numChannels, downsample, (int)(lfpSamplingRate * 5), lfpSamplingRate,
                                    (float)spikeTask[0].AIChannels.All.RangeHigh * 2F, 0.5, 5, Properties.Settings.Default.ADCPollingPeriodSec);
                            lfpPlotData.setGain(Properties.Settings.Default.LFPDisplayGain);

                            lfpGraph.setDisplayGain(Properties.Settings.Default.LFPDisplayGain);
                            lfpPlotData.dataAcquired += new PlotData.dataAcquiredHandler(lfpPlotData_dataAcquired);
                        }

                        waveformPlotData = new EventPlotData(numChannels, spikeDet.NumPre + spikeDet.NumPost + 1, (float)(spikeTask[0].AIChannels.All.RangeHigh * 2F),
                            numRows, numCols, numSnipsDisplayed, Properties.Settings.Default.ChannelMapping);
                        waveformPlotData.setGain(Properties.Settings.Default.SpkWfmDisplayGain);
                        spkWfmGraph.setDisplayGain(Properties.Settings.Default.SpkWfmDisplayGain);
                        waveformPlotData.dataAcquired += new EventPlotData.dataAcquiredHandler(waveformPlotData_dataAcquired);
                        waveformPlotData.start();
                        #endregion

                        if (Properties.Settings.Default.UseEEG)
                        {
                            eegPlotData = new PlotDataRows(Properties.Settings.Default.EEGNumChannels, downsample, (int)(eegSamplingRate * 5), eegSamplingRate,
                                    (float)eegTask.AIChannels.All.RangeHigh * 2F, 0.5, 5, Properties.Settings.Default.ADCPollingPeriodSec);
                            eegPlotData.setGain(Properties.Settings.Default.EEGDisplayGain);

                            eegGraph.setDisplayGain(Properties.Settings.Default.EEGDisplayGain);
                            eegPlotData.dataAcquired += new PlotData.dataAcquiredHandler(eegPlotData_dataAcquired);
                        }

                        if (Properties.Settings.Default.useAuxAnalogInput)
                        {
                            // Remove existing plots
                            for (int i = scatterGraph_AuxAnalogData.Plots.Count-1; i > 0; --i)
                            {
                                scatterGraph_AuxAnalogData.Plots.RemoveAt(i);
                            }
                            // Initialize the aux data scatter graph with a plot for each aux Analog channel
                            for (int i = 0; i < Properties.Settings.Default.auxAnalogInChan.Count-1; ++i)
                            {
                                ScatterPlot p = new ScatterPlot();
                                scatterGraph_AuxAnalogData.Plots.Add(p);
                            }

                            // Initialize the controller
                            auxInputGraphController = new ScatterGraphController(ref scatterGraph_AuxAnalogData);

                            // Make history selector reflect current limits on input
                            //slide_AnalogDispMaxVoltage.Range = new Range(0.05, 10);
                            //slide_AnalogDispWidth.Range = new Range(2*Properties.Settings.Default.ADCPollingPeriodSec, Properties.Settings.Default.datSrvBufferSizeSec);

                        }
                        #endregion

                        #region Setup_Filters
                        //Setup filters, based on user's input
                        resetSpikeFilter();
                        if (Properties.Settings.Default.UseLFPs) resetLFPFilter();
                        resetEEGFilter();

                        muaFilter = new Filters.MUAFilter(
                            numChannels, spikeSamplingRate, spikeBufferLength,
                            Properties.Settings.Default.MUAHighCutHz,
                            Properties.Settings.Default.MUAFilterOrder,
                            MUA_DOWNSAMPLE_FACTOR,
                            Properties.Settings.Default.ADCPollingPeriodSec);

                        #endregion

                        #region Setup_DataStorage
                        //Initialize data storing matrices
                      //  numChannels = Properties.Settings.Default.NumChannels;

                        numSpikeReads = new int[spikeTask.Count];

                        filtSpikeData = new rawType[numChannels][];

                        if (Properties.Settings.Default.UseLFPs)
                        {
                            filtLFPData = new rawType[numChannels][];
                            finalLFPData = new rawType[numChannels][];
                            for (int i = 0; i < filtSpikeData.GetLength(0); ++i)
                            {
                                if (Properties.Settings.Default.SeparateLFPBoard)
                                    filtLFPData[i] = new rawType[lfpBufferLength];
                                else
                                    filtLFPData[i] = new rawType[spikeBufferLength];
                            }
                        }

                        if (Properties.Settings.Default.ProcessMUA)
                        {
                            muaData = new double[numChannels][];
                            for (int c = 0; c < numChannels; ++c)
                                muaData[c] = new double[spikeBufferLength / MUA_DOWNSAMPLE_FACTOR];
                        }

                        if (Properties.Settings.Default.UseEEG)
                        {

                            filtEEGData = new double[Properties.Settings.Default.EEGNumChannels][];
                            for (int i = 0; i < filtEEGData.GetLength(0); ++i)
                            {
                                filtEEGData[i] = new double[eegBufferLength];
                            }
                        }

                        for (int i = 0; i < filtSpikeData.GetLength(0); ++i)
                        {
                            filtSpikeData[i] = new rawType[spikeBufferLength];
                            if (Properties.Settings.Default.UseLFPs)
                                finalLFPData[i] = new rawType[lfpBufferLength];
                        }

                        if (Properties.Settings.Default.UseStimulator)
                        {
                            stimDataBuffer = new double[STIM_BUFFER_LENGTH];
                            stimJump = (double)spikeSamplingRate * 0.0001; //num. indices in 100 us of data
                        }

                        stimIndices = new List<StimTick>(5);
                        //if devices refresh rate is reset, need to reset SALPA
                        if (checkBox_SALPA.Checked)
                            resetSALPA();
                        if (spikeDet != null && isNormalRecording)
                            setSpikeDetector();
                        if (spikeDet.spikeDetector == null)
                            setSpikeDetector();

                        #endregion

                        #region Verify Tasks
                        if (Properties.Settings.Default.UseStimulator && Properties.Settings.Default.RecordStimTimes)
                            stimTimeTask.Control(TaskAction.Verify);
                        if (Properties.Settings.Default.UseEEG)
                            eegTask.Control(TaskAction.Verify);
                        if (Properties.Settings.Default.SeparateLFPBoard && Properties.Settings.Default.UseLFPs)
                            lfpTask.Control(TaskAction.Verify);
                        if (checkBox_video.Checked)
                            triggerTask.Control(TaskAction.Verify);
                        for (int i = 0; i < spikeTask.Count; ++i)
                            spikeTask[i].Control(TaskAction.Verify);
                        if (Properties.Settings.Default.useAuxAnalogInput)
                            auxAnInTask.Control(TaskAction.Verify);
                        if (Properties.Settings.Default.useAuxDigitalInput)
                            auxDigInTask.Control(TaskAction.Verify);
                        #endregion

                        SetupFileWriting();

                        //Set callbacks for data acq.
                        spikeReader = new List<AnalogMultiChannelReader>(spikeTask.Count);
                        for (int i = 0; i < spikeTask.Count; ++i)
                        {
                            spikeReader.Add(new AnalogMultiChannelReader(spikeTask[i].Stream));
                            spikeReader[i].SynchronizeCallbacks = true;
                        }
                        //if (Properties.Settings.Default.UseSingleChannelPlayback)
                        //    spikeOutWriter = new AnalogSingleChannelWriter(spikeOutTask.Stream);
                        if (checkBox_video.Checked)
                            triggerWriter = new DigitalSingleChannelWriter(triggerTask.Stream);

                        //if (Properties.Settings.Default.UseSingleChannelPlayback)
                        //    spikeOutWriter.SynchronizeCallbacks = false; //These don't use UI, so they don't need to be synched

                        spikeCallback = new AsyncCallback(AnalogInCallback_spikes);

                        if (Properties.Settings.Default.UseStimulator && Properties.Settings.Default.RecordStimTimes)
                        {
                            stimTimeReader = new AnalogMultiChannelReader(stimTimeTask.Stream);
                        }

                        if (Properties.Settings.Default.SeparateLFPBoard && Properties.Settings.Default.UseLFPs)
                        {
                            lfpReader = new AnalogUnscaledReader(lfpTask.Stream);
                            lfpReader.SynchronizeCallbacks = true;
                            lfpCallback = new AsyncCallback(AnalogInCallback_LFPs);
                        }
                        if (Properties.Settings.Default.UseEEG)
                        {
                            eegReader = new AnalogUnscaledReader(eegTask.Stream);
                            eegReader.SynchronizeCallbacks = true;
                            eegCallback = new AsyncCallback(AnalogInCallback_EEG);
                        }

                        if (Properties.Settings.Default.useAuxAnalogInput)
                        {
                            auxAnReader = new AnalogMultiChannelReader(auxAnInTask.Stream);
                            auxAnReader.SynchronizeCallbacks = true;
                            auxAnCallback = new AsyncCallback(AnalogInCallback_AuxAn);
                        }

                        if (Properties.Settings.Default.useAuxDigitalInput)
                        {
                            auxDigReader = new DigitalSingleChannelReader(auxDigInTask.Stream);
                            auxDigReader.SynchronizeCallbacks = true;
                            auxDigCallback = new AsyncCallback(AnalogInCallback_AuxDig);
                        }

                        //Setup background workers for data processing
                        bwSpikes = new List<BackgroundWorker>(spikeTask.Count);
                        bwIsRunning = new bool[spikeTask.Count];
                        for (int i = 0; i < spikeTask.Count; ++i)
                        {
                            bwSpikes.Add(new BackgroundWorker());
                            bwSpikes[i].DoWork += new DoWorkEventHandler(bwSpikes_DoWork);
                            bwSpikes[i].RunWorkerCompleted += new RunWorkerCompletedEventHandler(bwSpikes_RunWorkerCompleted);
                            bwSpikes[i].WorkerSupportsCancellation = true;
                        }

                        //Make persistent buffers for spikeData
                        spikeData = new List<AnalogWaveform<double>[]>(spikeReader.Count);
                        for (int i = 0; i < spikeReader.Count; ++i)
                        {
                            spikeData.Add(new AnalogWaveform<double>[numChannelsPerDev]);
                            for (int j = 0; j < numChannelsPerDev; ++j)
                                spikeData[i][j] = new AnalogWaveform<double>(spikeBufferLength);
                        }

                        //Make channel playback task
                        if (Properties.Settings.Default.UseSingleChannelPlayback)
                            BNCOutput = new ChannelOutput(spikeSamplingRate, 0.1, Properties.Settings.Default.ADCPollingPeriodSec, spikeTask[0],
                                Properties.Settings.Default.SingleChannelPlaybackDevice, 0);

                    }
                    catch (Exception exception)
                    {
                        //Display Errors
                        this.Cursor = Cursors.Default;
                        MessageBox.Show(exception.Message);
                        reset();
                    }

                    // Set up the DataSrv object. This is an object that publishes a nice large data history
                    // for use in closed loop control and other things
                    if (datSrv != null)
                        datSrv = null;

                    datSrv = new DataSrv(
                        Properties.Settings.Default.datSrvBufferSizeSec,
                        checkBox_SALPA.Checked,
                        SALPA_WIDTH,
                        checkBox_spikesFilter.Checked,
                        spikeDet.spikeDetectionLag
                        );

                    // Set the number of units if appropriate
                    if (spikeDet.spikeSorter != null)
                        datSrv.SetNumberOfUnits(spikeDet.spikeSorter.totalNumberOfUnits, spikeDet.spikeSorter.unit2Channel);

                    Debugger = new Logger();
                    Debugger.GrabTimer(spikeTask[0]);

                    //Send debug output to the user's application data folder
                    Debugger.SetPath(Path.Combine(Properties.Settings.Default.neurorighterAppDataPath, "neurorighter-log.txt"));

                    //Tell neuroRighter that the tasks now exist
                    taskRunning = true;
                }
                else
                {
                    Console.WriteLine("NRAcquisitionSetup was called while a task was running, and therefore setup did not execute.  Perhaps this should have thrown an error");
                }
            }

            //update gui at the end
            // Modify the UI, so user doesn't try running multiple instances of tasks

            spikeDet.numPreSamples.Enabled = false;
            spikeDet.numPostSamples.Enabled = false;
            settingsToolStripMenuItem.Enabled = false;

            button_Train.Enabled = false;
            button_SetRecordingStreams.Enabled = false;
            switch_record.Enabled = false;
            //processingSettingsToolStripMenuItem.Enabled = false;

            button_startStimFromFile.Enabled = false;
            button_startClosedLoopStim.Enabled = false;
            checkBox_SALPA.Enabled = false;

            //numericUpDown_NumSnipsDisplayed.Enabled = false;
            button_startClosedLoopStim.Enabled = false;
            button_scaleUp.Enabled = true;
            button_scaleDown.Enabled = true;
            button_scaleReset.Enabled = true;

            // Disable spike detector saving while running
            spikeDet.DisableFileMenu();
            Console.WriteLine("NRAcquisitionSetup successfully executed");
            this.Cursor = Cursors.Default;
            return false;
        }
        //Skraldespanden
        //protected override void Dispose(bool disposing)
        //{
        //    if (disposing)
        //    {
        //        if (components != null)
        //        {
        //            components.Dispose();
        //        }
        //        if (myTask != null)
        //        {
        //            runningTask = null;
        //            myTask.Dispose();
        //        }
        //    }
        //    Dispose(disposing);
        //}
        public void indhentData()
        {
            if (runningTask == null)
            {
                try
                {
                    // Create a new task
                    myTask = new Task();

                    // Create a virtual channel
                    myTask.AIChannels.CreateVoltageChannel("Dev1/ai0", "",
                        (AITerminalConfiguration)(-1), Convert.ToDouble(-3.00),
                        Convert.ToDouble(3.00), AIVoltageUnits.Volts);

                    // Configure the timing parameters
                    // Her bliver samplerate sat til 1000 samt samples per channel til 20
                    myTask.Timing.ConfigureSampleClock("", Convert.ToDouble(1000),
                        SampleClockActiveEdge.Rising, SampleQuantityMode.ContinuousSamples,10);

                    // 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); //Håndterer de data vi får ind løbende, selvkørende event

                    // Use SynchronizeCallbacks to specify that the object
                    // marshals callbacks across threads appropriately.
                    analogInReader.SynchronizeCallbacks = true; //Sørger for at sætte trådene til den prioritet som de skal have
                    analogInReader.BeginReadWaveform(Convert.ToInt32(20),
                        analogCallback, myTask);
                }
                catch (DaqException exception)
                {
                    runningTask = null;
                    myTask.Dispose();
                    throw exception;
                }
            }
        }
        public void startMåling()
        {
            if (runningTask == null)
            {
                try
                {
                    // Create a new task
                    myTask = new Task();

                    // Create a virtual channel
                    myTask.AIChannels.CreateVoltageChannel(DeviceName, "",
                        (AITerminalConfiguration)(-1), MinimumVolt,
                        MaximumVolt, AIVoltageUnits.Volts);

                    // Configure the timing parameters
                    myTask.Timing.ConfigureSampleClock("", SampleRate,
                        SampleClockActiveEdge.Rising, SampleQuantityMode.ContinuousSamples, 1000);
                    // EVT SAMPLESPRCHANNEL!

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

                    // Prepare the table for Data

                    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(SamplesPerChannel,
                    analogCallback, myTask);
                }
                catch (DaqException exception)
                {
                    // Display Errors
                    runningTask = null;
                    myTask.Dispose();
                }
            }
        }