Example #1
0
        public void Read()
        {
            try {
                string[] channelNameList = DaqSystem.Local.GetPhysicalChannels(PhysicalChannelTypes.AI, PhysicalChannelAccess.External);
                if (channelNameList.Length > 0) {
                    Task task = new Task();
                    task.AIChannels.CreateVoltageChannel(channelNameList[0], "Voltage", AITerminalConfiguration.Differential, 0.0, 10.0, AIVoltageUnits.Volts);
                    task.Timing.ConfigureSampleClock("", 100000, SampleClockActiveEdge.Rising, SampleQuantityMode.FiniteSamples);
                    task.Control(TaskAction.Verify);

                    AnalogSingleChannelReader airead = new AnalogSingleChannelReader(task.Stream);
                    AnalogWaveform<double> waveform;
                    for(int i=0;i<repeat;i++){
                        waveform = airead.ReadWaveform(sampleRate);
                        datalist.AddRange(waveform.GetRawData());
                        Console.Out.WriteLine("Acquire " + i + "th try");
                    }
                    StreamWriter writer = new StreamWriter(File.Open("ai.txt", FileMode.Create));
                    int c = 0;
                    foreach (double d in datalist) {
                        writer.WriteLine(String.Format("{0} {1}",c,d));
                        c++;
                    }
                    writer.Close();
                }
            } catch (DaqException e) {
                Console.Out.WriteLine(e.Message);
            }
        }
        //AND CAVITY VOLTAGE!!!
        //The photodiode inputs have been bundled into one task. We never read one photodiode without reading
        //the other.
        public void ConfigureReadAI(int numberOfMeasurements, bool autostart)
        {
            readAIsTask = new Task("readAI");

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

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

            if (autostart == false)
            {
                 readAIsTask.Timing.ConfigureSampleClock(
                    "",
                    40000,
                    SampleClockActiveEdge.Rising,
                    SampleQuantityMode.FiniteSamples, numberOfMeasurements);
                readAIsTask.Triggers.StartTrigger.ConfigureDigitalEdgeTrigger(
                    (string)Environs.Hardware.GetInfo(trigger),
                    DigitalEdgeStartTriggerEdge.Rising);
            }
            readAIsTask.Control(TaskAction.Verify);
            analogReader = new AnalogMultiChannelReader(readAIsTask.Stream);
        }
 public void ConfigureCavityScan(int numberOfSteps, bool autostart)
 {
     outputCavityTask = new Task("CavityPiezoVoltage");
     cavityChannel =
                 (AnalogOutputChannel)Environs.Hardware.AnalogOutputChannels[cavityChannelName];
     cavityChannel.AddToTask(outputCavityTask, 0, 10);
     outputCavityTask.Control(TaskAction.Verify);
     cavityWriter = new AnalogSingleChannelWriter(outputCavityTask.Stream);
 }
 //This takes in a voltage. A bit cheezy, but I needed the laser
 // voltage to be set as soon value as soon as it gets configured.
 public void ConfigureSetLaserVoltage(double voltage)
 {
     outputLaserTask = new Task("FeedbackToLaser" + laserChannelName);
     laserChannel =
             (AnalogOutputChannel)Environs.Hardware.AnalogOutputChannels[laserChannelName];
     laserChannel.AddToTask(outputLaserTask, laserChannel.RangeLow, laserChannel.RangeHigh);
     outputLaserTask.Control(TaskAction.Verify);
     laserWriter = new AnalogSingleChannelWriter(outputLaserTask.Stream);
     laserWriter.WriteSingleSample(true, voltage);
     //outputLaserTask.Start();
 }
        public void ConfigureCavityScan(int numberOfSteps, bool autostart)
        {
            outputCavityTask = new Task("CavityPiezoVoltage");
            cavityChannel =
                        (AnalogOutputChannel)Environs.Hardware.AnalogOutputChannels[cavityChannelName];
            cavityChannel.AddToTask(outputCavityTask, 0, 10);
            outputCavityTask.AOChannels[0].DataTransferMechanism = AODataTransferMechanism.Dma;

            if (!autostart)
            {
                outputCavityTask.Timing.ConfigureSampleClock("", 500,
                SampleClockActiveEdge.Rising, SampleQuantityMode.FiniteSamples, 2 * numberOfSteps);
                outputCavityTask.Triggers.StartTrigger.ConfigureDigitalEdgeTrigger(
                        (string)Environs.Hardware.GetInfo(cavityTriggerInputName), DigitalEdgeStartTriggerEdge.Rising);
            }

            outputCavityTask.Control(TaskAction.Verify);
            cavityWriter = new AnalogSingleChannelWriter(outputCavityTask.Stream);
        }
