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();
                }
            }
        }
Example #2
0
        public void Configure(double __dCycleTimeMilisec, int __iSteps, bool master, bool continuous)
        {
            _logger.Info("Configuring stage timing....");

            this.m_samplePeriod = __dCycleTimeMilisec / 1000;

            if (this.m_bMaster && this.m_sampleClock == null)
            {
                this.m_sampleClock = new NISampleClock(this.m_sDevice, "Ctr2");
            }

            if (this.m_daqtskLineTrigger != null)
            {
                if (this.m_daqtskLineTrigger.IsDone != true)
                {
                    this.m_daqtskLineTrigger.Stop();
                }

                this.m_daqtskLineTrigger.Control(TaskAction.Unreserve);
            }

            Task _lineTask = new Task();

            try
            {

                if (this.m_daqtskMoveStage == null)
                {
                    this.Initialize();
                }

                this.m_daqtskMoveStage.Timing.SampleTimingType = SampleTimingType.SampleClock;

                this.m_daqtskMoveStage.Timing.ConfigureSampleClock(
                    this.m_bMaster ? this.m_sampleClock.Terminal : this.m_sTimingSource,
                    1000 / __dCycleTimeMilisec,
                    SampleClockActiveEdge.Rising,
                    continuous ? SampleQuantityMode.ContinuousSamples : SampleQuantityMode.FiniteSamples,
                    __iSteps);

                _lineTask.DOChannels.CreateChannel(
                    this.m_sDevice + "/port0",
                    "test",
                    ChannelLineGrouping.OneChannelForAllLines);

                _lineTask.Timing.SampleTimingType = SampleTimingType.SampleClock;

                _lineTask.Timing.ConfigureSampleClock(
                    this.m_bMaster ? this.m_sampleClock.Terminal : this.m_sTimingSource,
                    1000 / __dCycleTimeMilisec,
                    SampleClockActiveEdge.Rising,
                    continuous ? SampleQuantityMode.ContinuousSamples : SampleQuantityMode.FiniteSamples,
                    __iSteps);

                _lineTask.Control(TaskAction.Verify);
                _lineTask.Control(TaskAction.Commit);
            }

            catch (DaqException ex)
            {
                if (_lineTask != null)
                {
                    _lineTask.Dispose();
                }

                _logger.Error("Error while setting timing!", ex);
            }

            if (_lineTask != null)
            {
                this.m_daqtskLineTrigger = _lineTask;
            }
        }
Example #3
0
        public void resetFlipFlop()
        {
            ResetSignal = new Task("Reset Signal");
            DOChannel myDOChannel;
            myDOChannel = ResetSignal.DOChannels.CreateChannel(
                prevodnikId + "/port0",
                "write0",
                ChannelLineGrouping.OneChannelForAllLines
                );

            writer = new DigitalSingleChannelWriter(ResetSignal.Stream);

            writer.WriteSingleSamplePort(true, 127);//nastavit P0 na 01111111, => reset

            Thread.Sleep(100);
            writer.WriteSingleSamplePort(true, 255);//nastavit P0 na 11111111, => reset resetu

            ResetSignal.Dispose();
        }
Example #4
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();
            }
        }
Example #5
0
        private void radioButton_stimCurrentControlled_Click(object sender, EventArgs e)
        {
            if (radioButton_stimCurrentControlled.Checked)
            {
                Properties.Settings.Default.StimVoltageControlled = false;

                if (Properties.Settings.Default.UseStimulator)
                {
                    stimIvsVTask = new Task("stimIvsV");
                    //stimIvsVTask.DOChannels.CreateChannel(Properties.Settings.Default.StimIvsVDevice + "/Port0/line8:15", "",
                    //    ChannelLineGrouping.OneChannelForAllLines);
                    stimIvsVTask.DOChannels.CreateChannel(Properties.Settings.Default.StimIvsVDevice + "/Port1/line0", "",
                        ChannelLineGrouping.OneChannelForAllLines);
                    stimIvsVWriter = new DigitalSingleChannelWriter(stimIvsVTask.Stream);
                    //stimIvsVTask.Timing.ConfigureSampleClock("100kHztimebase", 100000,
                    //    SampleClockActiveEdge.Rising, SampleQuantityMode.FiniteSamples);
                    stimIvsVTask.Control(TaskAction.Verify);
                    //byte[] b_array = new byte[5] { 255, 255, 255, 255, 255 };
                    //DigitalWaveform wfm = new DigitalWaveform(5, 8, DigitalState.ForceDown);
                    //wfm = NationalInstruments.DigitalWaveform.FromPort(b_array);
                    //stimIvsVWriter.WriteWaveform(true, wfm);
                    stimIvsVWriter.WriteSingleSampleSingleLine(true, true);
                    stimIvsVTask.WaitUntilDone();
                    stimIvsVTask.Stop();
                    stimIvsVTask.Dispose();
                }

                radioButton_impCurrent.Checked = true;
            }
        }
Example #6
0
        private void radioButton_stimVoltageControlled_Click(object sender, EventArgs e)
        {
            if (radioButton_stimVoltageControlled.Checked)
            {
                Properties.Settings.Default.StimVoltageControlled = true;
                if (Properties.Settings.Default.UseStimulator)
                {
                    //this line goes high (TTL-wise) when we're doing current-controlled stim, low for voltage-controlled
                    stimIvsVTask = new Task("stimIvsV");
                    stimIvsVTask.DOChannels.CreateChannel(Properties.Settings.Default.StimIvsVDevice + "/Port1/line0", "",
                        ChannelLineGrouping.OneChannelForAllLines);
                    stimIvsVWriter = new DigitalSingleChannelWriter(stimIvsVTask.Stream);
                    stimIvsVTask.Control(TaskAction.Verify);
                    stimIvsVWriter.WriteSingleSampleSingleLine(true, false);
                    stimIvsVTask.WaitUntilDone();
                    stimIvsVTask.Stop();
                    stimIvsVTask.Dispose();
                }

                radioButton_impVoltage.Checked = true;
            }
        }
Example #7
0
        /// <summary>
        /// Perform IV cycles while standing in place
        /// </summary>
        /// <param name="settings"></param>
        /// <param name="worker"></param>
        /// <param name="e"></param>
        public void IV_AcquireDataWithoutMoving(IVSettings settings, BackgroundWorker worker, DoWorkEventArgs e)
        {
            int finalFileNumber = settings.IVGeneralSettings.CurrentFileNumber;
            double[,] dataAcquired;
            List<IDataChannel> physicalChannels = new List<IDataChannel>();

            //
            // Save this run settings if desired
            //
            SaveSettingsIfNeeded(settings, settings.IVGeneralSettings.IsFileSavingRequired, settings.IVGeneralSettings.Path);

            //
            // apply initial voltage on the EM if needed
            //
            ApplyVoltageOnElectroMagnetIfNeeded(settings.IVSteppingMethodSettings.SteppingDevice == SteppingDevice.ElectroMagnet);


            //
            // create the input and output tasks
            //
            m_ivInputTask = GetContinuousAITask(settings.IVGeneralSettings.SampleRate, settings.ChannelsSettings.ActiveChannels, null);
            m_ivInputTask.Stream.ReadRelativeTo = ReadRelativeTo.FirstSample;
            m_outputTask = GetContinuousAOTask(settings);

            //
            // initiate writer for the output and set initial bias
            //
            InitiateOutputWriter(m_outputTask, settings);

            //
            // Main loop for data aquisition
            //
            for (int i = 0; i < settings.IVGeneralSettings.TotalNumberOfCycles; i++)
            {
                //
                // Cancel the operatin if user asked for
                //
                if (worker.CancellationPending == true)
                {
                    e.Cancel = true;
                    break;
                }

                m_quitRealTimeOperation = false;

                //
                // we set the votlage to triangle wave and then open the junction by the EM
                //
                writer.BeginWriteMultiSample(false, m_functionGenerator.TriangleWave, null, null);

                //
                // Start the input task.
                //
                try
                {
                    m_ivInputTask.Start();
                }
                catch (DaqException ex)
                {
                    throw new SBJException("Error occured when tryin to start DAQ input task", ex);
                }

                //
                // start reading continuously. 
                // when the junction is opened, the opening thread will change m_quitJuncctionOpeningOperation to true.
                // set dataAquired to null otherwise it saves last cycle's data. 
                //
                reader = new AnalogMultiChannelReader(m_ivInputTask.Stream);
                dataAcquired = null;
                try
                {
                    while (!m_quitRealTimeOperation)
                    {
                        try
                        {
                            dataAcquired = reader.ReadMultiSample(-1);
                        }
                        catch (DaqException)
                        {
                            continue;
                        }
                    }

                    if (dataAcquired != null)
                    {
                        if (settings.ChannelsSettings.ActiveChannels.Count != dataAcquired.GetLength(0))
                        {
                            throw new SBJException("Number of data channels doesn't fit the recieved data.");
                        }
                    }
                }
                catch (DaqException ex)
                {
                    //
                    // Probably timeout.
                    // Ignore this cycle and rerun.
                    //
                    m_ivInputTask.Stop();
                    continue;
                }

                //
                // At this point the reader has returned with all the data and we can stop the input task.
                //
                m_ivInputTask.Stop();

                //
                // if we didn't acquire any data, there's no need to save anything.
                //
                if (dataAcquired == null)
                {
                    continue;
                }

                //
                // Assign the aquired data for each channel.
                // First clear all data from previous interation.
                //                
                ClearRawData(settings.ChannelsSettings.ActiveChannels);
                AssignRawDataToChannels(settings.ChannelsSettings.ActiveChannels, dataAcquired);

                //
                // physical channel will include both simple and complex channels. 
                // 
                physicalChannels = GetChannelsForDisplay(settings.ChannelsSettings.ActiveChannels);

                //
                // calculate the physical data for each channel
                //
                GetPhysicalData(physicalChannels);

                //
                // the IV acquisition is done, we need to return the output to constant voltage for the next cycle
                //
                writer.BeginWriteMultiSample(false, m_functionGenerator.ConstWave, null, null);

                // 
                // Increase file number by one
                // Save data if needed
                //
                finalFileNumber++;
                if (settings.IVGeneralSettings.IsFileSavingRequired)
                {
                    finalFileNumber = SaveData(settings.IVGeneralSettings.Path, settings.ChannelsSettings.ActiveChannels, physicalChannels, finalFileNumber);
                }

                //
                // Signal UI we have the data
                //
                if (DataAquired != null)
                {
                    DataAquired(this, new DataAquiredEventArgs(physicalChannels, finalFileNumber));
                }
            }

            //
            // Finish the measurement properly
            //
            if (settings.IVSteppingMethodSettings.SteppingDevice == SteppingDevice.ElectroMagnet)
            {
                m_electroMagnet.Shutdown();
            }
            m_ivInputTask.Dispose();
            m_ivInputTask = null;
            m_outputTask.Dispose();
            m_outputTask = null;
            m_stepperMotor.Shutdown();
        }
