Esempio n. 1
0
        /// <summary>
        /// Starts laser read and write tasks
        /// </summary>
        static void StartLaserTasks()
        {
            _laserWriteTask = new System.Threading.Tasks.Task(() =>
            {
                Task writeTask        = new Task("LaserWrite");
                double[] firstSamples = LaserFunction(0, _rate);
                writeTask.AOChannels.CreateVoltageChannel("Dev2/AO2", "", 0, 10, AOVoltageUnits.Volts);
                writeTask.Timing.ConfigureSampleClock("", _rate, SampleClockActiveEdge.Rising, SampleQuantityMode.ContinuousSamples);
                writeTask.Stream.WriteRegenerationMode = WriteRegenerationMode.DoNotAllowRegeneration;
                AnalogSingleChannelWriter dataWriter   = new AnalogSingleChannelWriter(writeTask.Stream);
                dataWriter.WriteMultiSample(false, firstSamples);
                writeTask.Start();
                long start_sample = _rate;
                while (!_writeStop.WaitOne(100))
                {
                    double[] samples = LaserFunction(start_sample, _rate);
                    if (samples == null)
                    {
                        break;
                    }
                    dataWriter.WriteMultiSample(false, samples);
                    start_sample += _rate;
                }
                writeTask.Dispose();
                Task resetTask = new Task("LaserReset");
                resetTask.AOChannels.CreateVoltageChannel("Dev2/AO2", "", 0, 10, AOVoltageUnits.Volts);
                AnalogSingleChannelWriter resetWriter = new AnalogSingleChannelWriter(resetTask.Stream);
                resetWriter.WriteSingleSample(true, 0);
                resetTask.Dispose();
            });

            _laserReadTask = new System.Threading.Tasks.Task(() =>
            {
                Task read_task = new Task("laserRead");
                read_task.AIChannels.CreateVoltageChannel("Dev2/ai16", "Laser", AITerminalConfiguration.Differential, -10, 10, AIVoltageUnits.Volts);
                read_task.Timing.ConfigureSampleClock("", _rate, SampleClockActiveEdge.Rising, SampleQuantityMode.ContinuousSamples);
                read_task.Start();
                AnalogSingleChannelReader laser_reader = new AnalogSingleChannelReader(read_task.Stream);
                while (!_readStop.WaitOne(10))
                {
                    var nsamples = read_task.Stream.AvailableSamplesPerChannel;
                    if (nsamples >= 10)
                    {
                        double[] read = laser_reader.ReadMultiSample((int)nsamples);
                        lock (_laser_aiv_lock)
                        {
                            foreach (double d in read)
                            {
                                //Simple exponential smoother
                                _laser_aiv = 0.9 * _laser_aiv + 0.1 * d;
                            }
                        }
                    }
                }
                read_task.Dispose();
            });
            _laserWriteTask.Start();
            _laserReadTask.Start();
        }
Esempio n. 2
0
        /// <summary>
        /// Start a constant output by the DAQ device. This function starts a task named "OutputTask",
        /// Don't forget to stop it when it's no longer needed.
        /// </summary>
        /// <param name="voltage">the requested voltage to apply</param>
        public void StartConstantOutputTask(double voltage)
        {
            int samplesPerChannel = 2500;
            int sampleRate = 2500;

            //
            // generate output array 
            //
            m_functionGenerator = new FunctionGenerator(samplesPerChannel, voltage, voltage);
            
            //
            // get the properties required for the output task
            //
            ContinuousAOTaskProperties outputProperties = new ContinuousAOTaskProperties(null, sampleRate, samplesPerChannel, voltage);
            
            //
            // create the output task
            //
            m_outputTask = m_daqController.CreateContinuousAOTask(outputProperties);

            //
            // create the writer of the output task
            //
            writer = new AnalogSingleChannelWriter(m_outputTask.Stream);

            //
            // write static voltage
            //
            writer.WriteMultiSample(true, m_functionGenerator.ConstWave);
        }
