Esempio n. 1
0
        //포트0 연결
        public bool Connect_port0_write()
        {
            bool flag = false;

            try
            {
                flag      = true;
                Writetask = new NationalInstruments.DAQmx.Task();
                Writetask.DOChannels.CreateChannel(ini.GetIniValue("NI", "Name") + "/port0/line0:7", "Digital Output Port0", ChannelLineGrouping.OneChannelForAllLines);
                writer = new DigitalSingleChannelWriter(Writetask.Stream);

                for (int i = 0; i < 8; i++)
                {
                    LED[i] = false;
                }
                if (writer != null)
                {
                    writer.WriteSingleSampleMultiLine(true, LED);
                }
            }
            catch
            {
                flag = false;
            }
            return(flag);
        }
Esempio n. 2
0
 private void button1_Click(object sender, EventArgs e)
 {
     Cursor.Current = Cursors.WaitCursor;
     try
     {
         using (Task digitalWriteTask = new Task())
         {
             digitalWriteTask.DOChannels.CreateChannel(comboBox1.Text, "", ChannelLineGrouping
                                                       .OneChannelForAllLines);
             bool[] dataArray = new bool[8];
             dataArray[0] = bit0CheckBox.Checked;
             dataArray[1] = bit1CheckBox.Checked;
             dataArray[2] = bit2CheckBox.Checked;
             dataArray[3] = bit3CheckBox.Checked;
             dataArray[4] = bit4CheckBox.Checked;
             dataArray[5] = bit5CheckBox.Checked;
             dataArray[6] = bit6CheckBox.Checked;
             dataArray[7] = bit7CheckBox.Checked;
             DigitalSingleChannelWriter writer = new DigitalSingleChannelWriter(digitalWriteTask.Stream);
             writer.WriteSingleSampleMultiLine(true, dataArray);
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
     finally
     {
         Cursor.Current = Cursors.Default;
     }
 }
Esempio n. 3
0
        private const double refractory         = 1; // in seconds

        internal IISZapper(int phaseWidth, double amplitude, int channel, int numPulses, double rate,
                           Task stimDigitalTask, Task stimAnalogTask, DigitalSingleChannelWriter stimDigitalWriter,
                           AnalogMultiChannelWriter stimAnalogWriter, double deviceRefreshRate, NeuroRighter sender)
        {
            const int prePadding  = 100;
            const int postPadding = 100;

            const double offsetVoltage    = 0.0;
            const int    interPhaseLength = 0;

            this.stimDigitalTask   = stimDigitalTask;
            this.stimDigitalWriter = stimDigitalWriter;
            this.stimAnalogTask    = stimAnalogTask;
            this.stimAnalogWriter  = stimAnalogWriter;
            this.channel           = channel - 1;

            sp = new StimPulse(phaseWidth, phaseWidth, amplitude, -amplitude, channel,
                               numPulses, rate, offsetVoltage, interPhaseLength, prePadding, postPadding, true);

            stimAnalogTask.Timing.SamplesPerChannel  = numPulses * sp.analogPulse.GetLength(1);
            stimDigitalTask.Timing.SamplesPerChannel = numPulses * sp.digitalData.GetLength(0);

            totalNumReadsTraining   = (int)(numSecondsTraining / deviceRefreshRate);
            totalNumReadsRefractory = (int)(refractory / deviceRefreshRate);
            numReadsRefractory      = totalNumReadsRefractory;
        }
Esempio n. 4
0
 internal void ZeroPortOnDev(string dev, int port)
 {
     lock (this)
     {
         try
         {
             // Create a digital out task for a given device and port.
             // Write clearingBufferSize zeros to that port. Wait
             // until this is finished and destroy the clearning Task.
             Task digitalClearingTask = new Task("DigiClear");
             digitalClearingTask.DOChannels.CreateChannel("/" + dev + "/Port" + port, "",
                                                          ChannelLineGrouping.OneChannelForAllLines);
             //digitalClearingTask.Timing.ConfigureSampleClock("100KHzTimeBase",
             //    clearingSampleRate,
             //    SampleClockActiveEdge.Rising,
             //    SampleQuantityMode.FiniteSamples,
             //    clearingBufferSize);
             DigitalSingleChannelWriter digitalClearingWriter = new DigitalSingleChannelWriter(digitalClearingTask.Stream);
             digitalClearingWriter.BeginWriteSingleSamplePort(true, 0, null, null);
             digitalClearingTask.WaitUntilDone(30);
             digitalClearingTask.Stop();
             digitalClearingTask.Dispose();
             digitalClearingTask = null;
         }
         catch (Exception e)
         {
             Console.WriteLine(" Could not zero digital output on device: "
                               + dev + "/" + port);
         }
     }
 }
Esempio n. 5
0
        public void SetScopeAddr(int addr)
        {
            byte addrOut = (byte)(~addr & 0xFF);

            //Ignore any invalid addresses and set to 0
            if (addr > MaxAddr)
            {
                addrOut = 0;
            }

            //Set address using a single port write
            try
            {
                using (NationalInstruments.DAQmx.Task digitalWriteTask = new NationalInstruments.DAQmx.Task())
                {
                    string addressCh = outputs[(int)OutputSignals.ScopeAddr0].slot;
                    addressCh += "/port" + outputs[(int)OutputSignals.ScopeAddr0].port.ToString();
                    //addressCh += "/line0:7";
                    digitalWriteTask.DOChannels.CreateChannel(addressCh, "", ChannelLineGrouping.OneChannelForAllLines);
                    DigitalSingleChannelWriter writer = new DigitalSingleChannelWriter(digitalWriteTask.Stream);
                    writer.WriteSingleSamplePort(true, addrOut);
                }
            }
            catch
            {
            }

            //Wait for relays to switch
            Thread.Sleep(RelayWaitMs);
        }
Esempio n. 6
0
        /// <summary>
        /// Instantiate a new camera with the default or the current settings (not sure), avoid using this one
        /// </summary>
        /// <exception cref="NoCameraDetectedException">Thrown when their is no camera detected</exception>
        public NikonCamera()
        {
            triggerControl = new DOTask(System.Configuration.ConfigurationManager.AppSettings["NikonTrigger"], "NikonTrigger");
            writer         = new DigitalSingleChannelWriter(triggerControl.Stream);

            relayControl = new RelayBoxComponent(System.Configuration.ConfigurationManager.AppSettings["NikonRelay"], "Nikon Power");
            PowerOn();


            deviceManager = new CameraDeviceManager();
            deviceManager.PhotoCaptured      += DeviceManager_PhotoCaptured;
            deviceManager.CameraConnected    += DeviceManager_CameraConnected;
            deviceManager.CameraDisconnected += DeviceManager_CameraDisconnected;
            FolderForPhotos = "FlowVisualization";
            bool ok    = deviceManager.ConnectToCamera();
            int  count = 0;

            while (!ok && count < 10)
            {
                count++;
                Thread.Sleep(500);
                ok = deviceManager.ConnectToCamera();
            }
            if (!ok)
            {
                throw new NoCameraDetectedException {
                          Source = "Nikon"
                };
            }

            deviceManager.SelectedCameraDevice.CaptureInSdRam = true;
        }
Esempio n. 7
0
        public bool Digital_Connect(string DAQName)
        {
            bool flag = false;

            try
            {
                flag      = true;
                Writetask = new NationalInstruments.DAQmx.Task();
                Writetask.DOChannels.CreateChannel(DAQName + "/port0/line0:7", "", ChannelLineGrouping.OneChannelForAllLines);
                Writer = new DigitalSingleChannelWriter(Writetask.Stream);

                for (int i = 0; i < 8; i++)
                {
                    LED[i] = false;
                }
                if (Writer != null)
                {
                    Writer.WriteSingleSampleMultiLine(true, LED);
                }
            }
            catch (DaqException Exception)
            {
                flag = false;
                MessageBox.Show(Exception.Message);
            }
            return(flag);
        }
Esempio n. 8
0
 /// <summary>
 /// Constructs a new DAQ object
 /// </summary>
 public DAQ()
 {
     if (ViewModelBase.IsInDesignMode)
     {
         return;
     }
     //Create digital out tasks and writers to control channel mode
     _chModeTasks    = new Task[2];
     _chModeTasks[0] = new Task("Ch1Mode");
     _chModeTasks[0].DOChannels.CreateChannel(HardwareSettings.DAQ.DeviceName + "/" + HardwareSettings.DAQ.Ch1Mode, "", ChannelLineGrouping.OneChannelForAllLines);
     System.Diagnostics.Debug.WriteLine("Created Ch1Mode task");
     _chModeTasks[1] = new Task("Ch2Mode");
     _chModeTasks[1].DOChannels.CreateChannel(HardwareSettings.DAQ.DeviceName + "/" + HardwareSettings.DAQ.Ch2Mode, "", ChannelLineGrouping.OneChannelForAllLines);
     System.Diagnostics.Debug.WriteLine("Created Ch2Mode task");
     _chModeWriters    = new DigitalSingleChannelWriter[2];
     _chModeWriters[0] = new DigitalSingleChannelWriter(_chModeTasks[0].Stream);
     _chModeWriters[1] = new DigitalSingleChannelWriter(_chModeTasks[1].Stream);
     System.Diagnostics.Debug.WriteLine("Created mode writers");
     //At startup, set both main channels to VoltageClamp
     _channelModes = new ClampMode[2];
     Channel1Mode  = ClampMode.CurrentClamp;
     Channel2Mode  = ClampMode.CurrentClamp;
     Channel1Mode  = ClampMode.VoltageClamp;
     Channel2Mode  = ClampMode.VoltageClamp;
     System.Diagnostics.Debug.WriteLine("All modes set to voltage clamp");
 }
Esempio n. 9
0
 public void Dispose()
 {
     if (!IsDisposed)
     {
         //Dispose _doTask and then reset the port
         if (_doTask != null)
         {
             _doTask.Dispose();
             ResetPort();
         }
         //decrement static refcount - if it reaches 0 we want to dispose the static trigger task
         _refcount--;
         if (_refcount < 1)
         {
             lock (_triggerTaskLock)
             {
                 if (_triggerTask != null)
                 {
                     //Make sure we leave trigger in low state
                     if (TriggerInititalized)
                     {
                         ResetTrigger();
                     }
                     _triggerTask.Dispose();
                     _triggerTask        = null;
                     _triggerWriter      = null;
                     TriggerInititalized = false;
                 }
             }
         }
         IsDisposed = true;
     }
 }
Esempio n. 10
0
 public DigitalWaveformGenerator(string line, bool periodic)
 {
     periodicWaveform             = periodic;
     waveform                     = new WaveformState[2];
     waveform[0]                  = new WaveformState();
     waveform[0].state            = true;
     waveform[0].durationMilliSec = onDuration;
     waveform[1]                  = new WaveformState();
     waveform[1].state            = false;
     waveform[1].durationMilliSec = offDuration;
     transitionevent              = new WaveformEventArgs();
     lastStateIdx                 = 0;
     digitalLine                  = line;
     try
     {
         DAQTask = new Task();
         DOChannel outputChannel = DAQTask.DOChannels.CreateChannel(digitalLine, "waveform", ChannelLineGrouping.OneChannelForAllLines);
         outputChannel.OutputDriveType = DOOutputDriveType.ActiveDrive;
         DAQTask.Start();
         writer = new DigitalSingleChannelWriter(DAQTask.Stream);
     }
     catch (DaqException ex)
     {
         MessageBox.Show(ex.Message);
         if (DAQTask != null)
         {
             DAQTask.Dispose();
             DAQTask = null;
         }
     }
 }
 public RelayBoxComponent(string port, string channelName)
 {
     control          = new DOTask(port, channelName);
     writer           = new DigitalSingleChannelWriter(control.Stream);
     this.channelName = channelName;
     writer.WriteSingleSampleSingleLine(true, true);
 }
Esempio n. 12
0
        internal IISZapper(int phaseWidth, double amplitude, int channel, int numPulses, double rate,
            Task stimDigitalTask, Task stimAnalogTask, DigitalSingleChannelWriter stimDigitalWriter,
            AnalogMultiChannelWriter stimAnalogWriter, double deviceRefreshRate, NeuroRighter sender)
        {
            const int prePadding = 100;
            const int postPadding = 100;

            const double offsetVoltage = 0.0;
            const int interPhaseLength = 0;

            this.stimDigitalTask = stimDigitalTask;
            this.stimDigitalWriter = stimDigitalWriter;
            this.stimAnalogTask = stimAnalogTask;
            this.stimAnalogWriter = stimAnalogWriter;
            this.channel = channel - 1;

            sp = new StimPulse(phaseWidth, phaseWidth, amplitude, -amplitude, channel,
                numPulses, rate, offsetVoltage, interPhaseLength, prePadding, postPadding, true);

            stimAnalogTask.Timing.SamplesPerChannel = numPulses * sp.analogPulse.GetLength(1);
            stimDigitalTask.Timing.SamplesPerChannel = numPulses * sp.digitalData.GetLength(0);

            totalNumReadsTraining = (int)(numSecondsTraining / deviceRefreshRate);
            totalNumReadsRefractory = (int)(refractory / deviceRefreshRate);
            numReadsRefractory = totalNumReadsRefractory;
        }
Esempio n. 13
0
        public int WriteDigChannel2(string lines, string name, uint val, uint mask)
        {
            //Create a task such that it will be disposed after
            //we are done using it.
            int  res = 0;
            Task digitalWriteTask = new Task();

            try
            {
                //Create channel
                digitalWriteTask.DOChannels.CreateChannel(lines, "port0", ChannelLineGrouping.OneChannelForEachLine);

                bool[] dataArray = new bool[7];
                CheckLines(ref dataArray);

                DigitalSingleChannelWriter writer = new DigitalSingleChannelWriter(digitalWriteTask.Stream);
                digitalWriteTask.Start();
                writer.WriteSingleSampleMultiLine(false, dataArray);
                digitalWriteTask.Stop();
                //UpdateDigitalShadows(lines, (int)val);
            }
            catch (DaqException ex)
            {
                DaqError(ex.Message);
                res = -1;
            }
            finally {
                //dispose task
                digitalWriteTask.Dispose();
            }
            return(res);
        }
Esempio n. 14
0
        public void OpenChannel()
        {
            // This function opens a new output channel to the NI ELVIS device.
            digitalOut.DOChannels.CreateChannel(Program.device + "/port0", "DigitalChn0",
                                                ChannelLineGrouping.OneChannelForAllLines);

            writer = new DigitalSingleChannelWriter(digitalOut.Stream);
        }
Esempio n. 15
0
 public override void AcquisitionStarting()
 {
     dot   = new Task("ttlSwitchTask");
     raita = new DigitalSingleChannelWriter(dot.Stream);
     ((DigitalOutputChannel)Environs.Hardware.DigitalOutputChannels["digitalSwitchChannel"]).AddToTask(
         dot);
     dot.Control(TaskAction.Verify);
 }
Esempio n. 16
0
 public Port0LineType(string deviceName, int lineIndex)
 {
     this.deviceName = deviceName;
     this.lineIndex  = lineIndex;
     lineTask        = new Task(deviceName + "Port0 line" + lineIndex + " Static Task");
     lineTask.DOChannels.CreateChannel(deviceName + "/port0/line" + lineIndex, "port0line" + lineIndex, ChannelLineGrouping.OneChannelForAllLines);
     lineWriter = new DigitalSingleChannelWriter(lineTask.Stream);
 }
Esempio n. 17
0
        public SourceTabController()
        {
            InitReadTimer();

            sourceTempReader = CreateAnalogInputReader("4Kthermistor");
            cryoWriter       = CreateDigitalOutputWriter("cryoCooler");
            heaterWriter     = CreateDigitalOutputWriter("sourceHeater");
        }
Esempio n. 18
0
 public override void AcquisitionStarting()
 {
     dot = new Task("ttlSwitchTask");
     raita = new DigitalSingleChannelWriter(dot.Stream);
     ((DigitalOutputChannel)Environs.Hardware.DigitalOutputChannels["digitalSwitchChannel"]).AddToTask(
         dot);
     dot.Control(TaskAction.Verify);
 }
Esempio n. 19
0
        public void SetDigitalLine(string name, bool value)
        {
            Task digitalTask = ((Task)digitalTasks[name]);
            DigitalSingleChannelWriter writer = new DigitalSingleChannelWriter(digitalTask.Stream);

            writer.WriteSingleSampleSingleLine(true, value);
            digitalTask.Control(TaskAction.Unreserve);
        }
Esempio n. 20
0
        public void Setup_USB6008()
        {
            //Resets and configures the NI USB6008 Daq boards
            Device dev = DaqSystem.Local.LoadDevice(loc);//added to reset the DAQ boards if they fail to comunicate giving error code 50405

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

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

                StrainChannel = USB6008_AITask.AIChannels.CreateVoltageChannel(
                    loc + "/ai0",                         //Physical name of channel
                    "strainChannel",                      //The name to associate with this channel
                    AITerminalConfiguration.Differential, //Differential Wiring
                    -0.1,                                 //-0.1v minimum
                    NIMaxVolt,                            //1v maximum
                    AIVoltageUnits.Volts                  //Use volts
                    );
                CurrentChannel = USB6008_AITask.AIChannels.CreateVoltageChannel(
                    loc + "/ai1",                         //Physical name of channel
                    "CurrentChannel",                     //The name to associate with this channel
                    AITerminalConfiguration.Differential, //Differential Wiring
                    -0.1,                                 //-0.1v minimum
                    10,                                   //10v maximum
                    AIVoltageUnits.Volts                  //Use volts
                    );
                USB6008_Reader = new AnalogMultiChannelReader(USB6008_AITask.Stream);
                ////////////////////////////////////////////////////////////
                USB6008_AOTask       = new NationalInstruments.DAQmx.Task();
                TraverseMotorChannel = USB6008_AOTask.AOChannels.CreateVoltageChannel(
                    loc + "/ao0",            //Physical name of channel)
                    "TravverseMotorChannel", //The name to associate with this channel
                    0,                       //0v minimum
                    5,                       //5v maximum
                    AOVoltageUnits.Volts
                    );
                LateralMotorChannel = USB6008_AOTask.AOChannels.CreateVoltageChannel(
                    loc + "/ao1",          //Physical name of channel)
                    "LateralMotorChannel", //The name to associate with this channel
                    0,                     //0v minimum
                    5,                     //5v maximum
                    AOVoltageUnits.Volts
                    );
                USB6008_Analog_Writter = new AnalogMultiChannelWriter(USB6008_AOTask.Stream);
                ////////////////////////////////////////////////////////////
                USB6008_DOTask = new NationalInstruments.DAQmx.Task();
                USB6008_DOTask.DOChannels.CreateChannel(loc + "/port0", "port0", ChannelLineGrouping.OneChannelForAllLines);
                USB6008_Digital_Writter = new DigitalSingleChannelWriter(USB6008_DOTask.Stream);
            }
            catch (NationalInstruments.DAQmx.DaqException e)
            {
                Console.WriteLine("Error?\n\n" + e.ToString(), "NI USB 6008 1 Error");
            }
        }
Esempio n. 21
0
        private int Init()
        {
            try
            {
                digitalWriteTaskP00 = new Task();
                digitalWriteTaskP01 = new Task();
                digitalWriteTaskP02 = new Task();
                digitalWriteTaskP03 = new Task();
                digitalWriteTaskP04 = new Task();
                digitalWriteTaskP05 = new Task();

                digitalWriteTaskP09 = new Task();

                digitalWriteTaskP00.DOChannels.CreateChannel("DIO/port0", "port0",
                                                             ChannelLineGrouping.OneChannelForAllLines);
                digitalWriteTaskP01.DOChannels.CreateChannel("DIO/port1", "port1",
                                                             ChannelLineGrouping.OneChannelForAllLines);
                digitalWriteTaskP02.DOChannels.CreateChannel("DIO/port2", "port2",
                                                             ChannelLineGrouping.OneChannelForAllLines);
                digitalWriteTaskP03.DOChannels.CreateChannel("DIO/port3", "port3",
                                                             ChannelLineGrouping.OneChannelForAllLines);
                digitalWriteTaskP04.DOChannels.CreateChannel("DIO/port4", "port4",
                                                             ChannelLineGrouping.OneChannelForAllLines);
                digitalWriteTaskP05.DOChannels.CreateChannel("DIO/port5", "port5",
                                                             ChannelLineGrouping.OneChannelForAllLines);

                digitalWriteTaskP09.DOChannels.CreateChannel("DIO/port9", "port9",
                                                             ChannelLineGrouping.OneChannelForAllLines);

                writerP00 = new DigitalSingleChannelWriter(digitalWriteTaskP00.Stream);
                writerP01 = new DigitalSingleChannelWriter(digitalWriteTaskP01.Stream);
                writerP02 = new DigitalSingleChannelWriter(digitalWriteTaskP02.Stream);
                writerP03 = new DigitalSingleChannelWriter(digitalWriteTaskP03.Stream);
                writerP04 = new DigitalSingleChannelWriter(digitalWriteTaskP04.Stream);
                writerP05 = new DigitalSingleChannelWriter(digitalWriteTaskP05.Stream);

                writerP09 = new DigitalSingleChannelWriter(digitalWriteTaskP09.Stream);


                writerP00.WriteSingleSamplePort(true, 0);
                writerP01.WriteSingleSamplePort(true, 0);
                writerP02.WriteSingleSamplePort(true, 0);
                writerP03.WriteSingleSamplePort(true, 0);
                writerP04.WriteSingleSamplePort(true, 0);
                writerP05.WriteSingleSamplePort(true, 0);
                writerP09.WriteSingleSamplePort(true, 0);


                return(0);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString(), "Initialize");
                return(-1);
            }
        }