Example #8
0
        //call this method after changing stimulation settings, or finishing a stimulation experiment
        //includes code to set dc offsets back to zero
        private void updateStim()
        {
            lock (this)
            {
                bool placedzeros = false;

                if (stimPulseTask != null || stimDigitalTask != null)
                {
                    try
                    {
                        // If we were ruuning a closed loop or open-loop protocol, this will zero the outputs
                        double[,] AnalogBuffer = new double[stimPulseTask.AOChannels.Count, STIMBUFFSIZE]; // buffer for analog channels
                        UInt32[] DigitalBuffer = new UInt32[STIMBUFFSIZE];

                        stimPulseTask.Stop();
                        stimDigitalTask.Stop();

                        stimPulseWriter.WriteMultiSample(true, AnalogBuffer);
                        stimDigitalWriter.WriteMultiSamplePort(true, DigitalBuffer);

                        stimPulseTask.WaitUntilDone(20);
                        stimDigitalTask.WaitUntilDone(20);

                        stimPulseTask.Stop();
                        stimDigitalTask.Stop();
                        placedzeros = true;
                    }
                    catch (Exception ex)
                    {
                        placedzeros = false;
                    }
                }
                if (stimDigitalTask != null)
                {
                    stimDigitalTask.Dispose();
                    stimDigitalTask = null;
                }
                if (stimPulseTask != null)
                {
                    stimPulseTask.Dispose();
                    stimPulseTask = null;
                }

                if (Properties.Settings.Default.UseStimulator)
                {
                    stimPulseTask = new Task("stimPulseTask");
                    stimDigitalTask = new Task("stimDigitalTask");
                    if (Properties.Settings.Default.StimPortBandwidth == 32)
                        stimDigitalTask.DOChannels.CreateChannel(Properties.Settings.Default.StimulatorDevice + "/Port0/line0:31", "",
                            ChannelLineGrouping.OneChannelForAllLines); //To control MUXes
                    else if (Properties.Settings.Default.StimPortBandwidth == 8)
                        stimDigitalTask.DOChannels.CreateChannel(Properties.Settings.Default.StimulatorDevice + "/Port0/line0:7", "",
                            ChannelLineGrouping.OneChannelForAllLines); //To control MUXes
                    if (Properties.Settings.Default.StimPortBandwidth == 32)
                    {
                        stimPulseTask.AOChannels.CreateVoltageChannel(Properties.Settings.Default.StimulatorDevice + "/ao0", "", -10.0, 10.0, AOVoltageUnits.Volts); //Triggers
                        stimPulseTask.AOChannels.CreateVoltageChannel(Properties.Settings.Default.StimulatorDevice + "/ao1", "", -10.0, 10.0, AOVoltageUnits.Volts); //Triggers
                        stimPulseTask.AOChannels.CreateVoltageChannel(Properties.Settings.Default.StimulatorDevice + "/ao2", "", -10.0, 10.0, AOVoltageUnits.Volts); //Actual Pulse
                        stimPulseTask.AOChannels.CreateVoltageChannel(Properties.Settings.Default.StimulatorDevice + "/ao3", "", -10.0, 10.0, AOVoltageUnits.Volts); //Timing
                    }
                    else if (Properties.Settings.Default.StimPortBandwidth == 8)
                    {
                        stimPulseTask.AOChannels.CreateVoltageChannel(Properties.Settings.Default.StimulatorDevice + "/ao0", "", -10.0, 10.0, AOVoltageUnits.Volts);
                        stimPulseTask.AOChannels.CreateVoltageChannel(Properties.Settings.Default.StimulatorDevice + "/ao1", "", -10.0, 10.0, AOVoltageUnits.Volts);
                    }

                    if (Properties.Settings.Default.UseCineplex)
                    {
                        stimPulseTask.Timing.ReferenceClockSource = videoTask.Timing.ReferenceClockSource;
                        stimPulseTask.Timing.ReferenceClockRate = videoTask.Timing.ReferenceClockRate;
                    }
                    else
                    {
                        stimPulseTask.Timing.ReferenceClockSource = "OnboardClock";
                        //stimPulseTask.Timing.ReferenceClockRate = 10000000.0; //10 MHz timebase
                    }
                    stimDigitalTask.Timing.ConfigureSampleClock("100kHzTimebase", STIM_SAMPLING_FREQ,
                       SampleClockActiveEdge.Rising, SampleQuantityMode.FiniteSamples);
                    stimPulseTask.Timing.ConfigureSampleClock("100kHzTimebase", STIM_SAMPLING_FREQ,
                        SampleClockActiveEdge.Rising, SampleQuantityMode.FiniteSamples);
                    stimDigitalTask.SynchronizeCallbacks = false;
                    stimPulseTask.SynchronizeCallbacks = false;

                    stimDigitalWriter = new DigitalSingleChannelWriter(stimDigitalTask.Stream);
                    stimPulseWriter = new AnalogMultiChannelWriter(stimPulseTask.Stream);

                    stimPulseTask.Triggers.StartTrigger.ConfigureDigitalEdgeTrigger(
                        "/" + Properties.Settings.Default.StimulatorDevice + "/PFI6", DigitalEdgeStartTriggerEdge.Rising);

                    stimDigitalTask.Control(TaskAction.Verify);
                    stimPulseTask.Control(TaskAction.Verify);

                    //Check to ensure one of the I/V buttons is checked
                    if (!radioButton_impCurrent.Checked && !radioButton_impVoltage.Checked)
                    {
                        radioButton_impCurrent.Checked = true;
                        radioButton_impVoltage.Checked = false;
                        radioButton_stimCurrentControlled.Checked = true;
                        radioButton_stimVoltageControlled.Checked = false;
                    }

                    if (Properties.Settings.Default.UseStimulator)
                    {
                        stimIvsVTask = new Task("stimIvsV");

                        stimIvsVTask.DOChannels.CreateChannel(Properties.Settings.Default.StimIvsVDevice + "/Port1/line0", "",
                            ChannelLineGrouping.OneChannelForAllLines);
                        stimIvsVWriter = new DigitalSingleChannelWriter(stimIvsVTask.Stream);
                        //stimIvsVTask.Timing.ConfigureSampleClock("100kHztimebase", 100000,
                        //    SampleClockActiveEdge.Rising, SampleQuantityMode.FiniteSamples);
                        stimIvsVTask.Control(TaskAction.Verify);
                        //byte[] b_array;
                        //if (radioButton_impCurrent.Checked)
                        //    b_array = new byte[5] { 255, 255, 255, 255, 255 };
                        //else
                        //    b_array = new byte[5] { 0, 0, 0, 0, 0 };
                        //DigitalWaveform wfm = new DigitalWaveform(5, 8, DigitalState.ForceDown);
                        //wfm = NationalInstruments.DigitalWaveform.FromPort(b_array);
                        //stimIvsVWriter.WriteWaveform(true, wfm);
                        if (radioButton_impCurrent.Checked) stimIvsVWriter.WriteSingleSampleSingleLine(true, true);
                        else stimIvsVWriter.WriteSingleSampleSingleLine(true, false);
                        stimIvsVTask.WaitUntilDone();
                        stimIvsVTask.Stop();
                        stimIvsVTask.Dispose();

                        if (!placedzeros)//try again
                        {

                            double[,] AnalogBuffer = new double[stimPulseTask.AOChannels.Count, STIMBUFFSIZE]; // buffer for analog channels
                            UInt32[] DigitalBuffer = new UInt32[STIMBUFFSIZE];

                            stimPulseTask.Stop();
                            stimDigitalTask.Stop();

                            stimPulseWriter.WriteMultiSample(true, AnalogBuffer);
                            stimDigitalWriter.WriteMultiSamplePort(true, DigitalBuffer);

                            //stimPulseTask.Start();

                            //stimDigitalTask.Start();
                            //stimPulseTask.WaitUntilDone();
                            stimPulseTask.Stop();
                            stimDigitalTask.Stop();

                        }
                    }

                    button_stim.Enabled = true;
                    button_stimExpt.Enabled = true;
                    openLoopStart.Enabled = true;
                    radioButton_impCurrent.Enabled = true;
                    radioButton_impVoltage.Enabled = true;
                    radioButton_stimCurrentControlled.Enabled = true;
                    radioButton_stimVoltageControlled.Enabled = true;
                    button_impedanceTest.Enabled = true;
                }
                else
                {
                    button_stim.Enabled = false;
                    button_stimExpt.Enabled = false;
                    openLoopStart.Enabled = false;
                    radioButton_impCurrent.Enabled = false;
                    radioButton_impVoltage.Enabled = false;
                    radioButton_stimCurrentControlled.Enabled = false;
                    radioButton_stimVoltageControlled.Enabled = false;
                    button_impedanceTest.Enabled = false;
                }
            }
            Console.WriteLine("updateStim");
        }