Esempio n. 3
0
        public void RunDAQ()
        {
            DigitalEdgeStartTriggerEdge triggerEdge = DigitalEdgeStartTriggerEdge.Rising;

            try
            {
                string s = string.Empty;
                s          = _name == "/ai1" ? "etalon" : "measured";
                inputTask  = new NationalInstruments.DAQmx.Task(s);
                outputTask = new NationalInstruments.DAQmx.Task(s + "_output");

                inputTask.AIChannels.CreateVoltageChannel(sInputName, "", AITerminalConfiguration.Pseudodifferential, inputDAQMinValue, inputDAQMaxValue, AIVoltageUnits.Volts);
                outputTask.AOChannels.CreateVoltageChannel(sOutputName, "", outputDAQMinValue, outputDAQMaxValue, AOVoltageUnits.Volts);

                inputTask.Timing.ConfigureSampleClock("", dRateIO, SampleClockActiveEdge.Rising, SampleQuantityMode.ContinuousSamples, iInputOutputSamples);
                outputTask.Timing.ConfigureSampleClock("", dRateIO, SampleClockActiveEdge.Rising, SampleQuantityMode.ContinuousSamples, iInputOutputSamples);

                outputTask.Triggers.StartTrigger.ConfigureDigitalEdgeTrigger(terminalNameBase + "ai/StartTrigger", triggerEdge);

                inputTask.Control(TaskAction.Verify);
                outputTask.Control(TaskAction.Verify);

                outputData = fGen.Data;

                writer = new AnalogSingleChannelWriter(outputTask.Stream);
                writer.WriteMultiSample(false, outputData);

                StartTask();
                outputTask.Start();
                inputTask.Start();

                //inputCallback = new AsyncCallback(InputReady);
                reader = new AnalogSingleChannelReader(inputTask.Stream);


                //------------ТЕСТОВЫЙ КУСОК------------ ЧТЕНИЕ В ЭТОМ ЖЕ ПОТОКЕ--
                double[] data = reader.ReadMultiSample(iInputOutputSamples);

                BufReadDAQReceived?.Invoke(data);
                StopTask();
                //----------------------------------------------------------------



                /*// Use SynchronizeCallbacks to specify that the object
                 * // marshals callbacks across threads appropriately.
                 * reader.SynchronizeCallbacks = bSynchronizeCallbacks;
                 *
                 * reader.BeginReadMultiSample(iInputOutputSamples, inputCallback, inputTask);*/
            }
            catch (Exception ex)
            {
                StopTask();
                WarningDAQUpdate?.Invoke(ex.Message);
            }
        }
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            // Maybe run shutdown code here. (i.e. release resources)
            bgwGetWL.CancelAsync();
            int    numberOfSamples = 1000;
            double currentPiezo    = ReaderAI.ReadSingleSample();

            double[] outputSteps = Enumerable.Range(0, numberOfSamples).Select(x => 0 + (currentPiezo - 0) * ((double)x / (numberOfSamples - 1))).Reverse().ToArray();
            WriterAO.WriteMultiSample(true, outputSteps);
            Thread.Sleep(1000); //need to wait for the sweep to finish
            Console.WriteLine("I'm out of here.");
        }
Esempio n. 5
0
        /// <summary>
        /// Включение постоянной генерации сигнала. Чтение и контроль ошибок при этом производится в CALLBACK. Для завершения генерации используй метод StopDAQGeneration()
        /// </summary>
        public void RunDAQGeneration()
        {
            DigitalEdgeStartTriggerEdge triggerEdge = DigitalEdgeStartTriggerEdge.Rising;

            try
            {
                string s = string.Empty;
                s          = _name == "/ai1" ? "etalon" : "measured";
                inputTask  = new NationalInstruments.DAQmx.Task(s);
                outputTask = new NationalInstruments.DAQmx.Task(s + "_output");

                inputTask.AIChannels.CreateVoltageChannel(sInputName, "", AITerminalConfiguration.Pseudodifferential, inputDAQMinValue, inputDAQMaxValue, AIVoltageUnits.Volts);
                outputTask.AOChannels.CreateVoltageChannel(sOutputName, "", outputDAQMinValue, outputDAQMaxValue, AOVoltageUnits.Volts);

                inputTask.Timing.ConfigureSampleClock("", dRateIO, SampleClockActiveEdge.Rising, SampleQuantityMode.ContinuousSamples, iInputOutputSamples);
                outputTask.Timing.ConfigureSampleClock("", dRateIO, SampleClockActiveEdge.Rising, SampleQuantityMode.ContinuousSamples, iInputOutputSamples);

                outputTask.Triggers.StartTrigger.ConfigureDigitalEdgeTrigger(terminalNameBase + "ai/StartTrigger", triggerEdge);

                inputTask.Control(TaskAction.Verify);
                outputTask.Control(TaskAction.Verify);

                outputData = fGen.Data;

                writer = new AnalogSingleChannelWriter(outputTask.Stream);
                writer.WriteMultiSample(false, outputData);

                StartTask();
                outputTask.Start();
                //inputTask.Start();

                inputCallback = new AsyncCallback(AnalogInCallback);
                reader        = new AnalogSingleChannelReader(inputTask.Stream);
                reader.SynchronizeCallbacks = true;
                //reader.BeginReadMultiSample(iInputOutputSamples, inputCallback, inputTask);
                reader.BeginReadWaveform(iInputOutputSamples, inputCallback, inputTask);



                //statusDAQtimer.Enabled = true;
            }
            catch (Exception ex)
            {
                StopTask();
                WarningDAQUpdate?.Invoke(ex.Message);
            }
        }