Esempio n. 22
0
        /// <summary>
        /// Reset all lines/pins to 0 - called by Dispose method
        /// </summary>
        private void ResetPort()
        {
            Task reset = new Task("Reset");

            reset.DOChannels.CreateChannel(_line, "do0", ChannelLineGrouping.OneChannelForAllLines);
            DigitalSingleChannelWriter resetWriter = new DigitalSingleChannelWriter(reset.Stream);

            resetWriter.WriteSingleSamplePort(true, (uint)0);
            reset.Dispose();
        }
Esempio n. 23
0
        public void DAQDO()
        {
            NationalInstruments.DAQmx.Task digitalWriteTask = DaqSystem.Local.LoadTask("Digital_Write_Single");
            DigitalSingleChannelWriter     DO_Channel       = new DigitalSingleChannelWriter(digitalWriteTask.Stream);

            do
            {
                DO_Channel.WriteSingleSampleSingleLine(true, Global.DO);
            } while (exit == false);
        }
 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();
 }
        public void OpenChannel(string channel)
        {
            //Create a new digital output Channel "called Doutport0"
            digitalOut.DOChannels.CreateChannel(channel,                                    //assigned line for the channel
                                                "DigitalChn0",                              //assigned name for the channel
                                                ChannelLineGrouping.OneChannelForAllLines); //grouping feature of the lines

            //Initialise the single channel writer and assign stream of channel to it
            writer = new DigitalSingleChannelWriter(digitalOut.Stream);
        }