Example #9
0
        /// <summary>
        /// Manually aquire data
        /// This method continuously poll the buffer for data until it is stopped by the user.
        /// </summary>
        /// <param name="settings">The settings for running the aquisition</param>
        /// <returns>True whether the operation was cacled by the user. False otherwise.</returns>
        public bool AquireDataManually(SBJControllerSettings settings, BackgroundWorker worker, DoWorkEventArgs e)
        {
            //
            // Apply voltage with desired tool: Task or Keithley
            //
            ApplyVoltageIfNeeded(settings.GeneralSettings.UseKeithley,
                                 settings.GeneralSettings.Bias,
                                 settings.GeneralSettings.BiasError,
                                 settings.GeneralSettings.Range,
                                 settings.GeneralSettings.AutoRange);

            bool isCancelled = false;
            int finalFileNumber = settings.GeneralSettings.CurrentFileNumber;
       
            //
            // The array is intialized with size for 1 minute sampling.
            //
            double[,] dataAquired = new double[1000, 1000];

            List<IDataChannel> physicalChannels = new List<IDataChannel>();

            //
            // Configure the laser if needed for this run
            //
            ConfigureLaserIfNeeded(settings);

            //
            // Save this run settings if desired
            //
            SaveSettingsIfNeeded(settings, settings.GeneralSettings.IsFileSavingRequired, settings.GeneralSettings.Path);

            //
            //apply initial voltage on the EM
            //
            ApplyVoltageOnElectroMagnetIfNeeded(settings.ElectromagnetSettings.IsEMEnable);

            //
            // Create the task
            //
            m_activeTriggeredTask = GetContinuousAITask(settings.GeneralSettings.SampleRate, settings.ChannelsSettings.ActiveChannels, null);
            
            //
            // If EM is enabled, and we are asked to skip the first cycle (that is done by the stepper motor), 
            // then return.
            //
            if (settings.ElectromagnetSettings.IsEMEnable && settings.ElectromagnetSettings.IsEMSkipFirstCycleEnable)
            {
                m_stepperMotor.Shutdown();
                return false;
            }

            //
            // Turn off the laser before we reach contact
            //
            if (settings.LaserSettings.IsLaserOn)
            {
                m_LaserController.TurnOff();
                Thread.Sleep(5000);
            }

            //
            // Change the gain power to 5 before reaching contact
            // to ensure full contact current
            //
            if (settings.GeneralSettings.UseDefaultGain)
            {
                m_amplifier.ChangeGain(5);
            }

            //
            // Reach to contact before we start openning the junction
            // If EM is enabled and we're after the first cycle, use the EM.
            // If user asked to stop than exit
            //
            isCancelled = (settings.ElectromagnetSettings.IsEMEnable) ?
                           EMTryObtainShortCircuit(settings.ElectromagnetSettings.EMShortCircuitDelayTime, 
                                                   settings.GeneralSettings.ShortCircuitVoltage, worker, e) :
                           TryObtainShortCircuit(settings.GeneralSettings.ShortCircuitVoltage, settings.GeneralSettings.UseShortCircuitDelayTime,settings.GeneralSettings.ShortCircuitDelayTime, worker, e);
            if (isCancelled)
            {
                return false;
            }

            //
            // Configure the gain to the desired one before strating the measurement.
            // And also this is the time to switch the laser on.
            //
            if (settings.GeneralSettings.UseDefaultGain)
            {
                int gainPower;
                Int32.TryParse(settings.GeneralSettings.Gain, out gainPower);
                m_amplifier.ChangeGain(gainPower);
            }


            if (settings.LaserSettings.IsLaserOn)
            {
                m_LaserController.TurnOn();
            }

            //
            // Start openning the junction.
            // If EM is enabled then use it.
            //
            if (settings.ElectromagnetSettings.IsEMEnable)
            {
                m_stepperMotor.Shutdown();
                EMBeginOpenJunction(settings, worker, e);                
            }
            else
            {
                BeginOpenJunction(settings, worker, e);
            }

            //
            // Start the task and wait for the data
            //
            try
            {
                m_activeTriggeredTask.Start();
            }
            catch (DaqException ex)
            {
                throw new SBJException("Error occured when tryin to start DAQ task", ex);
            }

            AnalogMultiChannelReader reader = new AnalogMultiChannelReader(m_activeTriggeredTask.Stream);
            List<List<double>> averagedData = new List<List<double>>(settings.ChannelsSettings.ActiveChannels.Count);

            for (int i = 0; i < averagedData.Capacity; i++)
            {
                averagedData.Add(new List<double>());
            }

            try
            {
                //
                // Before getting all the data clear the lists.
                //
                ClearRawData(settings.ChannelsSettings.ActiveChannels);              

                //
                // As long as the user didn't ask to stop the acquisition 
                // (which is signaled by the stop of the stepper motion)
                // we coninue sampling.
                //
                while (!m_quitJunctionOpenningOperation)
                {
                    //
                    // Read all available data points in the buffer that
                    // were not read so far.
                    //
                    dataAquired = reader.ReadMultiSample(-1);

                    //
                    // Get average for the acquired the data and assign to variable
                    //
                    List<double> averageDataValues = GetAverageDataValue(dataAquired);
                    for (int i = 0; i < averageDataValues.Count; i++)
                    {                        
                        averagedData[i].Add(averageDataValues[i]);
                    }
                      
                    dataAquired = null;
 
                    //
                    // Cancel the operatin if user asked for
                    // We do it at the end of the loop to make sure we 
                    // saved all the data we have available.
                    //
                    if (worker.CancellationPending == true)
                    {
                        e.Cancel = true;
                        break;
                    }
                }                
            }
            catch (DaqException)
            {
                //
                // In case of an error just return
                //
                m_activeTriggeredTask.Stop();
                m_activeTriggeredTask.Dispose();
                if (m_LaserController != null)
                {
                m_LaserController.TurnOff();
                }
                if (m_taborFirstEOMController != null)
                {
                    m_taborFirstEOMController.TurnOff();
                }
                if (m_taborSecondEOMController != null)
                {
                    m_taborSecondEOMController.TurnOff();
                }
                return false;
            }

            //
            // At this point the user had requested to stop the data aquisition.
            // By signaling "stop". We can stop the task.
            //            
            m_activeTriggeredTask.Stop();

            //
            // Assign the aquired data for each channel after an average process
            //                    
            AssignRawDataToChannels(settings.ChannelsSettings.ActiveChannels, ConvertDataToMatrix(GetAveragedData(averagedData, 5000)));

            //
            // physical channel will include both simple and complex channels. 
            // 
            physicalChannels = GetChannelsForDisplay(settings.ChannelsSettings.ActiveChannels);

            //
            // calculate the physical data for each channel
            //
            GetPhysicalData(physicalChannels);

            // 
            // Increase file number by one
            // Save data if needed
            //
            finalFileNumber++;
            if (settings.GeneralSettings.IsFileSavingRequired)
            {
                finalFileNumber = SaveData(settings.GeneralSettings.Path, settings.ChannelsSettings.ActiveChannels, physicalChannels, finalFileNumber);
            }

            //
            // Signal UI we have the data
            //
            if (DataAquired != null)
            {
                DataAquired(this, new DataAquiredEventArgs(physicalChannels, finalFileNumber));
            }
            

            //
            // Finish the measurement properly
            //
            if (settings.LaserSettings.IsLaserOn)
            {
                m_LaserController.TurnOff();
            }
            if (settings.ElectromagnetSettings.IsEMEnable)
            {
                m_electroMagnet.Shutdown();
            }
            if (settings.LaserSettings.IsFirstEOMOn)
            {
                m_taborFirstEOMController.TurnOff();
            }
            if (settings.LaserSettings.IsSecondEOMOn)
            {
                m_taborSecondEOMController.TurnOff();
            }

            m_activeTriggeredTask.Dispose();
            m_stepperMotor.Shutdown();

            return (isCancelled || e.Cancel);
        }