Example #6
0
        public void Read2()
        {
            try {
                string[] channelNameList = DaqSystem.Local.GetPhysicalChannels(PhysicalChannelTypes.DILine, PhysicalChannelAccess.External);
                if (channelNameList.Length > 0) {
                    Task task = new Task("Digital Input Test");
                    task.DIChannels.CreateChannel(channelNameList[0]+":7", "",ChannelLineGrouping.OneChannelForAllLines);
                    task.Timing.ConfigureSampleClock("", 10000, SampleClockActiveEdge.Rising, SampleQuantityMode.FiniteSamples);
                    task.Control(TaskAction.Verify);

                    DigitalSingleChannelReader diread = new DigitalSingleChannelReader(task.Stream);
                    DigitalWaveform waveform;
                    for (int i = 0; i < repeat; i++) {
                        waveform = diread.ReadWaveform(sampleRate);
                        foreach(DigitalWaveformSignal signal in waveform.Signals){
                            foreach (DigitalState state in signal.States) {
                                if (state == DigitalState.ForceDown) {
                                    Console.Write(0);
                                } else if (state == DigitalState.ForceUp) {
                                    Console.Write(1);
                                } else {
                                    Console.Write("?");
                                }
                            }
                            Console.WriteLine();
                        }
                        Console.Out.WriteLine("Acquire " + i + "th try");
                    }
                    StreamWriter writer = new StreamWriter(File.Open("di.txt", FileMode.Create));
                    int c = 0;
                    foreach (double d in datalist) {
                        writer.WriteLine(String.Format("{0} {1}", c, d));
                        c++;
                    }
                    writer.Close();
                }
            } catch (DaqException e) {
                Console.Out.WriteLine(e.Message);
            }
        }
        internal ChannelOutput(double samplingRate, double outputRefreshTime, double inputRefreshTime, Task spikeTask, String NIDevice, int NIChannel)
        {
            //Compute buffer length, instantiate buffer
            int multiple = (int)(Math.Round(outputRefreshTime / inputRefreshTime)); //Get number of input buffer reads that approximate the desired output rate
            if (multiple < 1) multiple = 1; //Ensure the multiple is at least 1
            int bufferLength = (int)((double)multiple * inputRefreshTime * samplingRate); //Calculate length
            buffer = new double[bufferLength];

            //Create new task
            analogOutputTask = new Task("Playback Analog Output Task");
            analogOutputTask.AOChannels.CreateVoltageChannel(NIDevice + "/ao" + NIChannel, "",
                            -10.0, 10.0, AOVoltageUnits.Volts);
            analogOutputTask.Timing.ReferenceClockSource = spikeTask.Timing.ReferenceClockSource;
            analogOutputTask.Timing.ReferenceClockRate = spikeTask.Timing.ReferenceClockRate;
            analogOutputTask.Timing.ConfigureSampleClock("", samplingRate,
                            SampleClockActiveEdge.Rising, SampleQuantityMode.ContinuousSamples, bufferLength);
            analogOutputTask.Control(TaskAction.Verify);

            //Create writer
            analogOutputWriter = new AnalogSingleChannelWriter(analogOutputTask.Stream);
            analogOutputWriter.SynchronizeCallbacks = false;
        }
 //AND CAVITY VOLTAGE!!!
 //The photodiode inputs have been bundled into one task. We never read one photodiode without reading
 //the other.
 public void ConfigureReadAI(int numberOfMeasurements, bool autostart)
 {
     readAIsTask = new Task("readAI");
     referenceLaserChannel = (AnalogInputChannel)Environs.Hardware.AnalogInputChannels[masterPDChannelName];
     lockingLaserChannel = (AnalogInputChannel)Environs.Hardware.AnalogInputChannels[slavePDChannelName];
     cavityVoltageChannel = (AnalogInputChannel)Environs.Hardware.AnalogInputChannels[cavityReadChannelName];
     referenceLaserChannel.AddToTask(readAIsTask, 0, 10);
     lockingLaserChannel.AddToTask(readAIsTask, 0, 10);
     cavityVoltageChannel.AddToTask(readAIsTask, 0, 10);
     if (autostart == false)
     {
          readAIsTask.Timing.ConfigureSampleClock(
             "",
             66000,
             SampleClockActiveEdge.Rising,
             SampleQuantityMode.FiniteSamples, numberOfMeasurements);
         readAIsTask.Triggers.StartTrigger.ConfigureDigitalEdgeTrigger(
             (string)Environs.Hardware.GetInfo(AITriggerInputName),
             DigitalEdgeStartTriggerEdge.Rising);
     }
     readAIsTask.Control(TaskAction.Verify);
     analogReader = new AnalogMultiChannelReader(readAIsTask.Stream);
 }
