def clean(self): """ Clears the task and does whatever else we think is best practice. """ # cleanup debug("clear output task") _mx.DAQmxClearTask(self._handle)
def _start_analog_output(self): """ Creates for each physical channel a task and its virtual channel @returns: error code: ok = 0, error = -1 """ try: # create a dictionary with physical channel name as key and a pointer as value {'/Dev1/AO0': c_void_p(None), ... } taskhandles = dict([(name, daq.TaskHandle(0)) for name in self._ao_channels]) # if an analog task is already running, stop it first (safety if one of the created pointers already points somewhere) for channel in self._ao_channels: if taskhandles[channel].value is not None: # stop analog output task daq.DAQmxStopTask(taskhandles[channel]) # delete the configuration of the analog task daq.DAQmxClearTask(taskhandles[channel]) # set the task handle to None as a safety taskhandles[channel].value = None # create an individual task and a channel per analog output for n, channel in enumerate(self._ao_channels): daq.DAQmxCreateTask('', daq.byref(taskhandles[channel])) daq.DAQmxCreateAOVoltageChan(taskhandles[channel], channel, '', self._ao_voltage_ranges[n][0], self._ao_voltage_ranges[n][1], daq.DAQmx_Val_Volts, None) self.ao_taskhandles = taskhandles except: self.log.exception('Error starting analog output task.') return -1 return 0
def clean(self): """ Cleans up the task, frees memory etc... """ # cleanup debug("clear input task") _mx.DAQmxClearTask(self._handle)
def configure_pulser_task(self): """ Clear pulser task and set to current settings. @return: """ a_channels = [self.channel_map[k] for k in self.a_names] d_channels = [self.channel_map[k] for k in self.d_names] # clear task daq.DAQmxClearTask(self.pulser_task) # add channels if len(a_channels) > 0: daq.DAQmxCreateAOVoltageChan(self.pulser_task, ', '.join(a_channels), ', '.join(self.a_names), self.min_volts, self.max_volts, daq.DAQmx_Val_Volts, '') if len(d_channels) > 0: daq.DAQmxCreateDOChan(self.pulser_task, ', '.join(d_channels), ', '.join(self.d_names), daq.DAQmx_Val_ChanForAllLines) # set sampling frequency daq.DAQmxCfgSampClkTiming(self.pulser_task, 'OnboardClock', self.sample_rate, daq.DAQmx_Val_Rising, daq.DAQmx_Val_ContSamps, 10 * self.sample_rate)
def on_deactivate(self): self._stop_analog_output() try: daq.DAQmxClearTask(self._laser_ao_task) self._scanner_ao_task = None except: self.log.exception('Could not clear AO output task.') self._reset_hardware()
def clear(self): """ Stops and clears all NI DAQ tasks we have created """ for _, osa in self.osas.items(): task_handle = self.handles.get(osa) if task_handle is not None: try: PyDAQmx.DAQmxStopTask(task_handle) finally: PyDAQmx.DAQmxClearTask(task_handle) self.handles[osa] = None
def create_taskhandle(self): taskhandles = daq.TaskHandle() if taskhandles.value is not None: # stop analog output task daq.DAQmxStopTask(taskhandles) # delete the configuration of the analog task daq.DAQmxClearTask(taskhandles) # set the task handle to None as a safety taskhandles.value = None return taskhandles
def close_counter(self): """ Closes the counter and cleans up afterwards. @return int: error code (0:OK, -1:error) """ daq.DAQmxStopTask(self._counter_daq_task) daq.DAQmxClearTask(self._counter_daq_task) self._counter_daq_task = None return 0
def close_scanner_clock(self,power=0): """ Closes the clock and cleans up afterwards. @return int: error code (0:OK, -1:error) """ daq.DAQmxStopTask(self._scanner_clock_daq_task) daq.DAQmxClearTask(self._scanner_clock_daq_task) self._scanner_clock_daq_task = None return 0
def on_deactivate(self): #self.set_control_mode(ControlMode.POWER) self.cobolt.close() self._stop_analog_output() try: daq.DAQmxClearTask(self._laser_ao_task) self._scanner_ao_task = None except: self.log.exception('Could not clear AO output task.') self._reset_hardware()
def stop(self): # TODO: I would love to be able to stop a task and keep it in memory # without having to restart; however, this will require some thought as # to the optimal way to do this. For now, we just clear everything. # Configuration is generally fairly quick. if not self._configured: return log.debug('Stopping engine') for task in self._tasks.values(): mx.DAQmxClearTask(task) self._callbacks = {} self._configured = False
def close_ai_task(self): """ close the analog input task if there is one """ if self.analog_in_taskhandle is not None: task = self.analog_in_taskhandle try: daq.DAQmxStopTask(task) daq.DAQmxClearTask(task) self.analog_in_taskhandle = None except: self.log.exception('Could not close analog input task') else: pass
def close_do_task(self): """ close the digital output task if there is one """ if self.digital_out_taskhandle is not None: task = self.digital_out_taskhandle try: daq.DAQmxStopTask(task) daq.DAQmxClearTask(task) self.digital_out_taskhandle = None except: self.log.exception('Could not close digital output task') else: pass
def on_deactivate(self): """ Shut down the NI card. """ # clear the task try: self.close_do_task( ) # ends the digital output task in case one was still configured for channel in self._ao_channels: daq.DAQmxClearTask(self.ao_taskhandles[channel]) self.ao_taskhandles[ channel].value = None # reset it to nullpointer # print(self.ao_taskhandles) except: self.log.exception('Could not clear AO Out Task.')
def setVoltage_2(val): try: taskHandle = tp.TaskHandle() daq.DAQmxCreateTask("",taskHandle) # print "taskHandle Value", taskHandle.value daq.DAQmxCreateAOVoltageChan(taskHandle,"Dev1/ao1","",0.0,10.0,cnst.DAQmx_Val_Volts,"") daq.DAQmxStartTask(taskHandle) daq.DAQmxWriteAnalogScalarF64(taskHandle,1,5.0,tp.float64(val),None) if not taskHandle == 0 : # print "Stopping Tasks\n" daq.DAQmxStopTask(taskHandle) daq.DAQmxClearTask(taskHandle) return 0 except: errBuff=tp.create_string_buffer(b"",2048) daq.DAQmxGetExtendedErrorInfo(errBuff,2048) print(errBuff.value)
def getVoltage(): try: taskHandle = tp.TaskHandle() daq.DAQmxCreateTask("",taskHandle) # print "taskHandle Value", taskHandle.value val = tp.float64() daq.DAQmxCreateAIVoltageChan(taskHandle,"Dev1/ai0","",cnst.DAQmx_Val_RSE,0.0,10.0,cnst.DAQmx_Val_Volts,"") daq.DAQmxStartTask(taskHandle) daq.DAQmxReadAnalogScalarF64(taskHandle,5.0,daq.byref(val),None) if not taskHandle == 0 : # print "Stopping Tasks\n" daq.DAQmxStopTask(taskHandle) daq.DAQmxClearTask(taskHandle) return val.value except: errBuff=tp.create_string_buffer(b"",2048) daq.DAQmxGetExtendedErrorInfo(errBuff,2048) print(errBuff.value)
def close_pulser_task(self): """ Clear tasks. @return int: error code (0:OK, -1:error) """ retval = 0 try: # stop the task daq.DAQmxStopTask(self.pulser_task) except: self.log.exception('Error while closing NI pulser.') retval = -1 try: # clear the task daq.DAQmxClearTask(self.pulser_task) except: self.log.exception('Error while clearing NI pulser.') retval = -1 return retval
def channel_info(channels, channel_type): task = create_task() if channel_type in ('di', 'do', 'digital'): mx.DAQmxCreateDIChan(task, channels, '', mx.DAQmx_Val_ChanPerLine) elif channel_type == 'ao': mx.DAQmxCreateAOVoltageChan(task, channels, '', -10, 10, mx.DAQmx_Val_Volts, '') elif channel_type == 'ai': mx.DAQmxCreateAIVoltageChan(task, channels, '', mx.DAQmx_Val_Cfg_Default, -10, 10, mx.DAQmx_Val_Volts, '') channels = ctypes.create_string_buffer('', 4096) mx.DAQmxGetTaskChannels(task, channels, len(channels)) devices = ctypes.create_string_buffer('', 4096) mx.DAQmxGetTaskDevices(task, devices, len(devices)) mx.DAQmxClearTask(task) return { 'channels': [c.strip() for c in channels.value.split(',')], 'devices': [d.strip() for d in devices.value.split(',')], }
def _start_analog_output(self): try: if self._laser_ao_task is not None: daq.DAQmxStopTask(self._laser_ao_task) daq.DAQmxClearTask(self._laser_ao_task) self._laser_ao_task = None self._laser_ao_task = daq.TaskHandle() daq.DAQmxCreateTask('usbAO', daq.byref(self._laser_ao_task)) daq.DAQmxCreateAOVoltageChan(self._laser_ao_task, self._NI_analog_channel, 'Laser ao channel', self._NI_voltage_range[0], self._NI_voltage_range[1], daq.DAQmx_Val_Volts, '') except: self.log.exception('Error starting analog output task.') return -1 return 0
def clear(self): daq.DAQmxClearTask(self.taskHandle)
def clearTask(taskHandle): """ Clears a task from the card. """ daq.DAQmxStopTask(taskHandle) daq.DAQmxClearTask(taskHandle)
2) # Total number of sample to acquire for each channel pydaqmx.DAQmxCfgSampClkTiming(handle, source, rate, edge, sampMode, sampPerChan) #int32 __CFUNC DAQmxGetAIDevScalingCoeff(TaskHandle taskHandle, const char channel[], float64 *data, uInt32 arraySizeInElements); coeffArray = numpy.zeros(100, dtype=ctypes.c_double()) pydaqmx.DAQmxGetAIDevScalingCoeff(handle, '/Dev1/ai2', coeffArray.data, 100) print coeffArray # int32 DAQmxReadBinaryI16 (TaskHandle taskHandle, int32 numSampsPerChan, float64 timeout, bool32 fillMode, int16 readArray[], uInt32 arraySizeInSamps, int32 *sampsPerChanRead, bool32 *reserved); read = pydaqmx.int32( ) # Variable that will hold the value of how many samples we actually read (This gives us the freedom of putting in any sized dataBuffer and know exactly how much data is in it) nSampsPerChan = -1 # -1 in finite mode means wait until all samples are collected and read them timeout = -1 # -1 means wait indefinitely to read the samples fillMode = pydaqmx.DAQmx_Val_GroupByChannel # Controls organization of output. Specifies if you want to prioritize by lowest channel or lowest sample (if you have mutiple channels each getting multiple samples) dataBuffer = numpy.zeros(100, dtype=pydaqmx.int16()) dataBufferFloat = numpy.zeros(100, dtype=pydaqmx.float64()) arrSize = pydaqmx.uInt32(len(dataBuffer)) # sampsPerChanRead = ctypes.byref(read) # The number of samples we actually read #pydaqmx.DAQmxStartTask(handle) #pydaqmx.DAQmxReadBinaryI16(handle, nSampsPerChan, timeout, fillMode, dataBuffer, arrSize, sampsPerChanRead, None) # This is the line when you actually read the voltage pydaqmx.DAQmxReadBinaryI16( handle, nSampsPerChan, timeout, fillMode, dataBuffer, arrSize, ctypes.byref(read), None) # This is the line when you actually read the voltage #pydaqmx.DAQmxReadAnalogF64(handle, nSampsPerChan, timeout, fillMode, dataBufferFloat, arrSize, ctypes.byref(read),None) # This is the line when you actually read the voltage pydaqmx.DAQmxStopTask(handle) pydaqmx.DAQmxClearTask(handle) print dataBuffer print dataBufferFloat
task_handle = daq.TaskHandle() samps = 3000 test_array = np.full((samps, ), -1, dtype=np.uint32) daq.DAQmxCreateTask('count_test', daq.byref(task_handle)) daq.DAQmxCreateCICountEdgesChan(task_handle, '/Dev1/Ctr0', 'Counter test', daq.DAQmx_Val_Rising, 0, daq.DAQmx_Val_CountUp) daq.DAQmxCfgSampClkTiming(task_handle, '100kHzTimebase', 100000, daq.DAQmx_Val_Rising, daq.DAQmx_Val_FiniteSamps, samps) daq.DAQmxSetCICountEdgesTerm(task_handle, '/Dev1/Ctr0', '/Dev1/PFI0') done = daq.bool32() daq.DAQmxStartTask(task_handle) daq.DAQmxGetTaskComplete(task_handle, done) n_read_samples = daq.int32() daq.DAQmxReadCounterU32(task_handle, samps, 500., test_array, len(test_array), daq.byref(n_read_samples), None) done = daq.bool32() daq.DAQmxGetTaskComplete(task_handle, done) daq.DAQmxStopTask(task_handle) daq.DAQmxClearTask(task_handle) print(test_array[-1] * 100000 / samps)
def start(self, test=False, **kwargs): """ 1. Creates a task using settings. 2. Starts the task. You need to call wait_and_clean() after you start() kwargs are sent to self() to set parameters. """ self(**kwargs) # make sure everything that should be a list is a list if not isinstance(self["ao_channels"], Iterable): self["ao_channels"] = [self["ao_channels"]] # if the first element of the waveform is not an array if len(_n.shape(self["ao_waveforms"][0])) < 1: self["ao_waveforms"] = [self["ao_waveforms"]] # create the task object. This doesn't return an object, because # National Instruments. Instead, we have this handle, and we need # to be careful about clearing the thing attached to the handle. debug("output task handle") _mx.DAQmxClearTask(self._handle) _mx.DAQmxCreateTask(self["ao_task_name"], _mx.byref(self._handle)) # create all the output channels debug("output channels") # this is an array of output data arrays, grouped by channel samples = 0 data = _n.array([]) # loop over all the channels for n in range(len(self["ao_channels"])): # get the channel-specific attributes name = self["ao_channels"][n] nickname = name.replace("/", "") debug(name) if isinstance(self["ao_min"], Iterable): ao_min = self["ao_min"][n] else: ao_min = self["ao_min"] if isinstance(self["ao_max"], Iterable): ao_max = self["ao_max"][n] else: ao_max = self["ao_max"] if isinstance(self["ao_units"], Iterable): ao_units = self["ao_units"][n] else: ao_units = self["ao_units"] waveform = self["ao_waveforms"][n] # add an output channel _mx.DAQmxCreateAOVoltageChan(self._handle, name, nickname, ao_min, ao_max, ao_units, "") # add the corresponding output wave to the master data array debug("data", data, "waveform", waveform) data = _n.concatenate([data, waveform]) # Set the samples number to the biggest output array size samples = max(len(self["ao_waveforms"][n]), samples) # Configure the clock debug("output clock") # make sure we don't exceed the max #ao_max_rate = _mx.float64() #_mx.DAQmxGetSampClkMaxRate(self._handle, _mx.byref(ao_max_rate)) #if self['ao_rate'] > ao_max_rate.value: # print "ERROR: ao_rate is too high! Current max = "+str(ao_max_rate.value) # self.clean() # return False _mx.DAQmxCfgSampClkTiming(self._handle, self["ao_clock_source"], self["ao_rate"], self["ao_clock_edge"], self["ao_mode"], samples) # if we're supposed to, export a signal if not self['ao_export_terminal'] == None: _mx.DAQmxExportSignal(self._handle, self['ao_export_signal'], self['ao_export_terminal']) # update to the actual ao_rate (may be different than what was set) ao_rate = _mx.float64() _mx.DAQmxGetSampClkRate(self._handle, _mx.byref(ao_rate)) debug("output actual ao_rate =", ao_rate.value) self(ao_rate=ao_rate.value) # Configure the trigger debug("output trigger") _mx.DAQmxCfgDigEdgeStartTrig(self._handle, self["ao_trigger_source"], self["ao_trigger_slope"]) # Set the post-trigger delay try: n = self["ao_delay"] * 10e6 if n < 2: n = 2 _mx.DAQmxSetStartTrigDelayUnits(self._handle, _mx.DAQmx_Val_Ticks) _mx.DAQmxSetStartTrigDelay(self._handle, n) except: _traceback.print_exc() # write the data to the analog outputs (arm it) debug("output write", len(data)) write_success = _mx.int32() _mx.DAQmxWriteAnalogF64( self._handle, samples, False, self["ao_timeout"], _mx. DAQmx_Val_GroupByChannel, # Type of grouping of data in the array (for interleaved use DAQmx_Val_GroupByScanNumber) data, # Array of data to output _mx.byref(write_success), # Output the number of successful write None) # Reserved input (just put in None...) debug("success:", samples, write_success) if test: self.clean() else: # Start the task!! debug("output start") try: _mx.DAQmxStartTask(self._handle) except: _traceback.print_exc() return True
def start(self, test=False, **kwargs): """ 1. Creates a task using settings. 2. Starts the task. 3. Fetches data. You need to call read_and_clean() after start(). kwargs are sent to self() to set parameters. """ # update any last-minute settings self(**kwargs) debug(self.settings) # create the task object. This doesn't return an object, because # National Instruments. Instead, we have this handle, and we need # to be careful about clearing the thing attached to the handle. debug("input task handle") _mx.DAQmxClearTask(self._handle) _mx.DAQmxCreateTask(self["ai_task_name"], _mx.byref(self._handle)) # Loop over all the input channel names and create a channel for each debug("input channels") for n in range(len(self["ai_channels"])): # get the channel-specific attributes name = self["ai_channels"][n] nickname = name.replace("/", "") debug(name) if isinstance(self["ai_terminal_config"], Iterable): ai_terminal_config = self["ai_terminal_config"][n] else: ai_terminal_config = self["ai_terminal_config"] if isinstance(self["ai_min"], Iterable): ai_min = self["ai_min"][n] else: ai_min = self["ai_min"] if isinstance(self["ai_max"], Iterable): ai_max = self["ai_max"][n] else: ai_max = self["ai_max"] if isinstance(self["ai_units"], Iterable): ai_units = self["ai_units"][n] else: ai_units = self["ai_units"] # add an input channel debug(name) _mx.DAQmxCreateAIVoltageChan(self._handle, name, nickname, ai_terminal_config, ai_min, ai_max, ai_units, "") # set the input coupling (optional) if not self["ai_input_couplings"] == None: ai_input_coupling = self["ai_input_couplings"][n] if ai_input_coupling == "AC": _mx.DAQmxSetAICoupling(self._handle, name, _mx.DAQmx_Val_AC) if ai_input_coupling == "DC": _mx.DAQmxSetAICoupling(self._handle, name, _mx.DAQmx_Val_DC) if ai_input_coupling == "GND": _mx.DAQmxSetAICoupling(self._handle, name, _mx.DAQmx_Val_GND) # Configure the clock debug("input clock") # make sure we don't exceed the max ai_max_rate = _mx.float64() _mx.DAQmxGetSampClkMaxRate(self._handle, _mx.byref(ai_max_rate)) if self['ai_rate'] > ai_max_rate.value: print("ERROR: ai_rate is too high! Current max = " + str(ai_max_rate.value)) self.clean() return False _mx.DAQmxCfgSampClkTiming(self._handle, self["ai_clock_source"], self["ai_rate"], self["ai_clock_edge"], self["ai_mode"], self["ai_samples"]) # get the actual ai_rate ai_rate = _mx.float64() _mx.DAQmxGetSampClkRate(self._handle, _mx.byref(ai_rate)) debug("input actual ai_rate =", ai_rate.value) self(ai_rate=ai_rate.value) # Configure the trigger debug("input trigger") _mx.DAQmxCfgDigEdgeStartTrig(self._handle, self.settings["ai_trigger_source"], self.settings["ai_trigger_slope"]) # Set the post-trigger delay try: n = self["ai_delay"] * 10e6 if n < 2: n = 2 _mx.DAQmxSetStartTrigDelayUnits(self._handle, _mx.DAQmx_Val_Ticks) _mx.DAQmxSetStartTrigDelay(self._handle, n) except: _traceback.print_exc() # in test mode, just check that it doesn't fail and clean up. if test: self.clean() # otherwise, start the show! else: debug("input start") try: _mx.DAQmxStartTask(self._handle) except: _traceback.print_exc() return True
def clearTask(self, task): if task: pydaqmx.DAQmxStopTask(task) pydaqmx.DAQmxClearTask(task) return False # So that we can always call stopPiezoScan without an error
def reset(self): status = mx.DAQmxStopTask(self.task_handle) status = mx.DAQmxClearTask(self.task_handle) self.create_task() self.start()
def clear_task(self): """Stops and Clears the DAQ task handle""" if self.task_handle: self.stop_task() pydaq.DAQmxClearTask(self.task_handle)