Esempio n. 26
0
 public override void AcquisitionStarting()
 {
     if (!Environs.Debug)
     {
         digitalTask = new Task(Channel);
         ((DigitalOutputChannel)Environs.Hardware.DigitalOutputChannels[Channel]).AddToTask(digitalTask);
         digitalTask.Control(TaskAction.Verify);
         writer = new DigitalSingleChannelWriter(digitalTask.Stream);
     }
 }
Esempio n. 27
0
 public override void AcquisitionStarting()
 {
     if (!Environs.Debug)
     {
         digitalTask = new Task(Channel);
         ((DigitalOutputChannel)Environs.Hardware.DigitalOutputChannels[Channel]).AddToTask(digitalTask);
         digitalTask.Control(TaskAction.Verify);
         writer = new DigitalSingleChannelWriter(digitalTask.Stream);
     }
 }
Esempio n. 28
0
        public void OpenChannel(string portLine, string portName)
        {
            //Create a new digital output channel called "Doutport0"
            digitalOut.DOChannels.CreateChannel(portLine,                                   //Assigned line
                                                portName,                                   // Assigned name for cahnnel
                                                ChannelLineGrouping.OneChannelForAllLines); //grouping feature of the lines

            //Initialise the single channel writer and assigned stream of channel to it
            writer = new DigitalSingleChannelWriter(digitalOut.Stream);
        }
Esempio n. 29
0
 internal void MakeWriters()
 {
     if (analogTask != null)
     {
         analogWriter = new AnalogMultiChannelWriter(analogTask.Stream);
     }
     if (digitalTask != null)
     {
         digitalWriter = new DigitalSingleChannelWriter(digitalTask.Stream);
     }
 }