Example #9
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 #10
0
        public void Initialize()
        {
            //    counterTask = new Task("");
            //    this.counterTask.CIChannels.CreateFrequencyChannel(
            //        currentLeakageCounterChannel.PhysicalChannel,
            //        "",
            //        0,
            //        150000,
            //        CIFrequencyStartingEdge.Rising,
            //      CIFrequencyMeasurementMethod.HighFrequencyTwoCounter,
            //       // the units of measurement time are not specified anywhere in the docs :-(
            //       measurementTime,
            //        // this has to be more than four to stop NIDAQ crashing, even though it is not used in this mode!
            //        100,
            //        CIFrequencyUnits.Hertz
            //        );
            //    counterTask.Stream.Timeout = (int)(10.1 * 1000 * measurementTime);
            //    leakageReader = new CounterReader(counterTask.Stream);

            monitorTask = new Task("EDMHCIn" + leakageChannel);
            ((AnalogInputChannel)Environs.Hardware.AnalogInputChannels[leakageChannel]).AddToTask(
                monitorTask,
                0,
                10
            );
            monitorTask.Control(TaskAction.Verify);
            leakageReader = new AnalogSingleChannelReader(monitorTask.Stream);
        }
        //The photodiode inputs have been bundled into one task. We never read one photodiode without reading
        //the other.
        public void ConfigureReadPhotodiodes(int numberOfMeasurements, bool autostart)
        {
            readPhotodiodesTask = new Task("ReadPhotodiodes");
            referenceLaserChannel = (AnalogInputChannel)Environs.Hardware.AnalogInputChannels[masterPDChannelName];
            lockingLaserChannel = (AnalogInputChannel)Environs.Hardware.AnalogInputChannels[slavePDChannelName];
            referenceLaserChannel.AddToTask(readPhotodiodesTask, 0, 10);
            lockingLaserChannel.AddToTask(readPhotodiodesTask, 0, 10);

            if (!autostart)
            {
                readPhotodiodesTask.Timing.ConfigureSampleClock(
                   "",
                   500,
                   SampleClockActiveEdge.Rising,
                   SampleQuantityMode.FiniteSamples, 2 * numberOfMeasurements);
                readPhotodiodesTask.Triggers.StartTrigger.ConfigureDigitalEdgeTrigger(
                    (string)Environs.Hardware.GetInfo(photodiodeTriggerInputName),
                    DigitalEdgeStartTriggerEdge.Rising);
            }
            readPhotodiodesTask.AIChannels[0].DataTransferMechanism = AIDataTransferMechanism.UsbBulk;
            readPhotodiodesTask.AIChannels[1].DataTransferMechanism = AIDataTransferMechanism.UsbBulk;
            readPhotodiodesTask.Control(TaskAction.Verify);
            photodiodesReader = new AnalogMultiChannelReader(readPhotodiodesTask.Stream);
        }