Example #10
0
        /// <summary>
        /// Manually aquire data
        /// This method continuously poll the buffer for data until it is stopped by the user.
        /// </summary>
        /// <param name="settings">The settings for running the aquisition</param>
        /// <returns>True whether the operation was cacled by the user. False otherwise.</returns>
        public bool AquireDataContinuously(SBJControllerSettings settings, BackgroundWorker worker, DoWorkEventArgs e)
        {
            //
            // Apply voltage with desired tool: Task or Keithley
            //
            ApplyVoltageIfNeeded(settings.GeneralSettings.UseKeithley,
                                 settings.GeneralSettings.Bias,
                                 settings.GeneralSettings.BiasError,
                                 settings.GeneralSettings.Range,
                                 settings.GeneralSettings.AutoRange);
            bool isCancelled = false;
            int finalFileNumber = settings.GeneralSettings.CurrentFileNumber;

            //
            // The array is intialized with size for 1 minute sampling.
            //
            double[,] dataAquired = new double[1000, 1000];

            List<IDataChannel> physicalChannels = new List<IDataChannel>();

            //
            // Configure the laser if needed for this run
            //
            ConfigureLaserIfNeeded(settings);

            //
            // Save this run settings if desired
            //
            SaveSettingsIfNeeded(settings, settings.GeneralSettings.IsFileSavingRequired, settings.GeneralSettings.Path);

            //
            //apply initial voltage on the EM
            //
            ApplyVoltageOnElectroMagnetIfNeeded(settings.ElectromagnetSettings.IsEMEnable);

            //
            // Create the task
            //
            m_activeTriggeredTask = GetContinuousAITask(settings.GeneralSettings.SampleRate, settings.ChannelsSettings.ActiveChannels, null);

            //
            // If EM is enabled, and we are asked to skip the first cycle (that is done by the stepper motor), 
            // then return.
            //
            if (settings.ElectromagnetSettings.IsEMEnable && settings.ElectromagnetSettings.IsEMSkipFirstCycleEnable)
            {
                m_stepperMotor.Shutdown();
                return false;
            } 

            if (settings.LaserSettings.IsLaserOn)
            {
                m_LaserController.TurnOn();
            }
           

            //
            // Start the task and wait for the data
            //
            try
            {
                m_activeTriggeredTask.Start();
            }
            catch (DaqException ex)
            {
                throw new SBJException("Error occured when tryin to start DAQ task", ex);
            }

            AnalogMultiChannelReader reader = new AnalogMultiChannelReader(m_activeTriggeredTask.Stream);
            List<List<double>> fullData = new List<List<double>>(settings.ChannelsSettings.ActiveChannels.Count);

            for (int i = 0; i < fullData.Capacity; i++)
            {
                fullData.Add(new List<double>());
            }

            try
            {
                //
                // Before getting all the data clear the lists.
                //
                ClearRawData(settings.ChannelsSettings.ActiveChannels);

                //
                // As long as the user didn't ask to stop the acquisition 
                // (which is signaled by the stop of the stepper motion)
                // we coninue sampling.
                //
                while (!worker.CancellationPending)
                {
                    //
                    // Read all available data points in the buffer that
                    // were not read so far.
                    //
                    dataAquired = reader.ReadMultiSample(-1);
                    fullData = AccumulateData(fullData, dataAquired);                    
                    dataAquired = null;                  
                }
            }
            catch (DaqException)
            {
                //
                // In case of an error just return
                //
                m_activeTriggeredTask.Stop();
                m_activeTriggeredTask.Dispose();
                if (m_LaserController != null)
                {
                    m_LaserController.TurnOff();
                }
                if (m_taborFirstEOMController != null)
                {
                    m_taborFirstEOMController.TurnOff();
                }
                if (m_taborSecondEOMController != null)
                {
                    m_taborSecondEOMController.TurnOff();
                }
                return false;
            }

            //
            // At this point the user had requested to stop the data aquisition.
            // By signaling "stop". We can stop the task.
            //            
            m_activeTriggeredTask.Stop();

            //
            // Assign the aquired data for each channel after an average process
            //                    
            AssignRawDataToChannels(settings.ChannelsSettings.ActiveChannels, ConvertDataToMatrix(fullData));

            //
            // physical channel will include both simple and complex channels. 
            // 
            physicalChannels = GetChannelsForDisplay(settings.ChannelsSettings.ActiveChannels);

            //
            // calculate the physical data for each channel
            //
            GetPhysicalData(physicalChannels);

            // 
            // Increase file number by one
            // Save data if needed
            //
            finalFileNumber++;
            if (settings.GeneralSettings.IsFileSavingRequired)
            {
                finalFileNumber = SaveData(settings.GeneralSettings.Path, settings.ChannelsSettings.ActiveChannels, physicalChannels, finalFileNumber);
            }

            //
            // Signal UI we have the data
            //
            if (DataAquired != null)
            {
                DataAquired(this, new DataAquiredEventArgs(physicalChannels, finalFileNumber));
            }


            //
            // Finish the measurement properly
            //
            if (settings.LaserSettings.IsLaserOn)
            {
                m_LaserController.TurnOff();
            }
            if (settings.ElectromagnetSettings.IsEMEnable)
            {
                m_electroMagnet.Shutdown();
            }
            if (settings.LaserSettings.IsFirstEOMOn)
            {
                m_taborFirstEOMController.TurnOff();
            }
            if (settings.LaserSettings.IsSecondEOMOn)
            {
                m_taborSecondEOMController.TurnOff();
            }

            m_activeTriggeredTask.Dispose();
            m_stepperMotor.Shutdown();

            return (isCancelled || e.Cancel);
        }
