public int ReadDIN(int nDev, int nPort, int nStartLine, int nEndLine) { int nResult = 0; string strDev = "Dev" + string.Format("{0:d}", nDev) + "/port" + string.Format("{0:d}", nPort) + "/line" + string.Format("{0:d}", nStartLine) + ":" + string.Format("{0:d}", nEndLine); try { using (Task digitalReadTask = new Task()) { digitalReadTask.DIChannels.CreateChannel(strDev, "", ChannelLineGrouping.OneChannelForAllLines); DigitalSingleChannelReader reader = new DigitalSingleChannelReader(digitalReadTask.Stream); UInt32 data = reader.ReadSingleSamplePortUInt32(); nResult = int.Parse(data.ToString()); //Update the Data Read box // hexData.Text = String.Format("0x{0:X}", data); } } catch (DaqException ex) { // MessageBox.Show(ex.Message); } finally { // Cursor.Current = Cursors.Default; } return(nResult); }
//포트0 연결 public bool Connect_port0_read(ref string ErrorMsg) { bool flag = false; try { flag = true; Readtask = new NationalInstruments.DAQmx.Task(); Readtask.DIChannels.CreateChannel(ini.GetIniValue("NI", "Name") + "/port0/line0:7", "Digital Input", ChannelLineGrouping.OneChannelForAllLines); reader = new DigitalSingleChannelReader(Readtask.Stream); if (reader != null) { Input = reader.ReadSingleSampleMultiLine(); } } catch (DaqException de) { flag = false; ErrorMsg = de.Message; } catch (Exception e) { ErrorMsg = e.Message; } return(flag); }
public uint ReadDigPort(string lines, string name) { //Create a task such that it will be disposed after //we are done using it. Task digitalReadTask = new Task(); uint data = 0; try { //Create channel digitalReadTask.DIChannels.CreateChannel(lines, "port0", ChannelLineGrouping.OneChannelForAllLines); DigitalSingleChannelReader reader = new DigitalSingleChannelReader(digitalReadTask.Stream); digitalReadTask.Start(); data = reader.ReadSingleSamplePortUInt32(); digitalReadTask.Stop(); Debug.Print(String.Format("0x{0:X}", data)); //return data; } catch (DaqException ex) { DaqError(ex.Message); } finally { //dispose task digitalReadTask.Dispose(); } return(data); }
private void BTN_Start_Click(object sender, EventArgs e) { Cursor.Current = Cursors.WaitCursor; try { myTask = new Task(); myTask.DIChannels.CreateChannel(comboBox1.Text, "", ChannelLineGrouping.OneChannelForAllLines); myDigitalReader = new DigitalSingleChannelReader(myTask.Stream); timer1.Enabled = true; BTN_Start.Enabled = false; BTN_Stop.Enabled = true; } catch (Exception ex) { MessageBox.Show(ex.Message); myTask.Dispose(); BTN_Start.Enabled = true; BTN_Stop.Enabled = false; } finally { Cursor.Current = Cursors.Default; } }
//read Digital Input(port0) - input public uint reading_DI(string device, string port_name) { UInt32 dataDI = 0; Task digitalReadTask = new Task(); digitalReadTask.DIChannels.CreateChannel(device, port_name, ChannelLineGrouping.OneChannelForAllLines); DigitalSingleChannelReader reader = new DigitalSingleChannelReader(digitalReadTask.Stream); dataDI = reader.ReadSingleSamplePortUInt32(); return(dataDI); }
public static byte ReadDigital(Task task) { if (disposed) { return(0); } DigitalSingleChannelReader reader = new DigitalSingleChannelReader(task.Stream); byte sample = reader.ReadSingleSamplePortByte(); return(sample); }
public void Read2() { try { string[] channelNameList = DaqSystem.Local.GetPhysicalChannels(PhysicalChannelTypes.DILine, PhysicalChannelAccess.External); if (channelNameList.Length > 0) { Task task = new Task("Digital Input Test"); task.DIChannels.CreateChannel(channelNameList[0] + ":7", "", ChannelLineGrouping.OneChannelForAllLines); task.Timing.ConfigureSampleClock("", 10000, SampleClockActiveEdge.Rising, SampleQuantityMode.FiniteSamples); task.Control(TaskAction.Verify); DigitalSingleChannelReader diread = new DigitalSingleChannelReader(task.Stream); DigitalWaveform waveform; for (int i = 0; i < repeat; i++) { waveform = diread.ReadWaveform(sampleRate); foreach (DigitalWaveformSignal signal in waveform.Signals) { foreach (DigitalState state in signal.States) { if (state == DigitalState.ForceDown) { Console.Write(0); } else if (state == DigitalState.ForceUp) { Console.Write(1); } else { Console.Write("?"); } } Console.WriteLine(); } Console.Out.WriteLine("Acquire " + i + "th try"); } StreamWriter writer = new StreamWriter(File.Open("di.txt", FileMode.Create)); int c = 0; foreach (double d in datalist) { writer.WriteLine(String.Format("{0} {1}", c, d)); c++; } writer.Close(); } } catch (DaqException e) { Console.Out.WriteLine(e.Message); } }
/// <summary> /// Initializes the data reader board. /// </summary> internal DataControllerHulk() { logger.Info("Create: DataControllerHulk"); // Create a task to check whether the PLC is OK checkPLCTask = new Task("CheckPLCTask"); checkPLCTask.DIChannels.CreateChannel(ConfigurationManager.AppSettings["InputLineCheckPLC"], "checkPLC", ChannelLineGrouping.OneChannelForEachLine); checkPLCTask.Timing.SampleTimingType = SampleTimingType.OnDemand; checkPLCTask.Timing.SampleQuantityMode = SampleQuantityMode.ContinuousSamples; checkPLCReader = new DigitalSingleChannelReader(checkPLCTask.Stream); // Create a task to check the status of the safety light checkLightsTask = new Task("CheckLightsTask"); checkLightsTask.DIChannels.CreateChannel(ConfigurationManager.AppSettings["InputLineCheckLights1"], "checkLights1", ChannelLineGrouping.OneChannelForEachLine); checkLightsTask.DIChannels.CreateChannel(ConfigurationManager.AppSettings["InputLineCheckLights2"], "checkLights2", ChannelLineGrouping.OneChannelForEachLine); checkLightsTask.Timing.SampleTimingType = SampleTimingType.OnDemand; checkLightsTask.Timing.SampleQuantityMode = SampleQuantityMode.ContinuousSamples; checkLightsReader = new DigitalMultiChannelReader(checkLightsTask.Stream); // Create a task to check for MAYDAY signals checkMaydayTask = new Task("CheckMaydayTask"); checkMaydayTask.DIChannels.CreateChannel(ConfigurationManager.AppSettings["InputLineCheckMayday1"], "checkMayday1", ChannelLineGrouping.OneChannelForEachLine); checkMaydayTask.DIChannels.CreateChannel(ConfigurationManager.AppSettings["InputLineCheckMayday2"], "checkMayday2", ChannelLineGrouping.OneChannelForEachLine); checkMaydayTask.Timing.SampleTimingType = SampleTimingType.OnDemand; checkMaydayTask.Timing.SampleQuantityMode = SampleQuantityMode.ContinuousSamples; checkMaydayReader = new DigitalMultiChannelReader(checkMaydayTask.Stream); // Create a task for sending 'PC Ready' signals pcReadyTask = new Task("PCReadyTask"); pcReadyTask.DOChannels.CreateChannel(ConfigurationManager.AppSettings["OutputLinePCReady"], "pcReady", ChannelLineGrouping.OneChannelForEachLine); pcReadyWriter = new DigitalSingleChannelWriter(pcReadyTask.Stream); logger.Info("Data tasks initialized."); }
//KONSTRUKTOR public NIDriver(int pocetBodov) { UlohaCounter = new Task("Counter"); Intensity = 0; StartSignal = new Task("Start Signal"); DIChannel myDIChannel; myDIChannel = StartSignal.DIChannels.CreateChannel( prevodnikId + "/port0", "read0", ChannelLineGrouping.OneChannelForAllLines ); reader = new DigitalSingleChannelReader(StartSignal.Stream); }
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); } } }
public int WriteDigChannelGroup(string lines, string name, uint val) { //Create a task such that it will be disposed after //we are done using it. int res = 0; Task digitalWriteTask = new Task(); DOChannel ch; try { //Create channel ch = digitalWriteTask.DOChannels.CreateChannel(lines, "digwrite", ChannelLineGrouping.OneChannelForAllLines); //Dim st As DOLineStatesStartState DigitalSingleChannelWriter writer = new DigitalSingleChannelWriter(digitalWriteTask.Stream); DigitalSingleChannelReader reader = new DigitalSingleChannelReader(digitalWriteTask.Stream); bool[] data; data = reader.ReadSingleSampleMultiLine(); digitalWriteTask.Start(); //st = ch.LineStatesStartState if (ch.Tristate == true) { ch.Tristate = false; } writer.WriteSingleSamplePort(false, val); digitalWriteTask.Stop(); //UpdateDigitalShadows(lines, CInt(val)); } catch (DaqException ex) { DaqError(ex.Message); res = -1; } finally { //dispose task digitalWriteTask.Dispose(); } return(res); }
void m_CheckState_CheckedChanged(object sender, EventArgs e) { if (this.m_CheckState.Checked) { this.task = new Task(); this.task.DIChannels.CreateChannel(this.m_Channels, "", ChannelLineGrouping.OneChannelForAllLines); this.reader = new DigitalSingleChannelReader(task.Stream); (this.m_Monitor = new Thread(this.Monitor) { IsBackground = true }).Start(); } else { this.CloseMonitor(); this.reader = null; this.task.Dispose(); this.task = null; } }
public int ReadDigChannel(string lines, string name) { //Create a task such that it will be disposed after //we are done using it. Task digitalReadTask = new Task(); int val = 0; try { //Create channel digitalReadTask.DIChannels.CreateChannel(lines, "DigRead", ChannelLineGrouping.OneChannelForEachLine); bool[] data; DigitalSingleChannelReader reader = new DigitalSingleChannelReader(digitalReadTask.Stream); digitalReadTask.Start(); data = reader.ReadSingleSampleMultiLine(); digitalReadTask.Stop(); for (int index = 0; index < data.Length; index++) { if (data[index] == true) { //if bit is true //add decimal value of bit val += 1 << index; } } //Debug.Print(String.Format(lines + ": " + "0x{0:X}", val)); //return val; } catch (DaqException ex) { DaqError(ex.Message); } finally { //dispose task digitalReadTask.Dispose(); } return(val); }
public static bool ReadDI(string port_num, int milliseconds = 100, string dev_name = "Dev1") { if (RuntimeConfiguration.Mode.HasFlag(RuntimeMode.VirtualNI)) { return(false); } dev_name = RefactorDevName(dev_name); Task task = new Task(); string port = port_num.Split(new char[] { '.' })[0]; string line = port_num.Split(new char[] { '.' })[1]; task.DIChannels.CreateChannel(string.Format("{0}/port{1}/line{2}", dev_name, port, line), "", ChannelLineGrouping.OneChannelForEachLine); DigitalSingleChannelReader reader = new DigitalSingleChannelReader(task.Stream); task.Start(); Thread.Sleep(milliseconds); bool res = reader.ReadSingleSampleSingleLine(); task.Stop(); return(res); }
//포트0 열결 해제 public void Disconnect_port0() { if (Writetask != null) { Writetask.Dispose(); Writetask = null; if (writer != null) { writer = null; } } if (Readtask != null) { Readtask.Dispose(); Readtask = null; if (reader != null) { reader = null; } } }
public void Read2() { try { string[] channelNameList = DaqSystem.Local.GetPhysicalChannels(PhysicalChannelTypes.DILine, PhysicalChannelAccess.External); if (channelNameList.Length > 0) { Task task = new Task("Digital Input Test"); task.DIChannels.CreateChannel(channelNameList[0]+":7", "",ChannelLineGrouping.OneChannelForAllLines); task.Timing.ConfigureSampleClock("", 10000, SampleClockActiveEdge.Rising, SampleQuantityMode.FiniteSamples); task.Control(TaskAction.Verify); DigitalSingleChannelReader diread = new DigitalSingleChannelReader(task.Stream); DigitalWaveform waveform; for (int i = 0; i < repeat; i++) { waveform = diread.ReadWaveform(sampleRate); foreach(DigitalWaveformSignal signal in waveform.Signals){ foreach (DigitalState state in signal.States) { if (state == DigitalState.ForceDown) { Console.Write(0); } else if (state == DigitalState.ForceUp) { Console.Write(1); } else { Console.Write("?"); } } Console.WriteLine(); } Console.Out.WriteLine("Acquire " + i + "th try"); } StreamWriter writer = new StreamWriter(File.Open("di.txt", FileMode.Create)); int c = 0; foreach (double d in datalist) { writer.WriteLine(String.Format("{0} {1}", c, d)); c++; } writer.Close(); } } catch (DaqException e) { Console.Out.WriteLine(e.Message); } }
public bool CanMoveSlider(int SliderPosition, string port) { try { Task readPort = new Task(); readPort.DIChannels.CreateChannel(port, "", ChannelLineGrouping.OneChannelForAllLines); DigitalSingleChannelReader DISMCSignals = new DigitalSingleChannelReader(readPort.Stream); bool[] states = DISMCSignals.ReadSingleSampleMultiLine(); string binary = ""; foreach (bool state in states) { if (state) { binary += "1"; } else { binary += "0"; } } char[] charArray = binary.ToCharArray(); Array.Reverse(charArray); binary = new string(charArray); int position = Convert.ToInt32(binary, 2); if (SliderPosition == position) { return(false); } else { return(true); } } catch (Exception) { return(false); } }
/// <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 RebuildTasks() { // http://zone.ni.com/reference/en-XX/help/370466AD-01/mxdevconsid/simultaneoustasks/ // http://zone.ni.com/reference/en-XX/help/370466AD-01/mxcncpts/explicitimplicitstates/ // http://zone.ni.com/reference/en-XX/help/370466AD-01/mxcncpts/taskstatemodel/ #region "DIGITAL OUT TASKS" NationalInstruments.DAQmx.Task[] digitalWriteTask = new NationalInstruments.DAQmx.Task[NiDigitalOutPorts.Count()]; digitalWriter = new DigitalSingleChannelWriter[NiDigitalOutPorts.Count()]; for (Int32 i = 0; i < NiDigitalOutPorts.Count(); i++) { digitalWriteTask[i] = new NationalInstruments.DAQmx.Task(); digitalWriteTask[i].DOChannels.CreateChannel(NiDigitalOutPorts[i], "portx", ChannelLineGrouping.OneChannelForAllLines); digitalWriter[i] = new DigitalSingleChannelWriter(digitalWriteTask[i].Stream); digitalWriteTask[i].Control(TaskAction.Verify); //digitalWriteTask[i].Control(TaskAction.Reserve); // TODO //digitalWriteTask[i].Control(TaskAction.Commit); //digitalWriteTask[i].Control(TaskAction.Start); } #endregion #region "DIGITAL IN TASKS" NationalInstruments.DAQmx.Task[] digitalReadTask = new NationalInstruments.DAQmx.Task[NiDigitalInPorts.Count()]; digitalReader = new DigitalSingleChannelReader[NiDigitalInPorts.Count()]; for (Int32 i = 0; i < NiDigitalInPorts.Count(); i++) { digitalReadTask[i] = new NationalInstruments.DAQmx.Task(); digitalReadTask[i].DIChannels.CreateChannel(NiDigitalInPorts[i], "portx", ChannelLineGrouping.OneChannelForAllLines); digitalReader[i] = new DigitalSingleChannelReader(digitalReadTask[i].Stream); digitalReadTask[i].Control(TaskAction.Verify); //digitalReadTask[i].Control(TaskAction.Reserve); //digitalReadTask[i].Control(TaskAction.Commit); //digitalReadTask[i].Control(TaskAction.Start); } #endregion #region "ANALOG OUT TASKS" NationalInstruments.DAQmx.Task[] analogOutTask = new NationalInstruments.DAQmx.Task[NiAllAnalogOut.Count()]; analogWriter = new AnalogSingleChannelWriter[NiAllAnalogOut.Count()]; Int32 analogOutCounter = 0; foreach (ChannelModel channel in NiAllAnalogOut) //for (Int32 analogCounter = 0; analogCounter < NI_ProgramConfigInstance.NiAllAnalogOut.Count(); analogCounter++) { try { analogOutTask[analogOutCounter] = new NationalInstruments.DAQmx.Task(); AOChannel myAOChannel; myAOChannel = analogOutTask[analogOutCounter].AOChannels.CreateVoltageChannel(channel.NIName, "", Convert.ToDouble(channel.Min), Convert.ToDouble(channel.Max), AOVoltageUnits.Volts); analogWriter[analogOutCounter] = new AnalogSingleChannelWriter(analogOutTask[analogOutCounter].Stream); analogOutTask[analogOutCounter].Control(TaskAction.Verify); //analogOutTask[analogOutCounter].Control(TaskAction.Reserve); //analogOutTask[analogOutCounter].Control(TaskAction.Commit); //analogOutTask[analogOutCounter].Control(TaskAction.Start); } catch (Exception ex) { LogFiles.AddLogEntry(12, String.Format("Analog Out Build Task Error, Message: {1} {0}", ex.Message, ex.Source)); //channel.Value //channel.ErrorCode = substring status code ex.Message; channel.ErrorText = ex.Message; } analogOutCounter++; } #endregion #region "ANALOG IN TASKS" NationalInstruments.DAQmx.Task[] analogInTask = new NationalInstruments.DAQmx.Task[NiAllAnalogIn.Count()]; analogReader = new AnalogSingleChannelReader[NiAllAnalogIn.Count()]; Int32 analogInCounter = 0; foreach (ChannelModel channel in NiAllAnalogIn) { try { analogInTask[analogInCounter] = new NationalInstruments.DAQmx.Task(); AIChannel myAIChannel; if ("RSE" == channel.InMode) { myAIChannel = analogInTask[analogInCounter].AIChannels.CreateVoltageChannel(channel.NIName, "", AITerminalConfiguration.Rse, Convert.ToDouble(channel.Min), Convert.ToDouble(channel.Max), AIVoltageUnits.Volts); } else if ("NRSE" == channel.InMode) { myAIChannel = analogInTask[analogInCounter].AIChannels.CreateVoltageChannel(channel.NIName, "", AITerminalConfiguration.Nrse, Convert.ToDouble(channel.Min), Convert.ToDouble(channel.Max), AIVoltageUnits.Volts); } else if ("Diff" == channel.InMode) { myAIChannel = analogInTask[analogInCounter].AIChannels.CreateVoltageChannel(channel.NIName, "", AITerminalConfiguration.Differential, Convert.ToDouble(channel.Min), Convert.ToDouble(channel.Max), AIVoltageUnits.Volts); } else if ("PDiff" == channel.InMode) { myAIChannel = analogInTask[analogInCounter].AIChannels.CreateVoltageChannel(channel.NIName, "", AITerminalConfiguration.Pseudodifferential, Convert.ToDouble(channel.Min), Convert.ToDouble(channel.Max), AIVoltageUnits.Volts); } else { // channel.InMode error myAIChannel = analogInTask[analogInCounter].AIChannels.CreateVoltageChannel(channel.NIName, "", AITerminalConfiguration.Rse, Convert.ToDouble(channel.Min), Convert.ToDouble(channel.Max), AIVoltageUnits.Volts); } analogInTask[analogInCounter].Control(TaskAction.Verify); analogReader[analogInCounter] = new AnalogSingleChannelReader(analogInTask[analogInCounter].Stream); //try { analogInTask[analogInCounter].Control(TaskAction.Reserve); } // TODO: check status //catch { } //try { analogInTask[analogInCounter].Control(TaskAction.Commit); } //catch { } //try { analogInTask[analogInCounter].Control(TaskAction.Start); } // By explicitly starting the task, these operations are performed once, not each time the read or write operation is performed. //catch { } } catch (Exception ex) { LogFiles.AddLogEntry(12, String.Format("Analog In Build Task Error, Message: {1} {0}", ex.Message, ex.Source)); //channel.Value //channel.ErrorCode = substring status code ex.Message; channel.ErrorText = ex.Message; } analogInCounter++; } #endregion }
/// <summary> /// Lee los valores de unos puertos de entrada binarios /// </summary> /// <param name="nombres">Nombres de puertos de entrada</param> /// <param name="persistente">true - para crear una tarea de lectura permanente</param> /// <returns>El valor de los puertos</returns> /// <exception cref="ArgumentNullException">Nombres 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 /// </exception> /// <exception cref="DriverException">Error de driver de la tarjeta</exception> public bool[] LeerBinario(string[] nombres, bool persistente = false) { ValidarCanales(nombres); Task digitalReadTask = null; try { // Generar nombre de la tarea var nombreTarea = "L" + String.Join(",", nombres); // Si la tarea esta creada antes if (tareas.ContainsKey(nombreTarea)) { digitalReadTask = tareas[nombreTarea]; persistente = true; } else { // Crear nueva tarea digitalReadTask = new Task(); // Agregar los canales digitalReadTask.DIChannels.CreateChannel( String.Join(",", nombres), "", ChannelLineGrouping.OneChannelForAllLines); // Guardar tarea persistente if (persistente) { tareas.Add(nombreTarea, digitalReadTask); } } // Leer los datos var reader = new DigitalSingleChannelReader(digitalReadTask.Stream); return reader.ReadSingleSampleMultiLine(); } catch (DaqException ex) { throw new DriverException(ex); } finally { if (!persistente && (digitalReadTask != null)) { digitalReadTask.Dispose(); digitalReadTask = null; } } }
/// <summary> /// Reads the specified line number /// </summary> /// <param name="linenum"></param> /// <returns></returns> public bool ReadLine(uint linenum) { if (_dev_type == Device_Types.Manual) { string linename = GetName(linenum); return _dic_values[linename]; } else if (_dev_type == Device_Types.NI_USB6008) { using (Task digitalReaderTask = 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); digitalReaderTask.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. DigitalSingleChannelReader reader = new DigitalSingleChannelReader(digitalReaderTask.Stream); return reader.ReadSingleSampleSingleLine(); } } else if (_dev_type == Device_Types.FT232H) { return _ft232hdio.ReadPin(_ftdi_bus, linenum); } Trace.TraceWarning("Unknown device"); return false; }
// 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; }
/// <summary> /// Reads the port /// </summary> /// <returns></returns> private byte rearPort() { Cursor.Current = Cursors.WaitCursor; byte data = 0; try { using (Task digitalReadTask = new Task()) { // Create an Digital Output channel and name it. digitalReadTask.DOChannels.CreateChannel(physicalChannelComboBox.Text, "port0", ChannelLineGrouping.OneChannelForAllLines); // Read digital port data. DigitalSingleChannelReader reader = new DigitalSingleChannelReader(digitalReadTask.Stream); data = reader.ReadSingleSamplePortByte(); } } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { Cursor.Current = Cursors.Default; } return data; }
private double ReadSingleDigital(NIDAQInputStream stream) { using (var t = new DAQTask()) { t.DIChannels.CreateChannel(stream.PhysicalName, "", ChannelLineGrouping.OneChannelForAllLines); var reader = new DigitalSingleChannelReader(t.Stream); return reader.ReadSingleSamplePortUInt32(); } }
bool ReadDigitalLine(string name) { Task digitalInputTask = ((Task)digitalInputTasks[name]); DigitalSingleChannelReader reader = new DigitalSingleChannelReader(digitalInputTask.Stream); bool digSample = reader.ReadSingleSampleSingleLine(); digitalInputTask.Control(TaskAction.Unreserve); return digSample; }
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); } } }