Example #12
0
        private double ReadAnalogInput(Task task, double sampleRate, int numOfSamples)
        {
            //Configure the timing parameters of the task
            task.Timing.ConfigureSampleClock("", sampleRate,
                SampleClockActiveEdge.Rising, SampleQuantityMode.FiniteSamples, numOfSamples);

            //Read in multiple samples
            AnalogSingleChannelReader reader = new AnalogSingleChannelReader(task.Stream);
            double[] valArray = reader.ReadMultiSample(numOfSamples);
            task.Control(TaskAction.Unreserve);

            //Calculate the average of the samples
            double sum = 0;
            for (int j = 0; j < numOfSamples; j++)
            {
                sum = sum + valArray[j];
            }
            double val = sum / numOfSamples;
            return val;
        }
Example #13
0
        private void button_electrolesioningStart_Click(object sender, EventArgs e)
        {
            //Change mouse cursor to waiting cursor
            this.Cursor = Cursors.WaitCursor;

            //Grab values from UI
            double voltage = Convert.ToDouble(numericUpDown_electrolesioningVoltage.Value);
            double duration = Convert.ToDouble(numericUpDown_electrolesioningDuration.Value);
            List<Int32> chList = new List<int>(listBox_electrolesioningChannels.SelectedIndices.Count);
            for (int i = 0; i < listBox_electrolesioningChannels.SelectedIndices.Count; ++i)
                chList.Add(listBox_electrolesioningChannels.SelectedIndices[i] + 1); //+1 since indices are 0-based but channels are 1-base

            //Disable buttons, so users don't try running two experiments at once
            button_electrolesioningStart.Enabled = false;
            button_electrolesioningSelectAll.Enabled = false;
            button_electrolesioningSelectNone.Enabled = false;
            button_electrolesioningStart.Refresh();

            //Refresh stim task
            stimDigitalTask.Dispose();
            stimDigitalTask = new Task("stimDigitalTask_Electrolesioning");
            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);

            //Refresh pulse task
            stimPulseTask.Dispose();
            stimPulseTask = new Task("stimPulseTask");
            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);
            }

            stimPulseWriter = new AnalogMultiChannelWriter(stimPulseTask.Stream);

            stimPulseTask.Timing.ConfigureSampleClock("",
                StimPulse.STIM_SAMPLING_FREQ, SampleClockActiveEdge.Rising, SampleQuantityMode.FiniteSamples);
            stimPulseTask.Timing.SamplesPerChannel = 2;

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

            //For each channel, deliver lesioning pulse
            for (int i = 0; i < chList.Count; ++i)
            {
                int channel = chList[i];
                UInt32 data = StimPulse.channel2MUX((double)channel);

                //Setup digital waveform, open MUX channel
                stimDigitalWriter.WriteSingleSamplePort(true, data);
                stimDigitalTask.WaitUntilDone();
                stimDigitalTask.Stop();

                //Write voltage to channel, wait duration, stop
                stimPulseWriter.WriteMultiSample(true, new double[,] { { 0, 0 }, { 0, 0 }, { voltage, voltage }, { 0, 0 } });
                stimPulseTask.WaitUntilDone();
                stimPulseTask.Stop();
                Thread.Sleep((int)(Math.Round(duration * 1000))); //Convert to ms
                stimPulseWriter.WriteMultiSample(true, new double[,] { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 } });
                stimPulseTask.WaitUntilDone();
                stimPulseTask.Stop();

                //Close MUX
                stimDigitalWriter.WriteSingleSamplePort(true, 0);
                stimDigitalTask.WaitUntilDone();
                stimDigitalTask.Stop();
            }

            bool[] fData = new bool[Properties.Settings.Default.StimPortBandwidth];
            stimDigitalWriter.WriteSingleSampleMultiLine(true, fData);
            stimDigitalTask.WaitUntilDone();
            stimDigitalTask.Stop();

            button_electrolesioningSelectAll.Enabled = true;
            button_electrolesioningSelectNone.Enabled = true;
            button_electrolesioningStart.Enabled = true;

            //Now, destroy the objects we made
            updateSettings();
            this.Cursor = Cursors.Default;
        }
