def __init__(self, device, adqTime, adqFreq, list_channels, rang_channels, mode='FiniteSamps', trigger=None, terminalConfig='diff'): """This will configure the DAQ and Task for the specified configuration""" self.device = device self.adqTime = adqTime # In seconds self.adqFreq = adqFreq self.list_channels = list_channels self.rang_channels = rang_channels self.mode = mode self.N_samples = int(adqTime * adqFreq) self.N_channels = len(list_channels) if terminalConfig is 'diff': self.terminalConfig = DAQmx_Val_Diff elif terminalConfig is 'SE': self.terminalConfig = DAQmx_Val_RSE else: raise Error( 'Terminal configuration "{}" not known'.format(terminalConfig)) print('I will adquire {} samples for each {} channels'.format( self.N_samples, self.N_channels)) # DAQmx Configure Code # We create a Task instance self.ai = Task() # Prepare the type of variable that it returns using the library ctypes that work with C-functions self.read = int32() # The vector data will contain the output of the DAQ card in a single vector with the data from different channels # in a single 1-D vector with the data concatenated self.data = np.zeros((self.N_samples * self.N_channels, ), dtype=np.float64) #self.ai = Task() # This prepares the string that is needed for the ``CreateAIVoltageChan`` depending on the number of channels to # read for channel, Vrange in zip(self.list_channels, self.rang_channels): str_channels = r"{}/ai{:d}".format(self.device, channel) #print(r"{}/ai{:d}".format(self.device,channel) ) self.ai.CreateAIVoltageChan(str_channels, "", self.terminalConfig, -1.0 * Vrange, Vrange, DAQmx_Val_Volts, None) if mode is 'FiniteSamps': self.ai.CfgSampClkTiming("", self.adqFreq, DAQmx_Val_Rising, DAQmx_Val_FiniteSamps, self.N_samples) elif mode is 'ContSamps': self.ai.CfgSampClkTiming("", self.adqFreq, DAQmx_Val_Rising, DAQmx_Val_ContSamps, self.N_samples) else: raise Error('Mode not known') if trigger is None: pass else: self.ai.CfgAnlgEdgeStartTrig( r"{}/ai{:d}".format(self.device, trigger[0]), DAQmx_Val_RisingSlope, trigger[1])
def __init__(self, config, consumer): Task.__init__(self) self.config = config self.consumer = consumer self.sample_buffer_size = (self.config.sampling_rate + 1) * self.config.number_of_ports * 2 self.samples_read = int32() self.remainder = [] # create voltage channels for i in xrange(0, 2 * self.config.number_of_ports, 2): self.CreateAIVoltageChan('{}/ai{}'.format(config.device_id, config.channel_map[i]), '', DAQmx_Val_Diff, -config.v_range, config.v_range, DAQmx_Val_Volts, None) self.CreateAIVoltageChan('{}/ai{}'.format(config.device_id, config.channel_map[i + 1]), '', DAQmx_Val_Diff, -config.dv_range, config.dv_range, DAQmx_Val_Volts, None) # configure sampling rate self.CfgSampClkTiming('', self.config.sampling_rate, DAQmx_Val_Rising, DAQmx_Val_ContSamps, self.config.sampling_rate) # register callbacks self.AutoRegisterEveryNSamplesEvent(DAQmx_Val_Acquired_Into_Buffer, self.config.sampling_rate // 2, 0) self.AutoRegisterDoneEvent(0)
def __init__(self, buff, chan, nps, start_acq, i_kspace, up_sigs): Task.__init__(self) self.nx = nps[0] self.p_steps = nps[1] self.s_steps = nps[2] # total number of acquisition needed self.tot = (nps[2] - 1) * (nps[1] - 1) * (nps[0] - 1) # index defining the beginning of the signal in the acquisition matrix self.s_acq = start_acq # Matrix to define correspondancy between index and k_space lines self.i_k = i_kspace # Total length of the matrix containing the signal self.chan = chan self.up_graph = up_sigs[0] self.up_graph2d = up_sigs[1] self.buff = buff # Precalculation of the matrices needed for quadratic acq self.q_cos = cos(2 * pi * arange(chan) / 4) self.q_sin = sin(2 * pi * arange(chan) / 4) # This is for 2 channels self.read = zeros([2 * self.buff], dtype=float64) # Chan is twice smaller in fft because of quadratic acquisition self.data_k = zeros([chan, nps[1], nps[2], nps[0]], dtype=complex) self.data_fft = zeros((chan / 2, nps[1], nps[2]), dtype=complex) # self.data_fft = zeros((chan / 2, p_steps, nx + 1), dtype=complex) self.CreateAIVoltageChan("Dev1/ai0:1", "", Cfg_Deft, -1, 1, Volts, None) ln = b"/Dev2/ao/SampleClock" self.CfgSampClkTiming(ln, 250000, Val_Ris, Val_ContSamps, buff)
def program_manual(self, front_panel_values): """ Update the static output chanels with new values. This method transitions the device into manual mode (if it is still in rerun mode) and updates the output state of all channels Parameters ---------- front_panel_values : dict {connection name : new state, ...} Containing the connection name and corresponding new output state """ if self.wait_for_rerun: print("dont wait for rerun any more. setup static") self.ao_task.StopTask() self.ao_task.ClearTask() self.do_task.StopTask() self.do_task.ClearTask() self.ao_task = Task() self.do_task = Task() self.setup_static_channels() self.wait_for_rerun = False for i in range(self.NUM_AO): self.ao_data[i] = front_panel_values['ao%d' % i] self.ao_task.WriteAnalogF64(1, True, 1, DAQmx_Val_GroupByChannel, self.ao_data, byref(self.ao_read), None) for i in range(self.NUM_DO): self.do_data[i] = front_panel_values['do_%d' % i] self.do_task.WriteDigitalLines(1, True, 1, DAQmx_Val_GroupByChannel, self.do_data, byref(self.do_read), None)
def __init__(self, targetFileName=None, saveRate=125, Nds=2, startOnTrig=None): Task.__init__(self) self.saveRate = saveRate self.Nds = Nds self.data = np.zeros(saveRate * Nds * 4) self.sampRate = saveRate * Nds self.a = [] self.CreateAIVoltageChan("Dev12/ai0:3", "", DAQmx_Val_RSE, -10.0, 10.0, DAQmx_Val_Volts, None) self.CfgSampClkTiming("", self.sampRate, DAQmx_Val_Rising, DAQmx_Val_ContSamps, self.sampRate) self.AutoRegisterEveryNSamplesEvent(DAQmx_Val_Acquired_Into_Buffer, self.sampRate, 0) self.AutoRegisterDoneEvent(0) self.t0 = None if startOnTrig is not None: self.CfgDigEdgeStartTrig(startOnTrig, DAQmx_Val_Rising) if targetFileName is not None: self.saveFile = open(targetFileName, 'wb') else: self.saveFile = None
def send_pulse(self, settings, B_zeros, B_finite): ### TODO: Reweite this using the _local_data """"Create a PyDAQmx packege task instance to create a channel to the device and then activate the pins as specified in the session. Use the boolans B_zeros or B_finite to refer to the turned-off default pin setting and/or to turn them off after the time specified in the session """ task = PyDAQmx_Task() self.__open_channel(task, settings) task.StartTask() if B_zeros: pin_vals = ZEROS else: pin_vals = [int(settings['B_pin_'+k]) for k in hardware.range_NI_pins] self.__write_to_pins(task, pin_vals) if B_finite: duration = cs.MILLI * float(settings['R_pulse_time']) time.sleep(duration) self.__write_to_pins(task, ZEROS) task.StopTask() device = settings['N_device'] port = settings['N_port'] message_scheme = "* (DriverNI_pulse) send_pulse: \n | Pulse | Device | Port | \n | {0} | {1} | {2} | " message = message_scheme.format(str(pin_vals), device, port) print message return message
def __init__(self): # Inicilizo la comunicación con la placa DAQ, específicamente con el canal #de output para controlar la corriente del electroimán self.task = Task() self.task.CreateAOVoltageChan("Dev1/ao0", "", -10.0, 10.0, PyDAQmx.DAQmx_Val_Volts, None) self.vi = 0
def supported_AI_ranges_for_non_differential_input(device_name, AI_ranges): """Empirically determine the analog input voltage ranges for non-differential inputs. Tries AI ranges to see which are actually allowed for non-differential input, since the largest range may only be available for differential input. Args: device_name (str): NI-MAX device name AI_ranges (list): list of `[Vmin, Vmax]` pairs to check compatibility. Returns: list: List of lists with the supported voltage ranges. """ chan = device_name + '/ai0' supported_ranges = [] for Vmin, Vmax in AI_ranges: try: task = Task() task.CreateAIVoltageChan( chan, "", c.DAQmx_Val_RSE, Vmin, Vmax, c.DAQmx_Val_Volts, None ) task.StartTask() except PyDAQmx.DAQmxFunctions.InvalidAttributeValueError as e: if 'DAQmx_AI_Min' in e.message or 'DAQmx_AI_Max' in e.message: # Not supported for non-differential input: continue raise finally: task.ClearTask() supported_ranges.append([Vmin, Vmax]) return supported_ranges
def __init__(self, MAX_name, message_queue): """ Initialise the driver and tasks using the given MAX name and message queue to communicate with this class Parameters ---------- MAX_name : str the National Instrument MAX name used to identify the hardware card message_queue : JoinableQueue a message queue used to send instructions to this class """ print("initialize device") self.NUM_DO = 32 self.MAX_name = MAX_name #Create DO Task self.do_task = Task() self.do_read = int32() self.do_data = np.zeros((self.NUM_DO, ), dtype=np.uint8) self.setup_static_channels() #DAQmx Start Code self.do_task.StartTask() self.wait_for_rerun = False self.running = True self.read_Thread = Thread(target=self.read_fun, args=(message_queue, ))
def __init__(self, device = 'Dev1', port = 0, timeout = 10.0, initial_state = 'high', ): Task.__init__(self) self.timeout = timeout lines = GetDOLines(device) lines = [l for l in lines if 'port' + str(port) in l] self.deviceLines = len(lines) #create dev str for various lines devStr = str(device) + "/port" + str(port) + "/line0:" + str(self.deviceLines-1) #create initial state of output lines if initial_state.lower() == 'low': self.lastOut = np.zeros(self.deviceLines, dtype = np.uint8) #keep track of last output #should be gotten from initial state instead elif initial_state.lower() == 'high': self.lastOut = np.ones(self.deviceLines,dtype=np.uint8) elif type(initial_state) == np.ndarray: self.lastOut = initial_state else: raise TypeError("Initial state not understood. Try 'high' or 'low'") #create IO channel self.CreateDOChan(devStr,"",DAQmx_Val_ChanForAllLines) self.AutoRegisterDoneEvent(0)
def stream_init(self, playback = False): """ Re-implemented from RecorderParent. """ if self.audio_stream == None: try: self.audio_stream = Task() self.audio_stream.stream_audio_callback = self.stream_audio_callback self.audio_stream.CreateAIVoltageChan(self.set_channels(),"", pdaq.DAQmx_Val_RSE,-10.0,10.0, pdaq.DAQmx_Val_Volts,None) self.audio_stream.CfgSampClkTiming("",self.rate, pdaq.DAQmx_Val_Rising,pdaq.DAQmx_Val_ContSamps, self.chunk_size) self.audio_stream.AutoRegisterEveryNSamplesEvent(pdaq.DAQmx_Val_Acquired_Into_Buffer, 1000,0,name = 'stream_audio_callback') self.stream_start() return True except: t,v,tb = sys.exc_info() print(t) print(v) print(traceback.format_tb(tb)) self.audio_stream = None return False
def __init__(self, device='Dev1', channel=0, voltageRange=(-10.0, 10.0), sampRate=1000.0, bufferSize=1000, accumulate=False): # construct task Task.__init__(self) # set up task properties self.channel = channel self.voltageRange = voltageRange self.sampRate = sampRate self.bufferSize = bufferSize self.timeout = 10.0 self.data = np.zeros(self.bufferSize, dtype=np.float64) self.accumulate = accumulate self.dataArray = [] self.bufferCount = 0 self.CreateAIVoltageChan(device + '/ai' + str(channel), '', DAQmx_Val_RSE, voltageRange[0], voltageRange[1], DAQmx_Val_Volts, None) self.CfgSampClkTiming('', sampRate, DAQmx_Val_Rising, DAQmx_Val_ContSamps, bufferSize) # set up data buffer callback self.AutoRegisterEveryNSamplesEvent(DAQmx_Val_Acquired_Into_Buffer, self.bufferSize, 0) # set up task complete callback (unused since this class takes continuous samples) self.AutoRegisterDoneEvent(0)
def __init__(self, device='Dev1', port=1, initialState='low'): # construct task Task.__init__(self) # set up task properties self.port = port lines = GetDOLines(device) lines = [l for l in lines if 'port' + str(port) in l] self.deviceLines = len(lines) self.timeout = 10.0 #create initial state of output lines if initialState.lower() == 'low': self.lastOut = np.zeros(self.deviceLines, dtype=np.uint8) elif initialState.lower() == 'high': self.lastOut = np.ones(self.deviceLines, dtype=np.uint8) elif type(initial_state) == np.ndarray: self.lastOut = initialState else: raise TypeError( "Initial state not understood. Try 'high' or 'low'") devStr = str(device) + "/port" + str(port) + "/line0:" + str( self.deviceLines - 1) self.CreateDOChan(devStr, "", DAQmx_Val_ChanForAllLines) self.AutoRegisterDoneEvent(0)
def __init__(self): Task.__init__(self) self.data = np.zeros(1000) self.a = [] self.CreateAIVoltageChan("cDAQ1Mod3/ai0","",DAQmx_Val_Cfg_Default,-10.0,10.0,DAQmx_Val_Volts,None) self.CfgSampClkTiming("",10000.0,DAQmx_Val_Rising,DAQmx_Val_ContSamps,1000) self.AutoRegisterEveryNSamplesEvent(DAQmx_Val_Acquired_Into_Buffer,1000,0) self.AutoRegisterDoneEvent(0)
def __init__(self): Task.__init__(self) self.data = np.zeros(1000) self.a = [] self.CreateAIVoltageChan("Dev1/ai0","PMT1_signal",PyDAQmx.DAQmx_Val_Cfg_Default,0,10.0,PyDAQmx.DAQmx_Val_Volts,None) self.CfgSampClkTiming(None,1000.0,PyDAQmx.DAQmx_Val_Rising,PyDAQmx.DAQmx_Val_ContSamps,1000) self.AutoRegisterEveryNSamplesEvent(PyDAQmx.DAQmx_Val_Acquired_Into_Buffer,1000,0) self.AutoRegisterDoneEvent(0)
def close(self): self.initialized = False ''' if self.startTriggerSyncCard != '': DAQmxDisconnectTerms(self._startTriggerSource, self.startTriggerSyncCard) ''' self.status = self.taskRef.ClearTask() self.taskRef = Task()
def connect(self, line="/Dev1/port0/line2"): """ Connect the laser to the software through the NI card through digital lines interface. """ self.task = Task() self.task.CreateDOChan(line, "", PyDAQmx.DAQmx_Val_ChanForAllLines) self.task.StartTask()
def __init__(self): Task.__init__(self) self.data = zeros(1000) self.a = [] self.CreateAIVoltageChan("Dev1/ai0","",DAQmx_Val_RSE,-10.0,10.0,DAQmx_Val_Volts,None) self.CfgSampClkTiming("",10000.0,DAQmx_Val_Rising,DAQmx_Val_ContSamps,1000) self.AutoRegisterEveryNSamplesEvent(DAQmx_Val_Acquired_Into_Buffer,1000,0) self.AutoRegisterDoneEvent(0)
def __init__(self, device, channels, rate=3e4): Task.__init__(self) self._rate = rate self._device = device self._ao_channels = channels self.configure()
def __init__(self, device, channels, time_constant=0.05, rate=1e5): Task.__init__(self) self._rate = rate self._time_constant = time_constant self._device = device self._ai_channels = channels self.configure()
def __init__(self): Task.__init__(self) self.data = np.zeros(buffer_size) # dummy array to write data from current buffer self.n = 0 # counting sampling events self.a = [] # list to write all acquired data into self.CreateAIVoltageChan(b"/%s/ai13"%device,"PMT1_signal",PyDAQmx.DAQmx_Val_Cfg_Default,0,10.0,PyDAQmx.DAQmx_Val_Volts,None) # Create Voltage input channel to acquire between 0 and 10 Volts self.CfgSampClkTiming(None,sampling_freq,PyDAQmx.DAQmx_Val_Rising,PyDAQmx.DAQmx_Val_ContSamps,buffer_size) # Acquire samples continuously with a sampling frequency of 10000 Hz on the rising edge of the sampling of the onboard clock, buffer size of 1000 self.AutoRegisterEveryNSamplesEvent(PyDAQmx.DAQmx_Val_Acquired_Into_Buffer,buffer_size,0) # Auto register the callback functions self.AutoRegisterDoneEvent(0) # Auto register the callback functions
def __init__(self, device, channels, rate=1e5): Task.__init__(self) self._rate = rate self._samps_per_chan_to_acquire = 2 self._device = device self._ao_channels = channels self.configure()
def get_min_semiperiod_measurement(device_name): """Determines the minimum semi-period measurement time supported by the device. Depending on the timebase used, counter inputs can measure time intervals of various ranges. As a default, we pick a largish range - the one with the fastest timebase still capable of measuring 100 seconds, or the largest time interval if it is less than 100 seconds, and we save the smallest interval measurable with this timebase. Then labscript can ensure it doesn't make wait monitor pulses shorter than this. This should be a sensible default behaviour, though if the user has experiments considerably shorter or longer than 100 seconds, such that they want to use a different timebase, they may pass the min_semiperiod_measurement keyword argument into the DAQmx class, to tell labscript to make pulses some other duration compatible with the maximum wait time in their experiment. However, since there are software delays in timeouts of waits during a shot, any timed-out waits necessarily will last software timescales of up to ~100ms on a slow computer, preventing one from using very fast timebases with low-resolution counters if there is any possibility of timing out. For now (in the wait monitor worker class) we pessimistically add one second to the expected longest measurement to account for software delays. These decisions can be revisited if there is a need, do not hesitate to file an issue on bitbucket regarding this if it affects you. Args: device_name (str): NI-MAX device name Returns: float: Minimum measurement time. """ CI_chans = DAQmxGetDevCIPhysicalChans(device_name) CI_chan = device_name + '/' + CI_chans[0] # Make a task with a semiperiod measurement task = Task() task.CreateCISemiPeriodChan(CI_chan, '', 1e-100, 1e100, c.DAQmx_Val_Seconds, "") try: task.StartTask() except PyDAQmx.DAQmxFunctions.CtrMinMaxError as e: # Parse the error to extract the allowed values: CI_ranges = [] DT_MIN_PREFIX = "Value Must Be Greater Than:" DT_MAX_PREFIX = "Value Must Be Less Than:" error_lines = e.message.splitlines() for line in error_lines: if DT_MIN_PREFIX in line: dt_min = float(line.replace(DT_MIN_PREFIX, '')) if DT_MAX_PREFIX in line: dt_max = float(line.replace(DT_MAX_PREFIX, '')) CI_ranges.append([dt_min, dt_max]) else: raise AssertionError("Can't figure out counter input ranges") finally: task.ClearTask() # Pick out the value we want. Either dtmin when dtmax is over 100, or the largest # dtmin if there is no dtmax over 100: for dtmin, dtmax in sorted(CI_ranges): if dtmax > 100: return dtmin return dtmin
def connect_di_port(devport): ''' Initialize task for reading from digital input port in devport = Device/port e.g. Dev1/port0 out task = Task handle ''' task = Task() task.CreateDIChan(devport, '', DAQmx_Val_ChanForAllLines) task.StartTask() return task
def connect_do_port(devport): ''' Initialize task for writing to digital output port in Device/port e.g. Dev1/port0 out Task handle ''' task = Task() task.CreateDOChan(devport, '', DAQmx_Val_ChanForAllLines) task.StartTask() return task
def AI_start_delay(device_name): if 'PFI0' not in DAQmxGetDevTerminals(device_name): return None task = Task() clock_terminal = '/' + device_name + '/PFI0' rate = DAQmxGetDevAIMaxSingleChanRate(device_name) Vmin, Vmax = DAQmxGetDevAIVoltageRngs(device_name)[0:2] num_samples = 1000 chan = device_name + '/ai0' task.CreateAIVoltageChan(chan, "", c.DAQmx_Val_RSE, Vmin, Vmax, c.DAQmx_Val_Volts, None) task.CfgSampClkTiming("", rate, c.DAQmx_Val_Rising, c.DAQmx_Val_ContSamps, num_samples) task.CfgDigEdgeStartTrig(clock_terminal, c.DAQmx_Val_Rising) start_trig_delay = float64() delay_from_sample_clock = float64() sample_timebase_rate = float64() task.GetStartTrigDelay(start_trig_delay) task.GetDelayFromSampClkDelay(delay_from_sample_clock) task.GetSampClkTimebaseRate(sample_timebase_rate) task.ClearTask() total_delay_in_ticks = start_trig_delay.value + delay_from_sample_clock.value total_delay_in_seconds = total_delay_in_ticks / sample_timebase_rate.value return total_delay_in_seconds
def connect_di_line(devportline): ''' Initialize task for reading from digital input lines in devportline = Device/port/lines e.g. Dev1/port0/line0:3 also single line supported e.g. Dev1/port0/line1 out task = Task handle ''' task = Task() task.CreateDIChan(devportline, '', DAQmx_Val_ChanPerLine) task.StartTask() return task
def connect_do_line(devportline): ''' Initialize task for writing to digital output lines in Device/port/lines e.g. Dev1/port0/line0:3 also single line supported e.g. Dev1/port0/line1 out Task handle ''' task = Task() task.CreateDOChan(devportline, '', DAQmx_Val_ChanPerLine) task.StartTask() return task
def connect_analog_write_io_port(devport): ''' Initialize task for writing Voltage data to analog output port in devport = Device/port e.g. Dev2/ao0 out task = Task handle ''' max_num_samples = 1 task = Task() task.CreateAOVoltageChan(devport, '', -10.0, 10.0, DAQmx_Val_Volts, None) task.StartTask() return task
def __init__(self): self.counter = '' self.Task = Task() self.initialized = False self.initialDelay = 0 self.dutyCycle = 0.50 self.frequency = 1e6 self._numberOfPulses = 0 self.status = 0 self._startTriggerSource = '' self.triggerType = TriggerType.Software self.timeout = -1
def AI_start_delay(device_name): """Empirically determines the analog inputs' start delay. Args: device_name (str): NI-MAX device name Returns: float: Analog input start delay in seconds. `None` if analog inputs not supported. """ if 'PFI0' not in DAQmxGetDevTerminals(device_name): return None task = Task() clock_terminal = '/' + device_name + '/PFI0' rate = DAQmxGetDevAIMaxSingleChanRate(device_name) Vmin, Vmax = DAQmxGetDevAIVoltageRngs(device_name)[0:2] num_samples = 1000 chan = device_name + '/ai0' supp_types = DAQmxGetPhysicalChanAITermCfgs(chan) if supp_types & c.DAQmx_Val_Bit_TermCfg_RSE: input_type = c.DAQmx_Val_RSE elif supp_types & c.DAQmx_Val_Bit_TermCfg_Diff: input_type = c.DAQmx_Val_Diff elif supp_types & c.DAQmx_Val_Bit_TermCfg_PseudoDIFF: input_type = c.DAQmx_Val_PseudoDiff task.CreateAIVoltageChan( chan, "", input_type, Vmin, Vmax, c.DAQmx_Val_Volts, None ) task.CfgSampClkTiming( "", rate, c.DAQmx_Val_Rising, c.DAQmx_Val_ContSamps, num_samples ) task.CfgDigEdgeStartTrig(clock_terminal, c.DAQmx_Val_Rising) start_trig_delay = float64() delay_from_sample_clock = float64() sample_timebase_rate = float64() try: task.GetStartTrigDelay(start_trig_delay) except PyDAQmx.DAQmxFunctions.AttributeNotSupportedInTaskContextError: # device does not have a Start Trigger Delay property # is likely a dynamic signal acquisition device with filter # delays instead. start_trig_delay.value = 0 try: task.GetDelayFromSampClkDelay(delay_from_sample_clock) except PyDAQmx.DAQmxFunctions.AttributeNotSupportedInTaskContextError: # seems simultaneous sampling devices do not have this property, # so assume it is zero delay_from_sample_clock.value = 0 task.GetSampClkTimebaseRate(sample_timebase_rate) task.ClearTask() total_delay_in_ticks = start_trig_delay.value + delay_from_sample_clock.value total_delay_in_seconds = total_delay_in_ticks / sample_timebase_rate.value return total_delay_in_seconds
def transition_to_manual(self, more_reps, abort): """ Stop buffered mode """ if abort: self.wait_for_rerun = False self.do_task.ClearTask() self.do_task = Task() self.setup_static_channels() self.do_task.StartTask() else: self.wait_for_rerun = True
def __init__(self, channelName='Dev2/ai0:23', dataLen = 40, frequency = 2000, nChannels = 24): Task.__init__(self) self.dataLen = dataLen self.frequency = frequency self.nChannels = nChannels self._data = np.zeros( (self.nChannels, self.dataLen) ) self.read = int32() self.CreateAIVoltageChan(channelName, "", DAQmx_Val_RSE, -10.0, 10.0, DAQmx_Val_Volts, None) self.CfgSampClkTiming("", self.frequency, DAQmx_Val_Rising, DAQmx_Val_ContSamps, self.dataLen) self.AutoRegisterEveryNSamplesEvent(DAQmx_Val_Acquired_Into_Buffer, self.dataLen, 0) self.AutoRegisterDoneEvent(0) self._data_lock = threading.Lock() self._newdata_event = threading.Event()
def __init__(self, device, channels, time_constant=0.05, rate=1e5): Task.__init__(self) self._rate = rate self._time_constant = time_constant self._device = device self._ai_channels = channels for ch, value in self._ai_channels.items(): chan = self._device + '/ai' + str(ch) self.create_ai_chan(chan, value['range'], value['mode']) self.configure()
def __init__(self, device = 'Dev1', channels = [0]): Task.__init__(self) #create dev str for various channels devStr = "" for channel in channels: devStr += str(device) + "/ao" + str(channel) + "," devStr = devStr[:-1] #print devStr #for troubleshooting self.data = 9.95*sin(arange(1000, dtype=float64)*2*pi/1000) #create waveform of some sort self.CreateAOVoltageChan(devStr,"",-10.0,10.0,DAQmx_Val_Volts,None) self.CfgSampClkTiming("",1000.0,DAQmx_Val_Rising,DAQmx_Val_ContSamps,1000) self.AutoRegisterDoneEvent(0) self.WriteAnalogF64("",1000,0,-1,DAQmx_Val_GroupByChannel,self.data.ctypes.data,None,None)
def __init__(self, analog, offset, buff, pattern, gui, index): Task.__init__(self) # buffer size self.buff = buff self.gui = gui # Patterns defined in the sequence to define gradient variation self.p_pat = pattern[0] self.s_pat = pattern[1] self.analog = analog self.offset = offset self.index = index self.index_stop = 0 chan = b"/Dev2/RTSI1" self.CreateAOVoltageChan(b"Dev2/ao0:4", "", -10, 10, Volts, None) self.CfgSampClkTiming(chan, 250000, Val_Ris, Val_ContSamps, buff) self.empty() self.AutoRegisterEveryNSamplesEvent(Val_Transf_Buffer, buff, 0)
def __init__(self, digit, read_data, index, stop_all): Task.__init__(self) # Find the buffer size dividing the array by the number of channels self.buff = len(digit) // 5 # Function to trigger the acquisition analysis self.read_data = read_data # Initialize an index class self.index = index # Flag to avoid having double stop function running self.index_stop = True # Function to stop all cards self.stop_all = stop_all # Converts digit into uint8 array, just in case digit = digit.astype(uint8) chan = b"/Dev2/ao/SampleClock" self.CreateDOChan(b"Dev2/port0/line1:5", "", DAQmx_Val_ChanPerLine) self.CfgSampClkTiming(chan, 250000, Val_Ris, Val_ContSamps, self.buff) self.WriteDigitalLines(self.buff, 0, 10, Val_GrpCh, digit, None, None) self.AutoRegisterEveryNSamplesEvent(Val_Transf_Buffer, self.buff, 0)
def __init__(self, device = GetDevices()[0] ,port = GetDIPorts(GetDevices()[0])[0][-1]): """ Constructor for DI Object Will get default device and port if none are specified. """ Task.__init__(self) lines = GetDILines(device) lines = [l for l in lines if 'port' + str(port) in l] self.deviceLines = len(lines) #set up task properties devStr = str(device) + "/port" + str(port) + "/line0:" + str(self.deviceLines-1) #create channel self.CreateDIChan(devStr,"",DAQmx_Val_ChanForAllLines) '''
def __init__(self,device = 'Dev1',channels = [0],bufferSize = 500,clockSpeed=10000.0): #construct task Task.__init__(self) #set up task properties self.bufferSize = bufferSize self.clockSpeed = clockSpeed self.channels = channels self.data = zeros((bufferSize,len(self.channels))) #data buffer self.dataArray = [] self.accumulate = False #create dev str for various channels devStr = "" for channel in channels: devStr += str(device) + "/ai" + str(channel) + "," devStr = devStr[:-1] self.CreateAIVoltageChan(devStr,"",DAQmx_Val_RSE,-10.0,10.0,DAQmx_Val_Volts,None) ''' #Configures channel "Dev1/ai0" #string for device and channel "" #handle name (not used in this example, only when using tasks without task class) DAQmx_Val_RSE #Referenced Single-Ended -10.0 #min voltage 10.0 #max voltage DAQmx_Val_Volts #measure in volts None #i have no idea what this does update:reserved for future use ''' self.CfgSampClkTiming("",self.clockSpeed,DAQmx_Val_Rising,DAQmx_Val_ContSamps,self.bufferSize) ''' #Configures sampling "" #external clock (for example "/Dev1/PFIO") or "" for internal clock self.clockSpeed #rate of internal clock or expected rate of external clock DAQmx_Val_Rising #aquire on rising or falling edge of clock ticks DAQmx_Val_ContSamps #continuous or finite samples self.bufferSize #if continuous samples, this is the buffer size. if finite, this is total sample size ''' self.AutoRegisterEveryNSamplesEvent(DAQmx_Val_Acquired_Into_Buffer,self.bufferSize,0) #set up data buffer callback self.AutoRegisterDoneEvent(0) #set up task complete callback (unused since this class takes continuous samples)
def __init__(self, name=""): PyDaqMxTask.__init__(self) self.name = name self.handle = daqmx.TaskHandle() self.TaskHandle = self.handle self.taskHandle = self.handle daqmx.CreateTask(name.encode(), self.handle) self.sample_rate = 100.0 self.timeout = 10.0 self.samples_per_channel = 10 self.channels = [] self.sample_clock_source = "" self.sample_clock_active_edge = "rising" self.sample_mode = "continuous samples" self.sample_clock_configured = False self.fillmode = "group by channel" self.task_type = "" self.append_data = False self.autolog = False self.autotrim_limit = 100000 # Maximum number of samples to keep self.autotrim = False # Only applicable if appending data
def __init__(self, device = GetDevices()[0], port = GetDOPorts(GetDevices()[0])[0][-1]): """ Constructor for DO object If no port is specified, gets default port from default device. """ Task.__init__(self) lines = GetDOLines(device) lines = [l for l in lines if 'port' + str(port) in l] self.deviceLines = len(lines) #create dev str for various lines devStr = str(device) + "/port" + str(port) + "/line0:" + str(self.deviceLines-1) self.lastOut = np.zeros(self.deviceLines, dtype = np.uint8) #keep track of last output #should be gotten from initial state instead #create IO channel self.CreateDOChan(devStr,"",DAQmx_Val_ChanForAllLines) ''' http://zone.ni.com/reference/en-XX/help/370471W-01/daqmxcfunc/daqmxcreatedochan/ ''' self.AutoRegisterDoneEvent(0)
def __init__(self, settings): Task.__init__(self) self.running = False self.settings = settings self.settings['time'].start() self.acq_samples = self.settings['acq_samples'] ################################### self.ch_in_list = self.settings['in'].keys() self.num_chans = len(self.ch_in_list) self.ch_out = [] self.data_buffer = {} for i in self.ch_in_list: chan = self.settings['device_input']+ '/' + self.settings['in'][i]['channel'] self.create_chan(chan, self.settings['in'][i]['min'], self.settings['in'][i]['max']) # print( 'created ', chan ) self.CfgSampClkTiming("", self.settings['acq_rate'], DAQmx_Val_Rising, DAQmx_Val_ContSamps, self.settings['buffer_size']) self.AutoRegisterEveryNSamplesEvent(DAQmx_Val_Acquired_Into_Buffer, self.acq_samples, 0) self.AutoRegisterDoneEvent(0)
def __init__(self): Task.__init__(self) running_tasks.append(self)
def __init__(self): Task.__init__(self) self._onDone = None