Example #11
0
        /// <summary>
        /// Data aquisition
        /// </summary>
        /// <param name="settings">The settings for running the aquisition</param>
        /// <returns>True whether the operation was cacled by the user. False otherwise.</returns>
        public bool AquireData(SBJControllerSettings settings, BackgroundWorker worker, DoWorkEventArgs e)
        {
            bool isCancelled = false;
            //
            // Apply voltage with desired tool: Task or Keithley
            //
            ApplyVoltageIfNeeded(settings.GeneralSettings.UseKeithley, 
                                 settings.GeneralSettings.Bias, 
                                 settings.GeneralSettings.BiasError,
                                 settings.GeneralSettings.Range,
                                 settings.GeneralSettings.AutoRange);

            //
            // Use Lambda Zup to apply constant voltage on external electromagnet if needed
            //
            UseLambdaZupIfNeeded(settings.LambdaZupSettings.IsLambdaZupEnable,
                                 settings.LambdaZupSettings.OutputVoltage);

            //
            // Configure the laser if needed for this run
            //
            ConfigureLaserIfNeeded(settings);

            //
            // Save this run settings if desired
            //
            SaveSettingsIfNeeded(settings, settings.GeneralSettings.IsFileSavingRequired, settings.GeneralSettings.Path);

            //
            //apply initial voltage on the EM
            //
            ApplyVoltageOnElectroMagnetIfNeeded(settings.ElectromagnetSettings.IsEMEnable);

            //
            // Change to E5 gain to determine current sign (+/-) in order to configure the task correctly
            // This is also used to disable auto range once reached to contact.
            //
            m_amplifier.ChangeGain(5);
            //
            // Create the task
            //
            switch (settings.GeneralSettings.RunDirection)
            {
                case RunDirection.Both:
                    //TODO: Add implementation for both direction measurement
                    break;
                case RunDirection.Break:
                    m_firstTriggeredTask = GetMultipleChannelsTriggeredTask(settings, "firstTriggeredTask" ,RunDirection.Break, 0, 0, worker, e);
                    m_firstTriggeredTask.Control(TaskAction.Verify);
                    double level = m_firstTriggeredTask.Triggers.ReferenceTrigger.AnalogEdge.Level * -1;
                    AnalogEdgeReferenceTriggerSlope slope = m_firstTriggeredTask.Triggers.ReferenceTrigger.AnalogEdge.Slope == AnalogEdgeReferenceTriggerSlope.Falling ? AnalogEdgeReferenceTriggerSlope.Rising : AnalogEdgeReferenceTriggerSlope.Falling;
                    m_secondaryTriggeredTask = GetMultipleChannelsTriggeredTask(settings, "secondaryTriggeredTask",  RunDirection.Break, slope, level , worker, e);
                    isCancelled = PerformBreakJunctionCycles(settings, worker, e);
                    break;
                case RunDirection.Make:
                    m_activeTriggeredTask = GetMultipleChannelsTriggeredTask(settings, null,RunDirection.Make, m_triggerSlope, m_triggerVoltage, worker, e);
                    isCancelled = PerformMakeJunctionCycles(settings, worker, e);                    
                    break;
            }     

            //
            // Finish the measurement properly
            //
            if (settings.LaserSettings.IsLaserOn)
            {
                m_LaserController.TurnOff();
            }
            if (settings.ElectromagnetSettings.IsEMEnable)
            {
                m_electroMagnet.Shutdown();
            }
            if (settings.LaserSettings.IsFirstEOMOn)
            {
                m_taborFirstEOMController.TurnOff();
            }
            if (settings.LaserSettings.IsSecondEOMOn)
            {
                m_taborSecondEOMController.TurnOff();
            }
            if (settings.LambdaZupSettings.IsLambdaZupEnable)
            {
                m_lambdaZup.TurnOffOutput();
            }
            m_activeTriggeredTask.Dispose();
            m_firstTriggeredTask.Dispose();
            m_secondaryTriggeredTask.Dispose();
            m_stepperMotor.Shutdown();

            return isCancelled;
        }      
Example #12
0
        /// <summary>
        /// Reach to position specified by conductance value and then stop and aqcuire data until asked to stop.
        /// </summary>
        /// <param name="settings"></param>
        /// <param name="worker"></param>
        /// <param name="e"></param>
        /// <returns></returns>
        private bool ReachToPositionByMovingUp(SBJControllerSettings settings, BackgroundWorker worker, DoWorkEventArgs e)
        {
            double[,] dataAcquired = new double[1000, 1000];
            int finalFileNumber = settings.GeneralSettings.CurrentFileNumber;
            List<IDataChannel> physicalChannels = new List<IDataChannel>();


            for (int i = 0; i < settings.GeneralSettings.TotalNumberOfCycles; i++)
            {
                //
                // Cancel the operatin if user asked for
                //
                if (worker.CancellationPending == true)
                {
                    e.Cancel = true;
                    break;
                }

                //
                // This flag is used to signal us when the user asked to stop the real time data acquisition
                //
                m_quitRealTimeOperation = false;
                m_activeTriggeredTask = GetMultipleChannelsTriggeredTask(settings, null, RunDirection.Break, m_triggerSlope, m_triggerVoltage, worker, e);
                m_activeTriggeredTask.EveryNSamplesReadEventInterval = settings.GeneralSettings.TotalSamples;
                m_activeTriggeredTask.Done += new TaskDoneEventHandler(OnTaskDoneOpenning);
                m_activeTriggeredTask.Control(TaskAction.Verify);
                m_triggerSlope = m_activeTriggeredTask.Triggers.ReferenceTrigger.AnalogEdge.Slope;
                m_triggerVoltage = m_activeTriggeredTask.Triggers.ReferenceTrigger.AnalogEdge.Level;

                //
                // physical channel will include both simple and complex channels. 
                // 
                physicalChannels = GetChannelsForDisplay(settings.ChannelsSettings.ActiveChannels);

                //
                // Assign the aquired data for each channel.
                // First clear all data from previous interation.
                //                
                ClearRawData(settings.ChannelsSettings.ActiveChannels);

                //
                // Create the tasks: One for triggering us to stop and the other for start monitoring the data
                //
                m_realTimeTask = GetContinuousAITask(settings.GeneralSettings.SampleRate, settings.ChannelsSettings.ActiveChannels, null);
                AnalogMultiChannelReader realTimeReader = new AnalogMultiChannelReader(m_realTimeTask.Stream);

                //
                // Start closing the junction.
                // If EM is enabled use the EM.
                //
                if (settings.ElectromagnetSettings.IsEMEnable)
                {
                    EMTryObtainShortCircuit(settings.ElectromagnetSettings.EMShortCircuitDelayTime, settings.GeneralSettings.ShortCircuitVoltage, worker, e);
                }
                else
                {
                    TryObtainShortCircuit(settings.GeneralSettings.ShortCircuitVoltage, settings.GeneralSettings.UseShortCircuitDelayTime,settings.GeneralSettings.ShortCircuitDelayTime, worker, e);
                }

                //
                // Start openning the junction. ASync operation.
                // If EM is enabled use the EM.
                //
                if (settings.ElectromagnetSettings.IsEMEnable)
                {
                    EMBeginOpenJunction(settings, worker, e);
                }
                else
                {
                    BeginOpenJunction(settings, worker, e);
                }

                //
                // Cancel the operatin if user asked for
                //
                if (worker.CancellationPending == true)
                {
                    e.Cancel = true;
                    break;
                }

                //
                // Start the triggered task. 
                //
                m_activeTriggeredTask.Start();

                //
                // If the user asked to stop the operation on the external thread then
                // WaitUntilDone will throw an expection. We can ignore that and return.
                //
                try
                {
                    m_activeTriggeredTask.WaitUntilDone();
                }
                catch (DaqException)
                {
                    //
                    // We got here if the user asked to stop the operation
                    //
                    break;
                }

                //
                // We reach this point only after we reached the desired conductance value.
                // As long as the user didn't ask to stop the operation continue recording the data.
                //
                while (!m_quitRealTimeOperation)
                {
                    //
                    // Read operation implicity start the task without the need to call Start() method.
                    //
                    try
                    {
                        dataAcquired = realTimeReader.ReadMultiSample(-1);
                    }
                    catch (DaqException)
                    {
                        continue;
                    }


                    if (dataAcquired.Length == 0)
                    {
                        continue;
                    }
                    //
                    // Assign the aquired data for each channel.
                    //                            
                    AssignRawDataToChannels(settings.ChannelsSettings.ActiveChannels, dataAcquired);

                    //
                    // calculate the physical data for each channel
                    //
                    GetPhysicalData(physicalChannels);

                    //
                    // Signal UI we have the data
                    //
                    if (DataAquired != null)
                    {
                        DataAquired(this, new DataAquiredEventArgs(physicalChannels, finalFileNumber));
                    }
                }

                if (DoneReadingData != null)
                {
                    DoneReadingData(this, null);
                }
                m_realTimeTask.Stop();
                m_realTimeTask.Dispose();

                // 
                // Increase file number by one
                // Save data if needed
                //
                finalFileNumber++;
                if (settings.GeneralSettings.IsFileSavingRequired)
                {
                    finalFileNumber = SaveData(settings.GeneralSettings.Path, settings.ChannelsSettings.ActiveChannels, physicalChannels, finalFileNumber);
                }
            }

            m_activeTriggeredTask.Dispose();
            m_realTimeTask.Dispose();
            m_triggerSlope = 0;
            m_triggerVoltage = 0;
            return e.Cancel;
        }