Example #14
0
 /// <summary>
 /// Method for outputing a voltage on the DAQ
 /// </summary>
 /// <param name="task">NI-DAQ output task</param>
 /// <param name="voltage">Voltage to output. 
 /// Note must be between the limits outMax and outMin.
 /// The range is limited elsewhere in the code</param>
 private void SetAnalogOutput(Task task, double voltage)
 {
     AnalogSingleChannelWriter writer = new AnalogSingleChannelWriter(task.Stream);
     writer.WriteSingleSample(true, voltage);
     task.Control(TaskAction.Unreserve);
 }
Example #15
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 #16
0
 private void CreateDigitalTask(String name)
 {
     Task digitalTask = new Task(name);
     ((DigitalOutputChannel)Environs.Hardware.DigitalOutputChannels[name]).AddToTask(digitalTask);
     digitalTask.Control(TaskAction.Verify);
     digitalTasks.Add(name, digitalTask);
 }
Example #17
0
 public void Write2()
 {
     try {
         string[] channelNameList = DaqSystem.Local.GetPhysicalChannels(PhysicalChannelTypes.DILine, PhysicalChannelAccess.External);
         string[] channelNameList2 = DaqSystem.Local.GetPhysicalChannels(PhysicalChannelTypes.DIPort, PhysicalChannelAccess.External);
         if (channelNameList.Length > 0) {
             Task task = new Task();
             task.DIChannels.CreateChannel(channelNameList[0], "DigitalOut", ChannelLineGrouping.OneChannelForAllLines);
             task.Timing.ConfigureSampleClock("", 10000, SampleClockActiveEdge.Rising, SampleQuantityMode.ContinuousSamples);
             task.Control(TaskAction.Verify);
         }
     } catch (DaqException e) {
         Console.Out.WriteLine(e.Message);
     }
 }
Example #18
0
        public void WatchTrigger()
        {
            //Create a virtual channel
            using (Task dirTask = new Task())
            {
                dirTask.AIChannels.CreateVoltageChannel("Dev1/ai3", "TriggerRead",
                                AITerminalConfiguration.Rse, Convert.ToDouble(0),
                                    Convert.ToDouble(5), AIVoltageUnits.Volts);
                //initialize the reader
                AnalogMultiChannelReader reader = new AnalogMultiChannelReader(dirTask.Stream);

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

                bool signal = false;

                while (true)
                {
                    signal = (Math.Round(DoRead(reader).First(), 2) > 0);
                    //Console.WriteLine("Shit is:" + DoRead(reader).First());
                    trigger = (signal) ? -1 : 1;
                    Thread.Sleep(50);
                }
            }
        }
Example #19
0
        public override void DoWork(BackgroundWorker worker)
        {
            while (!worker.CancellationPending)
            {
                try
                {
                    //connect to the server first.
                    this.Connect();
                    this.SetupClock();
                    if (FORWARD_ONLY)
                    {
                        this.StartTriggerWatcher();
                    }

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

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

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

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

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

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

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

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

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

                                    lastUpdate = stopwatch.ElapsedMilliseconds;
                                    PreviousState = currentState;

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

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

                                //add to the samplebox
                                samplebox.Add(FORWARD_ONLY ? CurrentSpeed : CurrentSpeed);
                            }
                        }
                    }
                }
                catch (DaqException e){
                    Console.WriteLine(e.Message);
                }
                catch (Exception e) { Console.WriteLine(e.Message); }
            }
        }