Esempio n. 30
0
        private static void WriteDigital(Task task, bool[] data)
        {
            if (disposed)
            {
                return;
            }

            DigitalSingleChannelWriter write = new DigitalSingleChannelWriter(task.Stream);

            write.BeginWriteSingleSampleMultiLine(true, data, null, null);
        }
Esempio n. 31
0
        private const double STEP = 250e-4; // in mm
        #endregion

        #region Constructors
        public Traverse()
        {
            dirTask   = new DOTask(ConfigurationManager.AppSettings["TravDir"], "dir");
            dirWriter = new DigitalSingleChannelWriter(dirTask.Stream);

            pulse       = new DOTask(ConfigurationManager.AppSettings["TravPulse"], "pulse");
            pulseWriter = new DigitalSingleChannelWriter(pulse.Stream);
            Direction   = Direction.Down;

            pulseWriter.WriteSingleSampleSingleLine(true, false);
            dirWriter.WriteSingleSampleSingleLine(true, false);
        }
Esempio n. 32
0
    public void setLine(uint line, bool value)
    {
        Task      task        = new Task();
        string    devFullname = string.Format("{0}/port0/line{1}", name, line);
        DOChannel dochannel   = task.DOChannels.CreateChannel(devFullname, "", ChannelLineGrouping.OneChannelForEachLine);

        task.Start();
        DigitalSingleChannelWriter writer = new DigitalSingleChannelWriter(task.Stream);

        writer.BeginWriteSingleSampleSingleLine(true, value, null, null);
        task.Stop();
    }
Esempio n. 33
0
        //parts of setup that are specific to clearing and configuring tasks
        private void SetupTasks()//Task[] analogTasks, AnalogMultiChannelWriter[] analogWriters, Task[] digitalTasks, DigitalSingleChannelWriter[] digitalWriters)
        {
            //do outputbuffer-specific task configuration (which device/channels, ranges)
            SetupTasksSpecific(ref analogTasks, ref digitalTasks);


            //do general configuration stuff (clocks, starts, writemodes, buffer sizes)

            //analog
            analogWriters = new AnalogMultiChannelWriter[analogTasks.Length];
            for (int i = 0; i < analogTasks.Length; i++)
            {
                //set timing off of the master task
                analogTasks[i].Timing.ReferenceClockSource =
                    masterTask.Timing.ReferenceClockSource;
                analogTasks[i].Timing.ReferenceClockRate =
                    masterTask.Timing.ReferenceClockRate;

                //set start triggers off of the buffer loading (counter) task
                analogTasks[i].Triggers.StartTrigger.ConfigureDigitalEdgeTrigger(
                    masterLoad, DigitalEdgeStartTriggerEdge.Rising);

                //configure the on board (hardware) buffer
                analogTasks[i].Stream.Buffer.OutputBufferSize = 2 * BUFFSIZE;
                //#soft!
                //  analogTasks[i].Stream.WriteRegenerationMode = WriteRegenerationMode.DoNotAllowRegeneration;
                analogTasks[i].Stream.WriteRegenerationMode = WriteRegenerationMode.AllowRegeneration;

                //create a writer for this task
                analogWriters[i] = new AnalogMultiChannelWriter(analogTasks[i].Stream);

                //now that we've created a potential task configuration, check to make sure everything is kosher
                //actually set the hardware to these settings
                analogTasks[i].Control(TaskAction.Reserve);
            }

            digitalWriters = new DigitalSingleChannelWriter[digitalTasks.Length];
            for (int i = 0; i < digitalTasks.Length; i++)
            {
                //configure the on board (hardware) buffer
                digitalTasks[i].Stream.Buffer.OutputBufferSize = 2 * BUFFSIZE;
                //digitalTasks[i].Stream.WriteRegenerationMode = WriteRegenerationMode.DoNotAllowRegeneration;
                digitalTasks[i].Stream.WriteRegenerationMode = WriteRegenerationMode.AllowRegeneration;

                //create a writer for this task
                digitalWriters[i] = new DigitalSingleChannelWriter(digitalTasks[i].Stream);

                //now that we've created a potential task configuration, check to make sure everything is kosher
                digitalTasks[i].Control(TaskAction.Verify);
                //actually set the hardware to these settings
                digitalTasks[i].Control(TaskAction.Reserve);
            }
        }
        /// <summary>
        /// Writes the specified byte to the dev/port
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void writeButton_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                using (Task digitalWriteTask = new Task())
                {

                    //  Create an Digital Output channel and name it.
                    digitalWriteTask.DOChannels.CreateChannel(physicalChannelComboBox.Text, "port0", ChannelLineGrouping.OneChannelForAllLines);

                    //  Write digital port data. WriteDigitalSingChanSingSampPort writes a single sample
                    //  of digital data on demand, so no timeout is necessary.
                    DigitalSingleChannelWriter writer = new DigitalSingleChannelWriter(digitalWriteTask.Stream);
                    writer.WriteSingleSamplePort(true, (UInt32)NumericUpDowndataToWrite.Value);
                }

                refreshNumericUpDownValue();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }
Esempio n. 35
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();
            }
        }
Esempio n. 36
0
 private void SetDigitalLine(string name, bool value)
 {
     Task digitalTask = ((Task)digitalTasks[name]);
     DigitalSingleChannelWriter writer = new DigitalSingleChannelWriter(digitalTask.Stream);
     writer.WriteSingleSampleSingleLine(true, value);
     digitalTask.Control(TaskAction.Unreserve);
 }
        /// <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;
                }
            }
        }
 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();
 }
Esempio n. 39
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;
            }
        }
Esempio n. 40
0
        private void TimedMove(double __dCycleTime, double[,] __dCoordinates, int[] __iLevels, bool master, bool continuous)
        {
            Stopwatch watch = new Stopwatch();

            watch.Start();
            _logger.Debug("Start:" + watch.ElapsedMilliseconds.ToString());
            int _iSamplesPerChannel = __dCoordinates.Length / 3;

            // Prepare the stage control task for writing as many samples as necessary to complete Move.
            this.Configure(__dCycleTime, _iSamplesPerChannel, master, continuous);

            AnalogMultiChannelWriter writerA = new AnalogMultiChannelWriter(this.m_daqtskMoveStage.Stream);
            DigitalSingleChannelWriter writerD = new DigitalSingleChannelWriter(this.m_daqtskLineTrigger.Stream);

            try
            {
                // Perform the actual AO write.
                writerA.WriteMultiSample(false, __dCoordinates);
                writerD.WriteMultiSamplePort(false, __iLevels);
                _logger.Debug("End write:" + watch.ElapsedMilliseconds.ToString());

                // Start all four tasks in the correct order. Global sync should be last.
                this.m_daqtskLineTrigger.Start();
                this.m_daqtskMoveStage.Start();
                if (this.m_bMaster && this.m_sampleClock != null)
                {
                    this.m_sampleClock.Start(this.m_samplePeriod);
                }
            }

            catch (Exception ex)
            {
                _logger.Error("Something went wrong! : \r\n", ex);
                m_daqtskMoveStage.Stop();
            }
        }
        /// <summary>
        /// Creates a task for a variable timebase output. Consumes the entire port (8 bits) that the timebase is on. (ie outputs the
        /// signal on all 8 bits
        /// </summary>
        /// <param name="channelName"></param>
        /// <param name="masterFrequency"></param>
        /// <param name="sequenceData"></param>
        /// <param name="timebaseType"></param>
        /// <returns></returns>
        public static Task createDaqMxVariableTimebaseSource(string channelName, int masterFrequency, SequenceData sequenceData, 
            SequenceData.VariableTimebaseTypes timebaseType, ServerSettings serverSettings, DeviceSettings deviceSettings)
        {
            Task task = new Task("Variable timebase output task");

            TimestepTimebaseSegmentCollection timebaseSegments = sequenceData.generateVariableTimebaseSegments(timebaseType,
                1.0 / (double)masterFrequency);

            bool [] buffer = sequenceData.getVariableTimebaseClock(timebaseSegments);

            string timebaseDeviceName = HardwareChannel.parseDeviceNameStringFromPhysicalChannelString(channelName);

            string timebasePort = HardwareChannel.parsePortStringFromChannelString(channelName);

            task.DOChannels.CreateChannel(timebasePort, "", ChannelLineGrouping.OneChannelForAllLines);

            task.Timing.ConfigureSampleClock("", (double)masterFrequency, deviceSettings.ClockEdge, SampleQuantityMode.FiniteSamples, buffer.Length);

            if (serverSettings.VariableTimebaseTriggerInput != "")
            {
                task.Triggers.StartTrigger.ConfigureDigitalEdgeTrigger(serverSettings.VariableTimebaseTriggerInput, DigitalEdgeStartTriggerEdge.Rising);
            }

            DigitalSingleChannelWriter writer = new DigitalSingleChannelWriter(task.Stream);

            byte[] byteBuffer = new byte[buffer.Length];
            for (int j = 0; j < buffer.Length; j++)
            {
                if (buffer[j])
                {
                    byteBuffer[j] = 255;
                }
            }

            writer.WriteMultiSamplePort(false, byteBuffer);

            return task;
        }
 private void WriteSingleDigital(NIDAQOutputStream stream, double value)
 {
     using (var t = new DAQTask())
     {
         t.DOChannels.CreateChannel(stream.PhysicalName, "", ChannelLineGrouping.OneChannelForAllLines);
         var writer = new DigitalSingleChannelWriter(t.Stream);
         writer.WriteSingleSamplePort(true, (UInt32) value);
     }
 }