Esempio n. 6
0
    public void setChannelValues(int line, double[] values)
    {
        Task      task        = new Task();
        string    devFullname = string.Format("{0}/ao{1}", name, line);
        AOChannel channel     = task.AOChannels.CreateVoltageChannel(devFullname, "", 0.0, 10.0, AOVoltageUnits.Volts);

        task.Timing.ConfigureSampleClock("", 1000, SampleClockActiveEdge.Rising, SampleQuantityMode.FiniteSamples, values.Length);
        task.Stream.WriteRegenerationMode = WriteRegenerationMode.AllowRegeneration;
        AnalogSingleChannelWriter writer = new AnalogSingleChannelWriter(task.Stream);

        writer.WriteMultiSample(false, values);
        task.Start();
        while (task.IsDone == false)
        {
            ;
        }
        task.Dispose();
    }
Esempio n. 7
0
        public void WriteWaveformAnalogChannel(string lines, string name, int freq, int samples, int cycles, string sigtype, double ampl, double min, double max)
        {
            Task      analogWriteTask = new Task();
            AOChannel ch;

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

            try
            {
                // Create the task and channel
                //myTask = New Task()
                ch = analogWriteTask.AOChannels.CreateVoltageChannel(lines, "", min, max, AOVoltageUnits.Volts);

                // Verify the task before doing the waveform calculations
                analogWriteTask.Control(TaskAction.Verify);

                // Calculate some waveform parameters and generate data
                clsFunctionGenerator fGen = new clsFunctionGenerator(analogWriteTask.Timing, freq.ToString(), samples.ToString(), cycles.ToString(), sigtype, ampl.ToString());

                // Configure the sample clock with the calculated rate
                analogWriteTask.Timing.ConfigureSampleClock("", fGen.fgResultingSampleClockRate, SampleClockActiveEdge.Rising, SampleQuantityMode.ContinuousSamples, 1000);

                // Write the data to the buffer
                AnalogSingleChannelWriter writer = new AnalogSingleChannelWriter(analogWriteTask.Stream);
                writer.WriteMultiSample(false, fGen.fgData);
                IAsyncResult res;
                res = writer.BeginWriteMultiSample(false, fGen.fgData, _WriteAnalogChannelComplete, 0);

                //Start writing out data
                analogWriteTask.Start();
                analogWriteTask.Stop();
            }
            catch (DaqException ex) {
                DaqError(ex.Message);
            }
            finally {
                analogWriteTask.Dispose();
            }
        }