Example #13
0
        // Look at the stimulation hardware settings and create NI Tasks that reflect the user's choices
        private void UpdateStimulationSettings()
        {
            try
            {
                if (stimPulseTask != null) { stimPulseTask.Dispose(); stimPulseTask = null; }
                if (stimDigitalTask != null) { stimDigitalTask.Dispose(); stimDigitalTask = null; }
                if (Properties.Settings.Default.UseStimulator)
                {
                    if (stimDigitalTask == null)
                    {
                        stimDigitalTask = new Task("stimDigitalTask");
                        stimPulseTask = new Task("stimPulseTask");
                        if (Properties.Settings.Default.StimPortBandwidth == 32)
                            stimDigitalTask.DOChannels.CreateChannel(Properties.Settings.Default.StimulatorDevice + "/Port0/line0:31", "",
                                ChannelLineGrouping.OneChannelForAllLines); //To control MUXes
                        else if (Properties.Settings.Default.StimPortBandwidth == 8)
                            stimDigitalTask.DOChannels.CreateChannel(Properties.Settings.Default.StimulatorDevice + "/Port0/line0:7", "",
                                ChannelLineGrouping.OneChannelForAllLines); //To control MUXes
                        if (Properties.Settings.Default.StimPortBandwidth == 32)
                        {
                            stimPulseTask.AOChannels.CreateVoltageChannel(Properties.Settings.Default.StimulatorDevice + "/ao0", "", -10.0, 10.0, AOVoltageUnits.Volts); //Triggers
                            stimPulseTask.AOChannels.CreateVoltageChannel(Properties.Settings.Default.StimulatorDevice + "/ao1", "", -10.0, 10.0, AOVoltageUnits.Volts); //Triggers
                            stimPulseTask.AOChannels.CreateVoltageChannel(Properties.Settings.Default.StimulatorDevice + "/ao2", "", -10.0, 10.0, AOVoltageUnits.Volts); //Actual Pulse
                            stimPulseTask.AOChannels.CreateVoltageChannel(Properties.Settings.Default.StimulatorDevice + "/ao3", "", -10.0, 10.0, AOVoltageUnits.Volts); //Timing
                        }
                        else if (Properties.Settings.Default.StimPortBandwidth == 8)
                        {
                            stimPulseTask.AOChannels.CreateVoltageChannel(Properties.Settings.Default.StimulatorDevice + "/ao0", "", -10.0, 10.0, AOVoltageUnits.Volts);
                            stimPulseTask.AOChannels.CreateVoltageChannel(Properties.Settings.Default.StimulatorDevice + "/ao1", "", -10.0, 10.0, AOVoltageUnits.Volts);
                        }

                        if (Properties.Settings.Default.UseCineplex)
                        {
                            stimPulseTask.Timing.ReferenceClockSource = videoTask.Timing.ReferenceClockSource;
                            stimPulseTask.Timing.ReferenceClockRate = videoTask.Timing.ReferenceClockRate;
                        }
                        else
                        {
                            string tmp1 = Properties.Settings.Default.StimulatorDevice.ToString();
                            string tmp2 = Properties.Settings.Default.AnalogInDevice[0].ToString();
                            if (tmp1.Equals(tmp2))
                            {
                                stimPulseTask.Timing.ReferenceClockSource = "OnboardClock";
                            }
                            else
                            {
                                stimPulseTask.Timing.ReferenceClockSource = "/" + Properties.Settings.Default.StimulatorDevice.ToString() + "/PFI0";
                                stimPulseTask.Timing.ReferenceClockRate = 10000000.0; //10 MHz timebase
                            }
                        }

                        stimDigitalTask.Timing.ConfigureSampleClock("100KHzTimebase", STIM_SAMPLING_FREQ,
                           SampleClockActiveEdge.Rising, SampleQuantityMode.FiniteSamples);
                        stimPulseTask.Timing.ConfigureSampleClock("100KHzTimebase", STIM_SAMPLING_FREQ,
                            SampleClockActiveEdge.Rising, SampleQuantityMode.FiniteSamples);
                        stimDigitalTask.SynchronizeCallbacks = false;
                        stimPulseTask.SynchronizeCallbacks = false;

                        stimDigitalWriter = new DigitalSingleChannelWriter(stimDigitalTask.Stream);
                        stimPulseWriter = new AnalogMultiChannelWriter(stimPulseTask.Stream);

                        stimPulseTask.Triggers.StartTrigger.ConfigureDigitalEdgeTrigger(
                            "/" + Properties.Settings.Default.StimulatorDevice + "/PFI6", DigitalEdgeStartTriggerEdge.Rising);

                        stimDigitalTask.Control(TaskAction.Verify);
                        stimPulseTask.Control(TaskAction.Verify);

                        //Check to ensure one of the I/V buttons is checked
                        if (!radioButton_impCurrent.Checked && !radioButton_impVoltage.Checked)
                        {
                            radioButton_impCurrent.Checked = true;
                            radioButton_impVoltage.Checked = false;
                            radioButton_stimCurrentControlled.Checked = true;
                            radioButton_stimVoltageControlled.Checked = false;
                        }

                        if (Properties.Settings.Default.UseStimulator)
                        {
                            stimIvsVTask = new Task("stimIvsV");
                            stimIvsVTask.DOChannels.CreateChannel(Properties.Settings.Default.StimIvsVDevice + "/Port1/line0", "",
                                ChannelLineGrouping.OneChannelForAllLines);
                            stimIvsVWriter = new DigitalSingleChannelWriter(stimIvsVTask.Stream);
                            stimIvsVTask.Control(TaskAction.Verify);
                            if (radioButton_impCurrent.Checked) stimIvsVWriter.WriteSingleSampleSingleLine(true, true);
                            else stimIvsVWriter.WriteSingleSampleSingleLine(true, false);
                            stimIvsVTask.WaitUntilDone();
                            //stimIvsVTask.Stop();
                            stimIvsVTask.Dispose();
                        }
                    }

                    button_stim.Enabled = true;
                    button_stimExpt.Enabled = true;
                    openLoopStart.Enabled = true;
                    radioButton_impCurrent.Enabled = true;
                    radioButton_impVoltage.Enabled = true;
                    radioButton_stimCurrentControlled.Enabled = true;
                    radioButton_stimVoltageControlled.Enabled = true;
                    button_impedanceTest.Enabled = true;
                }
                else
                {
                    button_stim.Enabled = false;
                    button_stimExpt.Enabled = false;
                    openLoopStart.Enabled = false;
                    radioButton_impCurrent.Enabled = false;
                    radioButton_impVoltage.Enabled = false;
                    radioButton_stimCurrentControlled.Enabled = false;
                    radioButton_stimVoltageControlled.Enabled = false;
                    button_impedanceTest.Enabled = false;
                }
                Console.WriteLine("UpdateStimulationSettings completed");
            }
            catch (DaqException exception)
            {
                MessageBox.Show(exception.Message); //Display Errors
                reset();
            }
        }
Example #14
0
        public void Initialize()
        {
            _logger.Info("Initializing analog Stage....");

            // Setup an Analog Out task to move the stage along X and Y.
            Task _daqtskTask = new Task();

            try
            {
                // Add AO channels.
                _daqtskTask.AOChannels.CreateVoltageChannel("/" + this.m_sDevice + "/ao0", "aoChannelX", m_dVoltageMin, m_dVoltageMax, AOVoltageUnits.Volts);
                _daqtskTask.AOChannels.CreateVoltageChannel("/" + this.m_sDevice + "/ao1", "aoChannelY", m_dVoltageMin, m_dVoltageMax, AOVoltageUnits.Volts);
                _daqtskTask.AOChannels.CreateVoltageChannel("/" + this.m_sDevice + "/ao2", "aoChannelZ", m_dVoltageMin, m_dVoltageMax, AOVoltageUnits.Volts);

                // checked IFilteredTypeDescriptor everything is OK.
                _daqtskTask.Control(TaskAction.Verify);

                // Assign the task.
                this.m_daqtskMoveStage = _daqtskTask;

                // Return a status indication for the stage.
                this.m_bIsInitialized = true;
            }

            catch (DaqException exception)
            {
                if (_daqtskTask != null)
                {
                    _daqtskTask.Dispose();
                }

                this.m_bIsInitialized = false;

                _logger.Error("Unable to connect set up AO channels for Move task!" + exception.Message);
            }

            // If everything went well, tell everyone.
            if (EngagedChanged != null)
            {
                EngagedChanged(this, new EventArgs());
            }

            _logger.Info("Init Stage Done!");
        }