Esempio n. 43
0
 internal void MakeWriters()
 {
     if (analogTask != null)
     {
         analogWriter = new AnalogMultiChannelWriter(analogTask.Stream);
     }
     if (digitalTask != null)
     {
         digitalWriter = new DigitalSingleChannelWriter(digitalTask.Stream);
     }
 }
Esempio n. 44
0
 /// <summary>
 /// Escribe los valores de unos puertos de salida binarios
 /// </summary>
 /// <param name="nombres">Nombres de puertos de salida</param>
 /// <param name="data">Valor para escribir</param>
 /// <param name="persistente">true - para crear una tarea de escritura permanente</param>
 /// <exception cref="ArgumentNullException">
 /// 1. Nombres es null
 /// 2. Data es null
 /// </exception>
 /// <exception cref="ArgumentException">
 /// 1. El nombre de canal es null
 /// 2. El nombre de canal no es valido
 /// 3. Se presente el puerto y el canal de mismo puerto
 /// 4. Numero de canales en data no corrsponde al numero de canales especificados 
 /// </exception>
 /// <exception cref="DriverException">Error de driver de la tarjeta</exception>
 public void EscribirBinario(string[] nombres, bool[] data, bool persistente = false)
 {
     var canales = ValidarCanales(nombres);
     if (data == null)
     {
         throw new ArgumentNullException("data");
     }
     if (data.Length != canales)
     {
         throw new ArgumentException("El numero de canales especificados " + canales.ToString() +
             " no corresponde al numero de canales en datos " + data.Length.ToString());
     }
     Task digitalWriteTask = null;
     try
     {
         // Generar nombre de la tarea
         var nombreTarea = "E" + String.Join(",", nombres);
         // Si la tarea esta creada antes
         if (tareas.ContainsKey(nombreTarea))
         {
             digitalWriteTask = tareas[nombreTarea];
             persistente = true;
         }
         else
         {
             // Crear nueva tarea
             digitalWriteTask = new Task();
             // Agregar los canales
             digitalWriteTask.DOChannels.CreateChannel(
                 String.Join(",", nombres),
                 "",
                 ChannelLineGrouping.OneChannelForAllLines);
             // Guardar tarea persistente
             if (persistente)
             {
                 tareas.Add(nombreTarea, digitalWriteTask);
             }
         }
         // Escribir los datos
         var writer = new DigitalSingleChannelWriter(digitalWriteTask.Stream);
         writer.WriteSingleSampleMultiLine(true, data);
     }
     catch (DaqException ex)
     {
         throw new DriverException(ex);
     }
     finally
     {
         if (!persistente && (digitalWriteTask != null))
         {
             digitalWriteTask.Dispose();
             digitalWriteTask = null;
         }
     }
 }
Esempio n. 45
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();
        }
Esempio n. 46
0
        // 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;
        }
Esempio n. 47
0
        /// <summary>
        /// Writes to the specified line number
        /// </summary>
        /// <param name="linenum"></param>
        /// <param name="value"></param>
        public void WriteLine(uint linenum, bool value)
        {
            string linename = GetName(linenum);
            _dic_values[linename] = value;

            if (_dev_type == Device_Types.NI_USB6008)
            {
                using (Task digitalWriteTask = new Task())
                {
                    //  Create an Digital Output channel and name it.
                    string linestr = string.Format("{0}/line{1}", _ni_port_desc, linenum);
                    string name = string.Format("line{0}", linenum);
                    digitalWriteTask.DOChannels.CreateChannel(linestr, name, ChannelLineGrouping.OneChannelForEachLine);

                    //  Write digital port data. WriteDigitalSingChanSingSampPort writes a single sample
                    //  of digital data on demand, so no timeout is necessary.
                    DigitalSingleChannelWriter writer = new DigitalSingleChannelWriter(digitalWriteTask.Stream);
                    writer.WriteSingleSampleSingleLine(true, value);
                }
                return;
            }
            else if (_dev_type == Device_Types.FT232H)
            {
                FTD2XX_NET.FTDI.FT_STATUS status = _ft232hdio.SetPin(_ftdi_bus, linenum, value);
                // ERROR if device is disconnected and then reconnected
                // Try to recover
                if (status != FTD2XX_NET.FTDI.FT_STATUS.FT_OK)
                {
                    try
                    {
                        Close();
                        initFT232H();
                        Open();
                        status = _ft232hdio.SetPin(_ftdi_bus, linenum, value);
                    }
                    catch { }
                }

                if (status != FTD2XX_NET.FTDI.FT_STATUS.FT_OK)
                {
                    throw new Exception(
                        string.Format("Error setting pin {0} to state {1}. Error = {2}", linenum, value, status.ToString() ) );
                }
                return;
            }
        }
Esempio n. 48
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");
        }
Esempio n. 49
0
 internal void ZeroPortOnDev(string dev, int port)
 {
     lock (this)
     {
         try
         {
             // Create a digital out task for a given device and port.
             // Write clearingBufferSize zeros to that port. Wait
             // until this is finished and destroy the clearning Task.
             Task digitalClearingTask = new Task("DigiClear");
             digitalClearingTask.DOChannels.CreateChannel("/" + dev + "/Port" + port, "",
                 ChannelLineGrouping.OneChannelForAllLines);
             //digitalClearingTask.Timing.ConfigureSampleClock("100KHzTimeBase",
             //    clearingSampleRate,
             //    SampleClockActiveEdge.Rising,
             //    SampleQuantityMode.FiniteSamples,
             //    clearingBufferSize);
             DigitalSingleChannelWriter digitalClearingWriter = new DigitalSingleChannelWriter(digitalClearingTask.Stream);
             digitalClearingWriter.BeginWriteSingleSamplePort(true,0,null,null);
             digitalClearingTask.WaitUntilDone(30);
             digitalClearingTask.Stop();
             digitalClearingTask.Dispose();
             digitalClearingTask = null;
         }
         catch (Exception e)
         {
             Console.WriteLine(" Could not zero digital output on device: "
                 + dev + "/" + port);
         }
     }
 }
Esempio n. 50
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");
        }