Esempio n. 8
0
        private void startButton_Click(object sender, System.EventArgs e)
        {
            // Change the mouse to an hourglass for the duration of this function.
            Cursor.Current = Cursors.WaitCursor;

            // Read UI selections
            DigitalEdgeStartTriggerEdge triggerEdge;

            if (this.triggerEdgeComboBox.Text == "Rising")
            {
                triggerEdge = DigitalEdgeStartTriggerEdge.Rising;
            }
            else
            {
                triggerEdge = DigitalEdgeStartTriggerEdge.Falling;
            }

            try
            {
                // Create the master and slave tasks
                inputTask  = new Task("inputTask");
                outputTask = new Task("outputTask");

                // Configure both tasks with the values selected on the UI.
                inputTask.AIChannels.CreateVoltageChannel(inputChannelComboBox.Text,
                                                          "",
                                                          AITerminalConfiguration.Differential,
                                                          Convert.ToDouble(inputMinValNumeric.Value),
                                                          Convert.ToDouble(inputMaxValNumeric.Value),
                                                          AIVoltageUnits.Volts);

                outputTask.AOChannels.CreateVoltageChannel(outputChannelComboBox.Text,
                                                           "",
                                                           Convert.ToDouble(outputMinValNumeric.Value),
                                                           Convert.ToDouble(outputMaxValNumeric.Value),
                                                           AOVoltageUnits.Volts);

                // Set up the timing
                inputTask.Timing.ConfigureSampleClock("",
                                                      Convert.ToDouble(rateNumeric.Value),
                                                      SampleClockActiveEdge.Rising,
                                                      SampleQuantityMode.ContinuousSamples,
                                                      Convert.ToInt32(samplesNumeric.Value));

                outputTask.Timing.ConfigureSampleClock("",
                                                       Convert.ToDouble(rateNumeric.Value),
                                                       SampleClockActiveEdge.Rising,
                                                       SampleQuantityMode.ContinuousSamples,
                                                       Convert.ToInt32(samplesNumeric.Value));

                // Set up the start trigger

                string deviceName       = inputChannelComboBox.Text.Split('/')[0];
                string terminalNameBase = "/" + GetDeviceName(deviceName) + "/";
                outputTask.Triggers.StartTrigger.ConfigureDigitalEdgeTrigger(terminalNameBase + "ai/StartTrigger",
                                                                             triggerEdge);

                // Verify the tasks
                inputTask.Control(TaskAction.Verify);
                outputTask.Control(TaskAction.Verify);

                // Write data to each output channel
                FunctionGenerator fGen = new FunctionGenerator(Convert.ToString(frequencyNumeric.Value),
                                                               Convert.ToString(samplesNumeric.Value),
                                                               Convert.ToString(frequencyNumeric.Value / (rateNumeric.Value / samplesNumeric.Value)),
                                                               waveformTypeComboBox.Text,
                                                               amplitudeNumeric.Value.ToString());

                output = fGen.Data;

                writer = new AnalogSingleChannelWriter(outputTask.Stream);
                writer.WriteMultiSample(false, output);

                // Officially start the task
                StartTask();

                outputTask.Start();
                inputTask.Start();

                // Start reading as well
                inputCallback = new AsyncCallback(InputRead);
                reader        = new AnalogSingleChannelReader(inputTask.Stream);

                // Use SynchronizeCallbacks to specify that the object
                // marshals callbacks across threads appropriately.
                reader.SynchronizeCallbacks = true;

                reader.BeginReadMultiSample(Convert.ToInt32(samplesNumeric.Value), inputCallback, inputTask);
            }
            catch (Exception ex)
            {
                StopTask();
                MessageBox.Show(ex.Message);
            }
        }
 public void ScanCavity(double[] rampVoltages, bool autostart)
 {
     cavityWriter.WriteMultiSample(autostart, rampVoltages);
 }
Esempio n. 10
0
 private void WriteAnalogFunction(double[] outputValues)
 {
     _writer.WriteMultiSample(AutoStart, outputValues);
 }
Esempio n. 11
0
        /// <summary>
        /// Initiate the output task writer, and apply an initial constant bias
        /// </summary>
        /// <param name="task">The output task that the writer will belong to</param>
        /// <param name="settings">The UI settings</param>
        private void InitiateOutputWriter(Task task, IVSettings settings)
        {
            //
            // generate output arrays
            //
            m_functionGenerator = new FunctionGenerator(settings.IVGeneralSettings.SamplesPerCycle,
                                                        settings.IVGeneralSettings.VoltageAmplitude,
                                                        settings.IVGeneralSettings.VoltageAmplitude);

            //
            // create the writer of the output task
            //
            writer = new AnalogSingleChannelWriter(m_outputTask.Stream);

            //
            // write static voltage
            //
            writer.WriteMultiSample(true, m_functionGenerator.ConstWave);
        }