Example #15
0
        /// <summary>
        /// Do Cycles of closing and opening the junction, while measuring IVs
        /// </summary>
        /// <param name="settings"></param>
        /// <param name="worker"></param>
        /// <param name="e"></param>
        public void IV_AcquireData(IVSettings settings,BackgroundWorker worker, DoWorkEventArgs e)
        {
            bool isCancelled = false;
            int finalFileNumber = settings.IVGeneralSettings.CurrentFileNumber;
            double[,] dataAcquired;
            List<IDataChannel> physicalChannels = new List<IDataChannel>();

            //
            // Save this run settings if desired
            //
            SaveSettingsIfNeeded(settings, settings.IVGeneralSettings.IsFileSavingRequired, settings.IVGeneralSettings.Path);

            //
            // apply initial voltage on the EM if needed
            //
            ApplyVoltageOnElectroMagnetIfNeeded(settings.IVSteppingMethodSettings.SteppingDevice == SteppingDevice.ElectroMagnet);

            
            //
            // create the input and output tasks
            //
            m_ivInputTask = GetContinuousAITask(settings.IVGeneralSettings.SampleRate, settings.ChannelsSettings.ActiveChannels, null);
            m_ivInputTask.Stream.ReadRelativeTo = ReadRelativeTo.FirstSample;
            m_outputTask = GetContinuousAOTask(settings);

            //
            // initiate writer for the output and set initial bias
            //
            InitiateOutputWriter(m_outputTask, settings);
            
            //
            // Main loop for data aquisition
            //
            for (int i = 0; i < settings.IVGeneralSettings.TotalNumberOfCycles; i++)
            {
                //
                // Cancel the operatin if user asked for
                //
                if (worker.CancellationPending == true)
                {
                    e.Cancel = true;
                    break;
                }

                //
                // if we use EM, and we are asked to skip the first cycle (that is done by the stepper motor), 
                // move on to the next cycle.
                //
                if (i == 0 && settings.IVSteppingMethodSettings.SteppingDevice == SteppingDevice.ElectroMagnet 
                            && settings.IVSteppingMethodSettings.IsEMSkipFirstCycleEnable)
                {
                    m_stepperMotor.Shutdown();
                    continue;
                }

                //
                // Change the gain power to 5 before reaching contact
                // to ensure full contact current
                //
                m_amplifier.ChangeGain(5);

                //
                // Reach to contact before we start openning the junction
                // If we use EM and we're after the first cycle, use the EM.
                // If user asked to stop than exit
                //
                isCancelled = (settings.IVSteppingMethodSettings.SteppingDevice == SteppingDevice.ElectroMagnet && i > 0) ?
                               EMTryObtainShortCircuit(settings.IVSteppingMethodSettings.EMShortCircuitDelayTime, settings.IVGeneralSettings.ShortCircuitVoltage, worker, e) :
                               TryObtainShortCircuit(settings.IVGeneralSettings.ShortCircuitVoltage,settings.IVGeneralSettings.UseShortCircuitDelayTime,settings.IVGeneralSettings.ShortCircuitDelayTime,worker, e);
                if (isCancelled)
                {
                    break;
                }

                //
                // Configure the gain to the desired one before strating the measurement.
                // And also this is the time to switch the laser on.
                //
                int gainPower;
                Int32.TryParse(settings.IVGeneralSettings.Gain, out gainPower);
                m_amplifier.ChangeGain(gainPower);

                //
                // Start openning the junction.
                // If EM is enabled and we're after the first cycle, use the EM.
                //
                if (settings.IVSteppingMethodSettings.SteppingDevice == SteppingDevice.ElectroMagnet)
                {
                    if (i == 0)
                    {
                        //
                        // we are on the first cycle and wish to open the junction by the stepper motor.
                        //
                        ObtainOpenJunctionByStepperMotor(settings.IVGeneralSettings.TriggerVoltage, worker, e);

                        //
                        // from now on we will be using the electroMagnet, so lets turn the stepper motor off and move to the next cycle
                        //
                        m_stepperMotor.Shutdown();
                        continue;
                    }
                    else
                    {
                        //
                        // we set the votlage to triangle wave and then open the junction by the EM
                        //
                        writer.BeginWriteMultiSample(false, m_functionGenerator.TriangleWave, null, null);
                        IV_EMBeginOpenJunction(settings);
                    }
                }
                else
                {
                    //
                    // we set the voltage to triangle wave and then open the junction by stepper motor
                    //
                    writer.BeginWriteMultiSample(false, m_functionGenerator.TriangleWave, null, null);
                    IV_StepperMotorBeginOpenJunction(settings);
                }

                //
                // Start the input task.
                //
                try
                {
                    m_ivInputTask.Start();
                }
                catch (DaqException ex)
                {
                    throw new SBJException("Error occured when tryin to start DAQ input task", ex);
                }

                //
                // start reading continuously. 
                // when the junction is opened, the opening thread will change m_quitJuncctionOpeningOperation to true.
                // set dataAquired to null otherwise it saves last cycle's data. 
                //
                reader = new AnalogMultiChannelReader(m_ivInputTask.Stream);
                dataAcquired = null;
                try
                {
                    while (!m_quitJunctionOpenningOperation)
                    {
                        dataAcquired = reader.ReadMultiSample(-1);
                    }

                    if (dataAcquired != null)
                    {
                        if (settings.ChannelsSettings.ActiveChannels.Count != dataAcquired.GetLength(0))
                        {
                            throw new SBJException("Number of data channels doesn't fit the recieved data.");
                        }
                    }
                }
                catch (DaqException)
                {
                    //
                    // Probably timeout.
                    // Ignore this cycle and rerun.
                    //
                    m_ivInputTask.Stop();
                    continue;
                }

                //
                // At this point the reader has returned with all the data and we can stop the input task.
                //
                m_ivInputTask.Stop();

                //
                // if we didn't acquire any data, there's no need to save anything.
                //
                if (dataAcquired == null)
                {
                    continue;
                }

                //
                // Assign the aquired data for each channel.
                // First clear all data from previous interation.
                //                
                ClearRawData(settings.ChannelsSettings.ActiveChannels);
                AssignRawDataToChannels(settings.ChannelsSettings.ActiveChannels, dataAcquired);

                //
                // physical channel will include both simple and complex channels. 
                // 
                physicalChannels = GetChannelsForDisplay(settings.ChannelsSettings.ActiveChannels);

                //
                // calculate the physical data for each channel
                //
                GetPhysicalData(physicalChannels);

                //
                // the IV acquisition is done, we need to return the output to constant voltage for the next cycle
                //
                writer.BeginWriteMultiSample(false, m_functionGenerator.ConstWave, null, null);

                // 
                // Increase file number by one
                // Save data if needed
                //
                finalFileNumber++;
                if (settings.IVGeneralSettings.IsFileSavingRequired)
                {
                    finalFileNumber = SaveData(settings.IVGeneralSettings.Path, settings.ChannelsSettings.ActiveChannels, physicalChannels, finalFileNumber);
                }

                //
                // Signal UI we have the data
                //
                if (DataAquired != null)
                {
                    DataAquired(this, new DataAquiredEventArgs(physicalChannels, finalFileNumber));
                }     
            }

            //
            // Finish the measurement properly
            //
            if (settings.IVSteppingMethodSettings.SteppingDevice == SteppingDevice.ElectroMagnet)
            {
                m_electroMagnet.Shutdown();
            }
            m_ivInputTask.Dispose();
            m_ivInputTask = null;
            m_outputTask.Dispose();
            m_outputTask = null;
            m_stepperMotor.Shutdown();
        }
        /// <summary>
        /// Start internally clocked software triggered tasks, software timed tasks (like gpib tasks), and tasks which act as clocks for other tasks.
        /// </summary>
        /// <returns></returns>
        public override bool generateTrigger()
        {
            lock (remoteLockObj)
            {
                try
                {

                    messageLog(this, new MessageEvent("Generating triggers."));

                    Dictionary<string, DeviceSettings> devicesSettings = myServerSettings.myDevicesSettings;
                    List<string> devicesToSoftTrigger = new List<string>();
                    List<Task> tasksToSoftTrigger = new List<Task>();
                    List<Task> tasksToSoftTriggerLast = new List<Task>();
                    List<GpibTask> gpibTasksToTrigger = new List<GpibTask>();
                    List<RS232Task> rs232TasksToTrigger = new List<RS232Task>();
                    List<RfsgTask> rfsgTasksToTrigger = new List<RfsgTask>();

                    // This loop adds the NIDAQ analog and digital tasks that require soft trigger to the appropriate list.
                    // These are software triggered tasks which do NOT use an external sample clock (those that do are started in armTasks)
                    foreach (string dev in devicesSettings.Keys)
                    {
                        if ((devicesSettings[dev].StartTriggerType == DeviceSettings.TriggerType.SoftwareTrigger)
                            && (devicesSettings[dev].MySampleClockSource != DeviceSettings.SampleClockSource.External))
                        {
                            devicesToSoftTrigger.Add(dev);

                            if (daqMxTasks.ContainsKey(dev))
                            {

                                if (daqMxTasks[dev] != null)
                                {
                                    if (devicesSettings[dev].SoftTriggerLast)
                                    {
                                        tasksToSoftTriggerLast.Add(daqMxTasks[dev]);
                                    }
                                    else
                                    {
                                        tasksToSoftTrigger.Add(daqMxTasks[dev]);
                                    }
                                }
                            }
                        }

                    }

                    // add all the gpib tasks to the soft trigger list
                    foreach (GpibTask gpTask in gpibTasks.Values)
                    {
                        gpibTasksToTrigger.Add(gpTask);
                    }

                    foreach (RS232Task task in rs232Tasks.Values)
                    {
                        rs232TasksToTrigger.Add(task);
                    }
                    foreach (RfsgTask task in rfsgTasks.Values)
                    {
                        rfsgTasksToTrigger.Add(task);
                    }

                    // If there is an additional "wait for ready" input, then wait for it.
                    if (serverSettings.ReadyInput != null)
                    {
                        if (serverSettings.ReadyInput != "")
                        {
                            if (sequence.WaitForReady)
                            {
                                messageLog(this, new MessageEvent("Waiting for ready input."));
                                Task readyReaderTask = new Task("ReadyInput");
                                readyReaderTask.DIChannels.CreateChannel(serverSettings.ReadyInput, "", ChannelLineGrouping.OneChannelForEachLine);
                                DigitalSingleChannelReader reader = new DigitalSingleChannelReader(readyReaderTask.Stream);

                                readyReaderLoopAbort = false;
                                readyReaderLoopRunning = true;
                                long startTicks = DateTime.Now.Ticks;
                                while (!reader.ReadSingleSampleSingleLine() && !readyReaderLoopAbort)
                                {
                                    if (serverSettings.ReadyTimeout > 0)
                                    {
                                        long durationTicks = DateTime.Now.Ticks - startTicks;
                                        if (durationTicks / 10000 > serverSettings.ReadyTimeout)
                                        {
                                            messageLog(this, new MessageEvent("Timeout waiting for ready input, more than " + serverSettings.ReadyTimeout + "ms elapsed."));
                                            if (serverSettings.ReadyTimeoutRunAnyway)
                                            {
                                                messageLog(this, new MessageEvent("Running sequence anyway..."));
                                                break;
                                            }
                                            else
                                            {
                                                readyReaderTask.Dispose();
                                                messageLog(this, new MessageEvent("Aborting run."));
                                                readyReaderLoopRunning = false;
                                                return false;
                                            }
                                        }
                                    }
                                }
                                readyReaderLoopRunning = false;

                                if (readyReaderLoopAbort)
                                {
                                    messageLog(this, new MessageEvent("Received an abort request while running the ready input polling loop. Aborting."));
                                    readyReaderTask.Dispose();
                                    return false;
                                }

                                messageLog(this, new MessageEvent("Done waiting for ready input. Running sequence."));
                                readyReaderTask.Dispose();

                            }
                        }
                    }
                    // ok, done waiting for the ready input (or never stopped to wait)

                    // Hardware trigger outputs. This is not a recommended way to synchronize things.
                    if (serverSettings.TriggerOutputChannel != "" && serverSettings.TriggerOutputChannel != null)
                    {
                        messageLog(this, new MessageEvent("******* This server is configured to use a trigger output channel. This is not recommended. Instead, either use a variable timebase sample clock, or derive your start trigger from the StartTrigger channel of a software triggered task. *********"));
                        displayError();

                        string triggerChannel = serverSettings.TriggerOutputChannel;
                        // Create trigger tasks
                        /*List<Task> triggerTasks = new List<Task>();
                        List<DigitalSingleChannelWriter> triggerWriters = new List<DigitalSingleChannelWriter>();
                        foreach (string triggerChannel in serverSettings.TriggerOutputChannels)
                        {*/
                        Task triggerTask = new Task();
                        triggerTask.DOChannels.CreateChannel(triggerChannel, "", ChannelLineGrouping.OneChannelForEachLine);
                        DigitalSingleChannelWriter writer = new DigitalSingleChannelWriter(triggerTask.Stream);
                        writer.WriteSingleSampleSingleLine(true, false);
                        // }

                        // wait for the trigger lines to go low.
                        Thread.Sleep(1);

                        // now pounce!

                        //foreach (DigitalSingleChannelWriter writer in triggerWriters)
                        writer.WriteSingleSampleSingleLine(true, true);
                    }

                    // Software triggering for daqMx tasks.
                    foreach (Task task in tasksToSoftTrigger)
                    {
                        task.Start();
                    }

                    if (!myServerSettings.TriggerSoftwareTasksAfterTimebaseTask)
                    {
                        // Trigger the software timed operations, but only if these operations are not going to be
                        // triggered through a triggering task. (see the armTasks function for more info).
                        if (softwareTriggeringTask == null)
                        {
                            if (computerClockProvider != null)
                            {
                                computerClockProvider.ArmClockProvider();
                                computerClockProvider.StartClockProvider();
                                messageLog(this, new MessageEvent("Triggered computer-software-clock (without sync to a hardware timed task)."));
                            }

                        }
                    }

                    foreach (Task task in tasksToSoftTriggerLast)
                    {
                        task.Start();
                    }

                    // finally, if there is a variable timebase output task, we start it.

                    if (variableTimebaseClockTask != null)
                    {
                        long before = DateTime.Now.Ticks;
                        variableTimebaseClockTask.Start();
                        long after = DateTime.Now.Ticks;
                        long elapsed = after - before;

                        int ms = (int)(elapsed / 10000);
                        messageLog(this, new MessageEvent("Triggered variable timebase clock task. Time elapsed waiting for task to start: " + ms + " ms."));

                        if (!myServerSettings.SilenceSoftwareTimebaseDelayError)
                        {
                            // Detect possible long delay between timebase and software task trigger.
                            if (ms > 50)
                            {
                                if (gpibTasks.Count + rs232Tasks.Count + rfsgTasks.Count > 0)
                                {
                                    if (softwareTriggeringTask == null)
                                    {
                                        if (!myServerSettings.TriggerSoftwareTasksAfterTimebaseTask)
                                        {
                                            messageLog(this, new MessageEvent("**** NOTE: There is a delay of ~" + ms + " ms between the start of your software-timed tasks and the start of your variable timebase. To reduce this, either use the DeviceToSyncSoftwareTasksTo sync method, or set TriggerSoftwareTasksAfterTimebaseTask to true. To silence this error, set SilenceSoftwareTimebaseDelayError to true.***"));
                                            displayError();
                                        }
                                    }
                                }
                            }
                        }
                    }

                    if (myServerSettings.TriggerSoftwareTasksAfterTimebaseTask)
                    {
                        // Trigger the software timed operations, but only if these operations are not going to be
                        // triggered through a triggering task. (see the armTasks function for more info).
                        if (softwareTriggeringTask == null)
                        {
                            if (computerClockProvider != null)
                            {
                                computerClockProvider.ArmClockProvider();
                                computerClockProvider.StartClockProvider();
                                messageLog(this, new MessageEvent("Triggered software-timed task(s) (without sync to a hardware timed task)."));
                            }

                        }

                    }

                    // TO DO. Insert code that waits for external triggers to occur, before returning. This
                    // Will allow client UI to stay synced with external triggers, if such things are being provided.

                    if (fpgaTasks != null)
                    {
                        foreach (FpgaTimebaseTask ft in fpgaTasks.Values)
                        {
                            ft.ArmClockProvider();
                            ft.StartClockProvider();
                            ft.Start();
                        }
                    }

                    messageLog(this, new MessageEvent("Triggers generated. Sequence running."));

                    return true;
                }
                catch (Exception e)
                {
                    messageLog(this, new MessageEvent("Unable to generate triggers due to exception. " + e.Message + e.StackTrace));
                    displayError();
                    return false;
                }
            }
        }