Esempio n. 51
0
        //Called after data acq. is complete, resets buttons and stops tasks.
        private void reset()
        {
            // Disable asychronous activity
            taskRunning = false;

            // Start by resetting the hardware settings
            UpdateRecordingSettings();

            //Grab display gains for later use
            if (spikePlotData != null)
                if (spikePlotData.getGain() != null)
                    Properties.Settings.Default.SpikeDisplayGain = spikePlotData.getGain();
            if (Properties.Settings.Default.UseLFPs & (lfpPlotData != null))
                Properties.Settings.Default.LFPDisplayGain = lfpPlotData.getGain();
            if (waveformPlotData != null)
                if (waveformPlotData.getGain() != null)
                    Properties.Settings.Default.SpkWfmDisplayGain = waveformPlotData.getGain();
            Console.WriteLine("reset: gains saved");

            if (triggerWriter != null)
            {
                byte[] b_array = new byte[3] { 0, 0, 0 };
                DigitalWaveform wfm = new DigitalWaveform(3, 8, DigitalState.ForceDown);
                wfm = NationalInstruments.DigitalWaveform.FromPort(b_array);
                triggerTask = new Task("TriggerTask");
                triggerTask.DOChannels.CreateChannel(Properties.Settings.Default.CineplexDevice + "/Port0/line0:7", "",
                    ChannelLineGrouping.OneChannelForAllLines);
                triggerWriter = new DigitalSingleChannelWriter(triggerTask.Stream);
                triggerWriter.WriteWaveform(true, wfm);
                triggerTask.WaitUntilDone();
            }
            Console.WriteLine("reset: trigger cleared");
            // Kill the background workers
            lock (this)
            {
                Console.WriteLine("reset: entered lock");
                if (bwSpikes != null)
                {
                    try
                    {
                        for (int i = 0; i < bwSpikes.Count; ++i)
                            //block while bw finishes
                            if (bwSpikes[i] != null)
                            {
                                Console.WriteLine("reset: " + bwSpikes[i].ToString() + " " + i.ToString() + "is busy");
                                while (bwSpikes[i].IsBusy)
                                {
                                    Application.DoEvents();
                                }
                                Console.WriteLine("reset: " + bwSpikes[i].ToString() + " " + i.ToString() + "finished");
                            }

                    }
                    catch
                    {
                        Console.WriteLine("reset: error while clearing spike tasks");
                        //All the bw workers are done, so we'll kill them
                        for (int i = 0; i < bwSpikes.Count; ++i)
                            bwSpikes[i].Dispose();
                        bwSpikes.Clear();
                        bwSpikes = null;
                    }
                }
                Console.WriteLine("reset: left lock");
            }
            Console.WriteLine("reset: spike tasks cleared");

            if (waveformPlotData != null) waveformPlotData.stop();
            if (Properties.Settings.Default.SeparateLFPBoard && lfpTask != null) lfpTask.Dispose();
            if (Properties.Settings.Default.UseEEG && eegTask != null) eegTask.Dispose();
            if (BNCOutput != null) { BNCOutput.Dispose(); BNCOutput = null; }
            if (stimTimeTask != null) stimTimeTask.Dispose();
            if (triggerTask != null) triggerTask.Dispose();
            if (auxAnInTask != null) auxAnInTask.Dispose();
            if (auxDigInTask != null) auxDigInTask.Dispose();
            Console.WriteLine("reset: tasks disposed of");
            buttonStop.Enabled = false;
            buttonStart.Enabled = true;
            spikeDet.numPreSamples.Enabled = true;
            spikeDet.numPostSamples.Enabled = true;
            settingsToolStripMenuItem.Enabled = true;
            button_Train.Enabled = true;
            button_SetRecordingStreams.Enabled = true;
            switch_record.Enabled = true;
            //processingSettingsToolStripMenuItem.Enabled = true;
            button_startStimFromFile.Enabled = true;
            button_startClosedLoopStim.Enabled = true;
            //numericUpDown_NumSnipsDisplayed.Enabled = true;
            button_stopClosedLoopStim.Enabled = false;
            button_startClosedLoopStim.Enabled = true;
            checkBox_SALPA.Enabled = true;

            Console.WriteLine("reset: gui updated");
            // Clean up data streams
            recordingSettings.Flush();
            Console.WriteLine("reset: recording streams flushed");
            if (triggerWriter != null) triggerWriter = null;
            channelOut.Enabled = Properties.Settings.Default.UseSingleChannelPlayback;

            led_recording.OnColor = Color.Lime;
            if (!button_startStimFromFile.Enabled) { button_startStimFromFile.Enabled = true; }

            //debugger
            if (Debugger != null)
            {
                Debugger.Close();
                Debugger = null;
            }

            timer_timeElapsed.Enabled = false;
            Console.WriteLine("Reset Complete");
        }
Esempio n. 52
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;
        }
        internal void getImpedance(double startFreq, double stopFreq, double numPeriods, bool isCurrentControlled, int startChannel, int numChannels,
            double RCurr, double RMeas, double RGain, double commandVoltage, bool useBandpassFilter, bool useMatchedFilter)
        {
            this.numPeriods = numPeriods;
            this.startChannel = startChannel;
            this.numChannels = numChannels;
            this.RCurr = RCurr;
            this.RGain = RGain;
            this.RMeas = RMeas;
            this.commandVoltage = commandVoltage;
            this.isCurrentControlled = isCurrentControlled;
            this.useBandpassFilter = useBandpassFilter;
            this.useMatchedFilter = useMatchedFilter;

            //StartChannel is 1-based
            if (startFreq == stopFreq)
                freqs = new double[1];
            else if ((stopFreq/startFreq)%RESOLUTION == 0) //stopFreq is a RESOLUTION multiple of startFreq
                freqs = new double[Convert.ToInt32(Math.Floor(Math.Log(stopFreq / startFreq) / Math.Log(RESOLUTION))) + 1]; //This determines the number of frequencies counting by doublings
            else //not an exact multiple
                freqs = new double[Convert.ToInt32(Math.Floor(Math.Log(stopFreq / startFreq) / Math.Log(RESOLUTION))) + 2]; //This determines the number of frequencies counting by doublings

            //Populate freqs vector
            freqs[0] = startFreq;
            for (int i = 1; i < freqs.GetLength(0); ++i)
                freqs[i] = freqs[i - 1] * RESOLUTION;
            if (freqs[freqs.Length - 1] > stopFreq) freqs[freqs.Length - 1] = stopFreq;

            //Setup tasks
            impedanceRecord = new Task("Impedance Analog Input Task");
            stimDigitalTask = new Task("stimDigitalTask_impedance");
            stimAnalogTask = new Task("stimAnalogTask_impedance");

            //Choose appropriate input for current/voltage-controlled stimulation
            String inputChannel = (isCurrentControlled ? "/ai2" : "/ai3");
            //if (isCurrentControlled) inputChannel = "/ai2";
            //else inputChannel = "/ai3";
            impedanceRecord.AIChannels.CreateVoltageChannel(Properties.Settings.Default.ImpedanceDevice + inputChannel, "",
                AITerminalConfiguration.Rse, -5.0, 5.0, AIVoltageUnits.Volts);
            //try delaying sampling
            impedanceRecord.Timing.DelayFromSampleClock = 10;
            impedanceRecord.Timing.ConfigureSampleClock("", IMPEDANCE_SAMPLING_RATE, SampleClockActiveEdge.Rising,
                SampleQuantityMode.FiniteSamples);
            impedanceReader = new AnalogSingleChannelReader(impedanceRecord.Stream);
            impedanceRecord.Timing.ReferenceClockSource = "OnboardClock";

            //Configure stim digital output task
            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);

            //Configure stim analog output task
            if (Properties.Settings.Default.StimPortBandwidth == 32)
            {
                stimAnalogTask.AOChannels.CreateVoltageChannel(Properties.Settings.Default.StimulatorDevice + "/ao0", "", -10.0, 10.0, AOVoltageUnits.Volts); //Triggers
                stimAnalogTask.AOChannels.CreateVoltageChannel(Properties.Settings.Default.StimulatorDevice + "/ao1", "", -10.0, 10.0, AOVoltageUnits.Volts); //Triggers
                stimAnalogTask.AOChannels.CreateVoltageChannel(Properties.Settings.Default.StimulatorDevice + "/ao2", "", -10.0, 10.0, AOVoltageUnits.Volts); //Actual Pulse
                stimAnalogTask.AOChannels.CreateVoltageChannel(Properties.Settings.Default.StimulatorDevice + "/ao3", "", -10.0, 10.0, AOVoltageUnits.Volts); //Timing
            }
            else if (Properties.Settings.Default.StimPortBandwidth == 8)
            {
                stimAnalogTask.AOChannels.CreateVoltageChannel(Properties.Settings.Default.StimulatorDevice + "/ao0", "", -10.0, 10.0, AOVoltageUnits.Volts); //Actual pulse
                stimAnalogTask.AOChannels.CreateVoltageChannel(Properties.Settings.Default.StimulatorDevice + "/ao1", "", -10.0, 10.0, AOVoltageUnits.Volts); //Timing
            }
            stimAnalogTask.Timing.ConfigureSampleClock("/" + Properties.Settings.Default.ImpedanceDevice + "/ai/SampleClock",
                IMPEDANCE_SAMPLING_RATE, SampleClockActiveEdge.Rising, SampleQuantityMode.FiniteSamples);
            stimAnalogTask.Triggers.StartTrigger.ConfigureDigitalEdgeTrigger("/" +
                Properties.Settings.Default.ImpedanceDevice + "/ai/StartTrigger",
                DigitalEdgeStartTriggerEdge.Rising);
            impedanceRecord.Control(TaskAction.Verify);
            stimAnalogTask.Timing.ReferenceClockSource = impedanceRecord.Timing.ReferenceClockSource;
            stimAnalogTask.Timing.ReferenceClockRate = impedanceRecord.Timing.ReferenceClockRate;
            stimAnalogWriter = new AnalogMultiChannelWriter(stimAnalogTask.Stream);

            //Verify tasks
            impedanceRecord.Control(TaskAction.Verify);
            stimDigitalTask.Control(TaskAction.Verify);
            stimAnalogTask.Control(TaskAction.Verify);

            //Setup storage variable
            impedance = new double[numChannels][];
            for (int c = 0; c < numChannels; ++c)
            {
                impedance[c] = new double[freqs.GetLength(0)];
                for (int f = 0; f < freqs.Length; ++f)
                    impedance[c][f] = double.NaN;
            }

            //Setup background worker
            bgWorker = new BackgroundWorker();
            bgWorker.DoWork += new DoWorkEventHandler(bgWorker_DoWork);
            bgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgWorker_RunWorkerCompleted);
            bgWorker.ProgressChanged += new ProgressChangedEventHandler(bgWorker_ProgressChanged);
            bgWorker.WorkerSupportsCancellation = true;
            bgWorker.WorkerReportsProgress = true;

            //Run worker
            bgWorker.RunWorkerAsync();
        }