Example #20
0
 public void AddAnalogOutput(Task task, AnalogOutputChannel channel, string channelName, double lowLimit, double highLimit)
 {
     channel.AddToTask(task, lowLimit, highLimit);
     task.Control(TaskAction.Verify);
     analogTasks.Add(channelName, task);
 }
Example #21
0
        private void startButton_Click(object sender, EventArgs e)
        {
            try
            {
                //  Update the UI.
                startButton.Enabled = false;
                stopButton.Enabled = true;
                bufNumTextBox.Text = "";
                //pixelValTextBox.Text = "";
                interfaceTextBox.Enabled = false;
                numImages.Enabled = false;
                volumeDepthTextBox.Enabled = false;
                thresholdDeltaVoltageTextBox.Enabled = false;
#if ACQDATA
                // TODO: Params from UI
                // Create a new task
                myTask = new Task();
                physicalChannelText = "Dev1/ai0";
                minimumValue = -10.00;
                maximumValue = 10.00;
                rateValue = 10000.00;
                samplesPerChannelValue = 1000;

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

                analogInReader = new AnalogMultiChannelReader(myTask.Stream);

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

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

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

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

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

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

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

                //  Start the background worker threads
                acquisitionWorker.RunWorkerAsync(subCheckBox);
                renderWorker.RunWorkerAsync(renderUIArgs);
            }
            catch (ImaqException ex)
            {
                MessageBox.Show(ex.Message, "NI-IMAQ Error");
                Cleanup();
            }
            catch (FormatException ex)
            {
                MessageBox.Show(ex.Message, "Format Error");
                Cleanup();
            }
        }
        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 #23
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 #24
0
 private Task CreateAnalogInputTask(string channel, double lowRange, double highRange)
 {
     Task task = new Task("EDMHCIn" + channel);
     ((AnalogInputChannel)Environs.Hardware.AnalogInputChannels[channel]).AddToTask(
         task,
         lowRange,
         highRange
     );
     task.Control(TaskAction.Verify);
     return task;
 }
Example #25
0
 /// <summary>
 /// Method to create a analog output task
 /// </summary>
 /// <param name="channel">Channel name as defined in Hardware class</param>
 /// <returns>The output task</returns>
 private Task CreateAnalogOutputTask(string channel)
 {
     Task task = new Task(channel);
     AnalogOutputChannel c = ((AnalogOutputChannel)Environs.Hardware.AnalogOutputChannels[channel]);
     c.AddToTask(
         task,
         c.RangeLow,
         c.RangeHigh
         );
     task.Control(TaskAction.Verify);
     return task;
 }