Example #17
0
        // Called when stimulation is stopped
        private void resetStim()
        {
            //Zero out IvsV and dispose
            stimIvsVTask = new Task("stimIvsV");
            stimIvsVTask.DOChannels.CreateChannel(Properties.Settings.Default.StimIvsVDevice + "/Port1/line0", "",
                ChannelLineGrouping.OneChannelForAllLines);
            stimIvsVWriter = new DigitalSingleChannelWriter(stimIvsVTask.Stream);
            stimIvsVTask.Control(TaskAction.Verify);
            stimIvsVWriter.WriteSingleSampleSingleLine(true, false);
            stimIvsVTask.WaitUntilDone();
            stimIvsVTask.Stop();
            stimIvsVTask.Dispose();

            // Sero out stim digital output and dispose
            if (stimDigitalTask != null)
                stimDigitalTask.Dispose();
            stimDigitalTask = new Task("stimDigitalTask_formClosing");
            if (Properties.Settings.Default.StimPortBandwidth == 32)
                stimDigitalTask.DOChannels.CreateChannel(Properties.Settings.Default.StimulatorDevice + "/Port0/line0:31", "",
                    ChannelLineGrouping.OneChannelForAllLines); //To control MUXes
            else if (Properties.Settings.Default.StimPortBandwidth == 8)
                stimDigitalTask.DOChannels.CreateChannel(Properties.Settings.Default.StimulatorDevice + "/Port0/line0:7", "",
                    ChannelLineGrouping.OneChannelForAllLines); //To control MUXes
            stimDigitalWriter = new DigitalSingleChannelWriter(stimDigitalTask.Stream);
            bool[] fData = new bool[Properties.Settings.Default.StimPortBandwidth];
            stimDigitalWriter.WriteSingleSampleMultiLine(true, fData);
            stimDigitalTask.WaitUntilDone();
            stimDigitalTask.Stop();
            Console.WriteLine("resetStim completed");
        }