Esempio n. 54
0
        private void button_computeGain_Click(object sender, EventArgs e)
        {
            double startFreq = Convert.ToDouble(numericUpDown_startFreq.Value);
            double stopFreq = Convert.ToDouble(numericUpDown_stopFreq.Value);
            double numPeriods = Convert.ToDouble(numericUpDown_numPeriods.Value);
            double[] freqs = new double[1 + Convert.ToInt32(Math.Floor(Math.Log(stopFreq / startFreq) / Math.Log(Convert.ToDouble(textBox_diagnosticsMult.Text))))]; //This determines the number of frequencies counting by doublings

            radioButton_stimVoltageControlled.Checked = true;
            radioButton_stimVoltageControlled_Click(null, null);

            //Populate freqs vector
            freqs[0] = startFreq;
            for (int i = 1; i < freqs.GetLength(0); ++i)
                freqs[i] = freqs[i - 1] * Convert.ToDouble(textBox_diagnosticsMult.Text);

            spikeSamplingRate = Properties.Settings.Default.RawSampleFrequency;
            buttonStart.Enabled = false;  //So users can't try to get data from the same card
            button_computeGain.Enabled = false;
            button_computeGain.Refresh();
            buttonStart.Refresh();
            spikeTask = new List<Task>(Properties.Settings.Default.AnalogInDevice.Count);
            diagnosticsReaders = new List<AnalogMultiChannelReader>(Properties.Settings.Default.AnalogInDevice.Count);
            for (int i = 0; i < Properties.Settings.Default.AnalogInDevice.Count; ++i)
            {
                spikeTask.Add(new Task("spikeTask_Diagnostics_" + i));
                int numChannelsPerDevice = (numChannels < 32 ? numChannels : 32);
                for (int j = 0; j < numChannelsPerDevice; ++j)
                    spikeTask[i].AIChannels.CreateVoltageChannel(Properties.Settings.Default.AnalogInDevice[0] + "/ai" + j.ToString(), "",
                        AITerminalConfiguration.Nrse, -10.0, 10.0, AIVoltageUnits.Volts);

                //Change gain based on comboBox values (1-100)
                setGain(spikeTask[i], Properties.Settings.Default.A2Dgain);

                //Verify the Task
                spikeTask[i].Control(TaskAction.Verify);

                spikeTask[i].Timing.ConfigureSampleClock("", spikeSamplingRate, SampleClockActiveEdge.Rising,
                    SampleQuantityMode.FiniteSamples);
                diagnosticsReaders.Add(new AnalogMultiChannelReader(spikeTask[i].Stream));
            }

            spikeTask[0].Timing.ReferenceClockSource = "OnboardClock";
            for (int i = 1; i < spikeTask.Count; ++i)
            {
                spikeTask[i].Timing.ReferenceClockSource = spikeTask[0].Timing.ReferenceClockSource;
                spikeTask[i].Timing.ReferenceClockRate = spikeTask[0].Timing.ReferenceClockRate;
            }
            stimPulseTask.Timing.ReferenceClockSource = spikeTask[0].Timing.ReferenceClockSource;
            stimPulseTask.Timing.ReferenceClockRate = spikeTask[0].Timing.ReferenceClockRate;

            stimDigitalTask.Dispose();
            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
            stimDigitalWriter = new DigitalSingleChannelWriter(stimDigitalTask.Stream);
            stimPulseTask.Timing.ConfigureSampleClock("/" + Properties.Settings.Default.AnalogInDevice[0] + "/ai/SampleClock",
                spikeSamplingRate, SampleClockActiveEdge.Rising, SampleQuantityMode.FiniteSamples);
            stimPulseTask.Triggers.StartTrigger.ConfigureDigitalEdgeTrigger("/" +
                                Properties.Settings.Default.AnalogInDevice[0] + "/ai/StartTrigger",
                                DigitalEdgeStartTriggerEdge.Rising);

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

            switch (Properties.Settings.Default.NumChannels)
            {
                case 0:
                    numChannels = 16;
                    break;
                case 1:
                    numChannels = 32;
                    break;
                case 2:
                    numChannels = 48;
                    break;
                case 3:
                    numChannels = 64;
                    break;
            }
            //gains = new double[numChannels, freqs.GetLength(0)];
            //numChannels = 1;

            gains = new double[numChannels][];
            for (int i = 0; i < numChannels; ++i)
                gains[i] = new double[freqs.GetLength(0)];
            scatterGraph_diagnostics.ClearData();
            scatterGraph_diagnostics.Plots.Clear();

            textBox_diagnosticsResults.Clear();

            if (!checkBox_diagnosticsBulk.Checked)
            {
                //for (int c = 1; c <= numChannels; ++c)
                for (int c = 13; c < 14; ++c)
                {
                    textBox_diagnosticsResults.Text += "Channel " + c.ToString() + "\r\n\tFrequency (Hz)\tGain (dB)\r\n";

                    scatterGraph_diagnostics.Plots.Add(new ScatterPlot());

                    UInt32 data = StimPulse.channel2MUX((double)c); //Get data bits lined up to control MUXes

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

                    for (int f = 0; f < freqs.GetLength(0); ++f)
                    {
                        double numSeconds = 1 / freqs[f];
                        if (numSeconds * numPeriods < 0.1)
                        {
                            numPeriods = Math.Ceiling(0.1 * freqs[f]);
                        }

                        int size = Convert.ToInt32(numSeconds * spikeSamplingRate);
                        SineSignal testWave = new SineSignal(freqs[f], Convert.ToDouble(numericUpDown_diagnosticsVoltage.Value));  //Generate a 100 mV sine wave at 1000 Hz
                        double[] testWaveValues = testWave.Generate(spikeSamplingRate, size);

                        double[,] analogPulse = new double[2, size];

                        for (int i = 0; i < size; ++i)
                            analogPulse[0, i] = testWaveValues[i];

                        for (int i = 0; i < spikeTask.Count; ++i)
                            spikeTask[i].Timing.SamplesPerChannel = (long)(numPeriods * size);

                        stimPulseTask.Timing.SamplesPerChannel = (long)(numPeriods * size); //Do numperiods cycles of sine wave
                        stimPulseWriter.WriteMultiSample(true, analogPulse);

                        double[] stateData = new double[4];
                        stateData[0] = (double)c;
                        stateData[1] = freqs[f];
                        stateData[2] = (double)f;
                        for (int i = diagnosticsReaders.Count - 1; i >= 0; --i)
                        {
                            stateData[3] = (double)i;
                            diagnosticsReaders[i].BeginReadMultiSample((int)(numPeriods * size), analogInCallback_computeGain, (Object)stateData); //Get 5 seconds of "noise"
                        }

                        stimPulseTask.WaitUntilDone();
                        for (int i = 0; i < spikeTask.Count; ++i)
                        {
                            spikeTask[i].WaitUntilDone();
                            spikeTask[i].Stop();
                        }
                        stimPulseTask.Stop();
                    }
                    stimDigitalWriter.WriteSingleSamplePort(true, 0);
                    stimDigitalTask.WaitUntilDone();
                    stimDigitalTask.Stop();
                    //DEBUGGING
                    c = 1;
                    scatterGraph_diagnostics.Plots[c - 1].PlotXY(freqs, gains[c - 1]);
                    for (int f = 0; f < freqs.GetLength(0); ++f)
                    {
                        textBox_diagnosticsResults.Text += "\t" + freqs[f].ToString() + "\t" + gains[c - 1][f] + "\r\n";
                    }
                    textBox_diagnosticsResults.Text += "\r\n";
                    scatterGraph_diagnostics.Refresh();

                    //DEBUGGING
                    c = 100;
                }
            }
            else
            {
                for (int f = 0; f < freqs.GetLength(0); ++f)
                {
                    double numSeconds = 1 / freqs[f];
                    if (numSeconds * numPeriods < 0.1)
                    {
                        numPeriods = Math.Ceiling(0.1 * freqs[f]);
                    }

                    int size = Convert.ToInt32(numSeconds * spikeSamplingRate);
                    SineSignal testWave = new SineSignal(freqs[f], Convert.ToDouble(numericUpDown_diagnosticsVoltage.Value));  //Generate a 100 mV sine wave at 1000 Hz
                    double[] testWaveValues = testWave.Generate(spikeSamplingRate, size);

                    double[,] analogPulse = new double[2, size];

                    for (int i = 0; i < size; ++i)
                        analogPulse[0, i] = testWaveValues[i];

                    for (int i = 0; i < spikeTask.Count; ++i)
                        spikeTask[i].Timing.SamplesPerChannel = (long)(numPeriods * size);

                    stimPulseTask.Timing.SamplesPerChannel = (long)(numPeriods * size); //Do numperiods cycles of sine wave
                    stimPulseWriter.WriteMultiSample(true, analogPulse);

                    double[] stateData = new double[4];
                    stateData[0] = -1.0;
                    stateData[1] = freqs[f];
                    stateData[2] = (double)f; //Frequency of interest

                    for (int i = diagnosticsReaders.Count - 1; i >= 0; --i)
                    {
                        stateData[3] = (double)i; //Keeps track of which device called the reader
                        diagnosticsReaders[i].BeginReadMultiSample((int)(numPeriods * size), analogInCallback_computeGain, (Object)stateData); //Get 5 seconds of "noise"
                    }

                    stimPulseTask.WaitUntilDone();
                    for (int i = 0; i < spikeTask.Count; ++i)
                    {
                        spikeTask[i].WaitUntilDone();
                        spikeTask[i].Stop();
                    }
                    stimPulseTask.Stop();
                }
                for (int c = 0; c < numChannels; ++c)
                {
                    scatterGraph_diagnostics.Plots.Add(new ScatterPlot());
                    scatterGraph_diagnostics.Plots[c].PlotXY(freqs, gains[c]);
                    textBox_diagnosticsResults.Text += "Channel " + (c + 1).ToString() + "\r\n\tFrequency (Hz)\tGain (dB)\r\n";
                    for (int f = 0; f < freqs.GetLength(0); ++f)
                    {
                        textBox_diagnosticsResults.Text += "\t" + freqs[f].ToString() + "\t" + gains[c][f].ToString() + "\r\n";
                    }
                    textBox_diagnosticsResults.Text += "\r\n";
                }
                scatterGraph_diagnostics.Refresh();
            }
            buttonStart.Enabled = true;
            button_computeGain.Enabled = true;

            //Now, destroy the objects we made
            updateSettings();
            gains = null;
            diagnosticsReaders = null;
        }