Example #26
0
        public void Write()
        {
            try {
                string[] channelNameList = DaqSystem.Local.GetPhysicalChannels(PhysicalChannelTypes.AO, PhysicalChannelAccess.External);
                if (channelNameList.Length > 0) {
                    Task task1 = new Task();
                    task1.AOChannels.CreateVoltageChannel(channelNameList[0], "Voltage1", 0, 10, AOVoltageUnits.Volts);
                    task1.AOChannels.CreateVoltageChannel(channelNameList[1], "Voltage2", 0, 10, AOVoltageUnits.Volts);
                    task1.AOChannels.CreateVoltageChannel(channelNameList[2], "Voltage3", 0, 10, AOVoltageUnits.Volts);
                    task1.Timing.ConfigureSampleClock("", 100, SampleClockActiveEdge.Rising, SampleQuantityMode.FiniteSamples);
                    task1.Control(TaskAction.Verify);
                    Task task2 = new Task();
                    task2.AOChannels.CreateVoltageChannel(channelNameList[0], "Voltage1", 0, 10, AOVoltageUnits.Volts);
                    task2.AOChannels.CreateVoltageChannel(channelNameList[1], "Voltage2", 0, 10, AOVoltageUnits.Volts);
                    task2.AOChannels.CreateVoltageChannel(channelNameList[2], "Voltage3", 0, 10, AOVoltageUnits.Volts);
                    task2.Timing.ConfigureSampleClock("", 100, SampleClockActiveEdge.Rising, SampleQuantityMode.FiniteSamples);
                    task2.Control(TaskAction.Verify);

                    AnalogMultiChannelWriter aowriter1 = new AnalogMultiChannelWriter(task1.Stream);
                    AnalogMultiChannelWriter aowriter2 = new AnalogMultiChannelWriter(task2.Stream);

                    double[,] wave = new double[3, 1000];
                    for (int i = 0; i < 3; i++)
                    {
                        for (int j = 0; j < 1000; j++)
                        {
                            wave[i,j] = 0.001*(1000-j);
                        }
                    }

                    Console.WriteLine("Task is ready");
                    aowriter1.WriteMultiSample(false, wave);
                    task1.Control(TaskAction.Start);
                    Console.ReadKey();
                    task1.Control(TaskAction.Stop);
                    task1.Control(TaskAction.Unreserve);
                    Console.WriteLine("Task1 is released");
                    aowriter2.WriteMultiSample(false, wave);
                    task1.Control(TaskAction.Start);
                    Console.ReadKey();
                    task1.Control(TaskAction.Stop);
                    task1.Control(TaskAction.Unreserve);
                    Console.ReadKey();
                }
            } catch (DaqException e) {
                Console.Out.WriteLine(e.Message);
            }
        }
Example #27
0
 public void setupMasterVoltageOut()
 {
     masterOutputTask = new Task("rampfeedback");
     masterChannel=(AnalogOutputChannel)Environs.Hardware.AnalogOutputChannels["rampfb"];
     masterChannel.AddToTask(masterOutputTask, masterChannel.RangeLow, masterChannel.RangeHigh);
     masterOutputTask.Control(TaskAction.Verify);
     masterWriter = new AnalogSingleChannelWriter(masterOutputTask.Stream);
 }
 public void ConfigureScanTrigger()
 {
     sendScanTriggerTask = new Task("Send Cavity UnlockCavity Trigger");
     sendTriggerChannel = (DigitalOutputChannel)Environs.Hardware.DigitalOutputChannels[triggerOutput];
     sendTriggerChannel.AddToTask(sendScanTriggerTask);
     sendScanTriggerTask.Control(TaskAction.Verify);
     triggerWriter = new DigitalSingleChannelWriter(sendScanTriggerTask.Stream);
     triggerWriter.WriteSingleSampleSingleLine(true, false);
     sendScanTriggerTask.Start();
 }
        // Method to set up the recording side of neurorighter
        private bool NRAcquisitionSetup()
        {
            lock (this)
            {
                if (!taskRunning)
                {
                    try
                    {

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                            }

                        }

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

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

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

                        #region Setup_Plotting

                        numSnipsDisplayed = (int)numericUpDown_NumSnipsDisplayed.Value;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                        }
                        #endregion

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

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

                        #endregion

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

                        numSpikeReads = new int[spikeTask.Count];

                        filtSpikeData = new rawType[numChannels][];

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

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

                        if (Properties.Settings.Default.UseEEG)
                        {

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

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

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

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

                        #endregion

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

                        SetupFileWriting();

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

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

                        spikeCallback = new AsyncCallback(AnalogInCallback_spikes);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            // Disable spike detector saving while running
            spikeDet.DisableFileMenu();
            Console.WriteLine("NRAcquisitionSetup successfully executed");
            this.Cursor = Cursors.Default;
            return false;
        }
Example #30
0
 private double ReadAnalogInput(Task task)
 {
     AnalogSingleChannelReader reader = new AnalogSingleChannelReader(task.Stream);
     double val = reader.ReadSingleSample();
     task.Control(TaskAction.Unreserve);
     return val;
 }