Esempio n. 55
0
        public void Configure( double clockFrequency, bool loop, bool fullWidth,
                                    bool lowGroup, int length, bool internalClock, bool triggered)
        {
            this.clockFrequency = clockFrequency;
            this.length = length;

            pgTask = new Task("pgTask");

            /**** Configure the output lines ****/

            // The underscore notation is the way to address more than 8 of the PatternList generator
            // lines at once. This is really buried in the NI-DAQ documentation !
            String chanString = "";
            if ((string)Environs.Hardware.GetInfo("PGType") == "dedicated")
            {
                if (fullWidth) chanString = device + "/port0_32";
                else
                {
                    if (lowGroup) chanString = device + "/port0_16";
                    else chanString = device + "/port3_16";
                }
            }
            // as far as I know you can only address the whole 32-bit port on the 6229 type integrated PatternList generators
            if ((string)Environs.Hardware.GetInfo("PGType") == "integrated")
            {
                chanString = device + "/port0";
            }

            DOChannel doChan = pgTask.DOChannels.CreateChannel(
                chanString,
                "pg",
                ChannelLineGrouping.OneChannelForAllLines
                );

            /**** Configure the clock ****/

            String clockSource = "";
            if ((string)Environs.Hardware.GetInfo("PGType") == "dedicated")
            {
                if (!internalClock) clockSource = (string)Environment.Environs.Hardware.GetInfo("PGClockLine");
                else clockSource = "";
            }

            if ((string)Environs.Hardware.GetInfo("PGType") == "integrated")
            {
                // clocking is more complicated for the 6229 style PG boards as they don't have their own internal clock.

                // if external clocking is required it's easy:
                if (!internalClock) clockSource = (string)Environment.Environs.Hardware.GetInfo("PGClockLine");
                else
                {
                    // if an internal clock is requested we generate it using the card's timer/counters.
                    counterTask = new Task();
                    counterTask.COChannels.CreatePulseChannelFrequency(
                        device + (string)Environs.Hardware.GetInfo("PGClockCounter"),
                        "PG Clock",
                        COPulseFrequencyUnits.Hertz,
                        COPulseIdleState.Low,
                        0.0,
                        clockFrequency,
                        0.5
                        );
                    counterTask.Timing.SampleQuantityMode = SampleQuantityMode.ContinuousSamples;
                    counterTask.Start();

                    clockSource = device + (string)Environs.Hardware.GetInfo("PGClockCounter") + "InternalOutput";
                }
            }

            /**** Configure regeneration ****/

            SampleQuantityMode sqm;
            if (loop)
            {
                sqm = SampleQuantityMode.ContinuousSamples;
                pgTask.Stream.WriteRegenerationMode = WriteRegenerationMode.AllowRegeneration;

            }
            else
            {
                sqm = SampleQuantityMode.FiniteSamples;
                pgTask.Stream.WriteRegenerationMode = WriteRegenerationMode.DoNotAllowRegeneration;

            }

            pgTask.Timing.ConfigureSampleClock(
                clockSource,
                clockFrequency,
                SampleClockActiveEdge.Rising,
                sqm,
                length
                );

            /**** Configure buffering ****/

            if ((string)Environs.Hardware.GetInfo("PGType") == "dedicated")
            {
                // these lines are critical - without them DAQMx copies the data you provide
                // as many times as it can into the on board FIFO (the cited reason being stability).
                // This has the annoying side effect that you have to wait for the on board buffer
                // to stream out before you can update the patterns - this takes ~6 seconds at 1MHz.
                // These lines tell the board and the software to use buffers as close to the size of
                // the PatternList as possible (on board buffer size is coerced to be related to a power of
                // two, so you don't quite get what you ask for).
                // note that 6229 type integrated PGs only have 2kB buffer, so this isn't needed for them (or allowed, in fact)
                pgTask.Stream.Buffer.OutputBufferSize = length;
                pgTask.Stream.Buffer.OutputOnBoardBufferSize = length;
            }

            /**** Configure triggering ****/
            if (triggered)
            {
                pgTask.Triggers.StartTrigger.ConfigureDigitalEdgeTrigger(
                    (string)Environs.Hardware.GetInfo("PGTrigger"),
                    DigitalEdgeStartTriggerEdge.Rising);
            }

            /**** Write configuration to board ****/

            pgTask.Control(TaskAction.Commit);
            writer = new DigitalSingleChannelWriter(pgTask.Stream);
        }
Esempio n. 56
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;
            }
        }
        public DigitalIO(int channel)
        {
            try
            {

                    doTask.DOChannels.CreateChannel(doline[channel], "", ChannelLineGrouping.OneChannelForAllLines);
                    diTask.DIChannels.CreateChannel(diline[channel], "", ChannelLineGrouping.OneChannelForAllLines);

                    writer = new DigitalSingleChannelWriter(doTask.Stream);
                    reader = new DigitalSingleChannelReader(diTask.Stream);

            }

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