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): freq1 = 10 freq2 = 20 freq3 = 30 sampRate = 1000 modAmp = 5 N = 1000 self.data = zeros(3, dtype='f8') th = Task() #Task.__init__(self) th.CreateAOVoltageChan("Dev12/ao0:2", "", -10, 10, DAQmx_Val_Volts, None) th.CfgSampClkTiming("", sampRate, DAQmx_Val_Rising, DAQmx_Val_ContSamps, N) self.th = th
def intensity(self): self.label.setText(str(self.textbox.text())) task = Task() task.CreateAOVoltageChan("/Dev1/ao1", "", minVal=0, maxVal=2, units=PyDAQmx.DAQmx_Val_Volts, customScaleName=None) task.StartTask() task.WriteAnalogScalarF64(1, 10.0, float((self.textbox.text())), reserved=None)
def init_task(): amplifier = Task() amplifier.CreateAOVoltageChan("Dev1/ao0", "", -10.0, 10.0, DAQmx_Val_Volts, None) amplifier.StartTask() laser_sensor = Task() laser_sensor.CreateAIVoltageChan("Dev1/ai0", "", DAQmx_Val_Cfg_Default, -10.0, 10.0, DAQmx_Val_Volts, None) laser_sensor.CfgSampClkTiming("", 10000.0, DAQmx_Val_Rising, DAQmx_Val_ContSamps, 1000) laser_sensor.StartTask() return amplifier, laser_sensor
class FieldControl(): # LibrerÃas necesarias: PyDAQmx, numpy y time 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 set_voltage(self,voltage): # Inicio un task para establecer el valor de voltaje de salida en volts self.task.StartTask() self.task.WriteAnalogScalarF64(1,10.0,voltage,None) self.task.StopTask() def set_voltage_steps(self,vf,step=0.01): # Cambia el voltaje en pasos pequeños, es necesario poner el valor de voltaje #deseado vf y el voltaje inicial vi(mejorar para que lo tome solo) vaux = self.vi if vf > self.vi: while vaux < vf: self.task.StartTask() self.task.WriteAnalogScalarF64(1,10.0,vaux,None) self.task.StopTask() vaux = vaux + step time_aux_ini = time.time() time_aux = time_aux_ini while (time_aux-time_aux_ini) < step: time_aux = time.time() else: while vaux > vf: self.task.StartTask() self.task.WriteAnalogScalarF64(1,10.0,vaux,None) self.task.StopTask() vaux = vaux - step time_aux_ini = time.time() time_aux = time_aux_ini while (time_aux-time_aux_ini) < step: time_aux = time.time() self.task.StartTask() self.task.WriteAnalogScalarF64(1,10.0,vf,None) self.task.StopTask() self.vi = vf # print('Succes')
def __init__(self, Nsamps=1000, sampRate=1000, modAmpL=[5e-3, 5e-3, 5e-3], modFreqL=[5, 3, 1]): self.data = zeros(3, dtype='f8') self.Vx, self.Vy, self.Vz = self.data th = Task() #Task.__init__(self) th.CreateAOVoltageChan("Dev12/ao0:2", "", -10, 10, DAQmx_Val_Volts, None) th.CfgSampClkTiming("", sampRate, DAQmx_Val_Rising, DAQmx_Val_ContSamps, Nsamps) self.th = th self.Nsamps = Nsamps self.sampRate = sampRate self.modFreqL = modFreqL self.modAmpL = modAmpL self.wvfm = zeros((3, Nsamps), dtype='f8') self.t = np.linspace(0, Nsamps / sampRate, Nsamps)
def trigger_analog_output(devport, edge_selection): ''' Using PFI to Trigger an Analog Output Generation in devport = Device/port e.g. Dev2/PFI0 out task = Task handle ''' logger.info("testlog, Device: {}".format(devport)) max_num_samples = 2 task = Task() task.CreateAOVoltageChan(devport, '', -10.0, 10.0, DAQmx_Val_Volts, None) task.CfgSampClkTiming('', float64(100), DAQmx_Val_Rising, DAQmx_Val_FiniteSamps, uInt64(max_num_samples)) if edge_selection == 'R': task.CfgDigEdgeStartTrig("/Dev2/PFI1", DAQmx_Val_Rising) #logger.info("testlog, trigger analog output -function, Rising: {}") else: task.CfgDigEdgeStartTrig("/Dev2/PFI1", DAQmx_Val_Falling) #logger.info("testlog, trigger analog output -function, Falling: {}") return task
from PyDAQmx import Task import PyDAQmx import numpy as np # Set initial voltage gain values pmt1_gain_val = 0.2 pmt2_gain_val = 0.2 # Create an analog output channel with a range of 0-1.25 V range and write out the voltage value set above pmt1_gain = Task() pmt1_gain.CreateAOVoltageChan("/Dev1/ao0", "PMT1_voltage_gain", 0, 1.25, PyDAQmx.DAQmx_Val_Volts, None) pmt1_gain.StartTask() pmt1_gain.WriteAnalogScalarF64(1, 0, pmt1_gain_val, None) pmt1_gain.StopTask() pmt1_gain.ClearTask() # Same for second PMT pmt2_gain = Task() pmt2_gain.CreateAOVoltageChan("/Dev1/ao1", "PMT2_voltage_gain", 0, 1.25, PyDAQmx.DAQmx_Val_Volts, None) pmt2_gain.StartTask() pmt2_gain.WriteAnalogScalarF64(1, 0, pmt2_gain_val, None) pmt2_gain.StopTask() pmt2_gain.ClearTask()
from PyDAQmx import Task import PyDAQmx import numpy as np from ctypes import byref pulse = Task() pulse.CreateCOPulseChanTime("/Dev2/ctr0", "LED pulse", PyDAQmx.DAQmx_Val_Seconds, PyDAQmx.DAQmx_Val_Low, 1.00, 10, 10) pulse.StartTask() voltage = Task() voltage.CreateAOVoltageChan("/Dev2/ao1", "LED", 0, 5, PyDAQmx.DAQmx_Val_Volts, None) voltage.CfgImplicitTiming(PyDAQmx.DAQmx_Val_ContSamps, 1000) voltage.CfgDigEdgeStartTrig("/Dev2/pfi0", PyDAQmx.DAQmx_Val_Rising) voltage.WriteAnalogScalarF64(1, 0, 3, None) # voltage.CfgSampClkTiming(None,1000,PyDAQmx.DAQmx_Val_Rising,PyDAQmx.DAQmx_Val_ContSamps,4000) # voltage.CfgDigEdgeStartTrig("/Dev2/pfi0",PyDAQmx.DAQmx_Val_Rising) # voltage.StartTask() # voltage.WriteAnalogF64(1,0,voltage_out,None) # taskHandle,4000,0,10.0,DAQmx_Val_GroupByChannel,data,&written,NULL) # class LED(Task): # def __init__(self): # Task.__init__(self) # self.CreateAOVoltageChan("/Dev2/ao1","LED",0,5,PyDAQmx.DAQmx_Val_Volts,None) # self.CfgSampClkTiming(None,1000,PyDAQmx.DAQmx_Val_Rising,PyDAQmx.DAQmx_Val_ContSamps,1000) # self.CfgDigEdgeStartTrig("/Dev2/pfi0",PyDAQmx.DAQmx_Val_Rising) # self.AutoRegisterDoneEvent(0)
) # sample 1000 data points into each buffer and then read them into the data array (size 1000), time out after 10 seconds self.a.extend( self.data.tolist()) # add current data to all acquired data self.n += buffer_size # count sample points #print(self.n, self.data[0]) return 0 def DoneCallback(self, status): print("Status", status.value) return 0 if __name__ == "__main__": ##################### Setting PMT gain ######################################## pmt1_gain = Task() pmt1_gain.CreateAOVoltageChan(b"/%s/ao1" % device, "PMT1_voltage_gain", 0, 1.25, PyDAQmx.DAQmx_Val_Volts, None) pmt1_gain.StartTask() pmt1_gain.WriteAnalogScalarF64(1, 0, pmt1_gain_val, None) pmt1_gain.StopTask() pmt1_gain.ClearTask() ##################### Start recording PMT for plotting ######################## pmt1_signal = ReadPMT1() pmt1_signal.StartTask() print('Recording') while len(pmt1_signal.a) < 30 * sampling_freq: time.sleep(0.01) pmt1_signal.StopTask() df = pd.DataFrame(np.column_stack(( np.arange(0, len(pmt1_signal.a)),
# samp_frequency = 44100 # sampling rate # mod_frequency = 1100 # mod_amplitude = 2 # mod_offset = 2 # samples = 1000 # x = np.arange(samples) # sinewave = mod_offset + mod_amplitude*(np.sin(2 * np.pi * mod_frequency * x / samp_frequency)).astype(np.float64) # laser.modulate(sinewave) # laser.StopTask() # laser.ClearTask() samp_frequency = 1000 # sampling rate mod_frequency = 1100 mod_amplitude = 2 mod_offset = 2 samples = 1000 # create the sine sinewave x = np.arange(samples) sinewave = mod_offset + mod_amplitude * (np.sin( 2 * np.pi * mod_frequency * x / samp_frequency)).astype(np.float64) laser = Task() laser.CreateAOVoltageChan("/Dev2/ao0", "Laser", 0, 5, PyDAQmx.DAQmx_Val_Volts, None) laser.CfgSampClkTiming(None, 1000.0, PyDAQmx.DAQmx_Val_Rising, PyDAQmx.DAQmx_Val_ContSamps, 1000) laser.SetWriteRegenMode(PyDAQmx.DAQmx_Val_DoNotAllowRegen) laser.WriteAnalogF64(1000, 0, 10.0, PyDAQmx.DAQmx_Val_GroupByChannel, sinewave, None, None) laser.StartTask()
""" Simple example of analog output This example outputs 'value' on ao0 """ from PyDAQmx import Task import numpy as np value = 1.3 task = Task() task.CreateAOVoltageChan("/TestDevice/ao0", "", -10.0, 10.0, PyDAQmx.DAQmx_Val_Volts, None) task.StartTask() task.WriteAnalogScalarF64(1, 10.0, value, None) task.StopTask()
class NI_6713Device(): """ This class is the interface to the NI driver for a NI PCI-6713 analog output card """ 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_AO = 8 self.NUM_DO = 8 self.MAX_name = MAX_name self.limits = [-10, 10] #Create AO Task self.ao_task = Task() self.ao_read = int32() self.ao_data = np.zeros((self.NUM_AO, ), dtype=np.float64) #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.ao_task.StartTask() self.do_task.StartTask() self.wait_for_rerun = False self.running = True self.read_Thread = Thread(target=self.read_fun, args=(message_queue, )) def start(self): """ Starts the message queue thread to read incoming instructions """ self.read_Thread.start() def read_fun(self, message_queue): """ Main method to read incoming instructions from the message queue """ while self.running: try: #read an instruction from the message queue typ, msg = message_queue.get(timeout=0.5) except Queue.Empty: continue #if there is no instruction in the queue, just read again until there is an instruction, or until the the the thread stops (running==False) # handle incoming instructions if typ == 'manual': # the msg argument contains the dict front_panel_values to send to the device self.program_manual(msg) message_queue.task_done( ) #signalise the sender, that the instruction is complete elif typ == 'trans to buff': #Transition to Buffered # msg is a dict containing all relevant arguments # If fresh is true, the hardware should be programmed with new commands, which were permitted # if fresh is false, use the last programmed harware commands again, so no hardware programming is needed at all if msg['fresh']: self.transition_to_buffered(True, msg['clock_terminal'], msg['ao_channels'], msg['ao_data']) else: self.transition_to_buffered(False, None, None, None) message_queue.task_done() #signalize that the task is done elif typ == 'trans to man': #Transition to Manual self.transition_to_manual(msg['more_reps'], msg['abort']) message_queue.task_done() # signalise that the task is done else: # an unknown/unimplemented instruction is requestet print("unkown message: " + msg) message_queue.task_done() continue def setup_static_channels(self): self.wait_for_rerun = False #setup AO channels for i in range(self.NUM_AO): self.ao_task.CreateAOVoltageChan(self.MAX_name + "/ao%d" % i, "", self.limits[0], self.limits[1], DAQmx_Val_Volts, None) #setup DO port(s) self.do_task.CreateDOChan(self.MAX_name + "/port0/line0:7", "", DAQmx_Val_ChanForAllLines) def shutdown(self): """ Shutdown the device (stop & clear all tasks). Also stop the message queue thread """ print("shutdown device") self.running = False self.ao_task.StopTask() self.ao_task.ClearTask() self.do_task.StopTask() self.do_task.ClearTask() 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 transition_to_buffered(self, fresh, clock_terminal, ao_channels, ao_data): """ Transition the device to buffered mode This method does the hardware programming if needed Parameters ---------- fresh : bool True if the device should be programmed with new instructions False if the old instructions should be executed again, so no programming is needed (just rerun last instructions) clock_terminal : str The device connection on which the clock signal is connected (e.g. 'PFI0') ao_channels : list str A list of all analog output channels that should be used ao_data : 2d-numpy array, float64 A 2d-array containing the instructions for each ao_channel for every clock tick """ self.ao_task.StopTask( ) #Stop the last task (static mode or last buffered shot) if not fresh: if not self.wait_for_rerun: raise Exception("Cannot rerun Task.") self.ao_task.StartTask() #just run old task again return elif not clock_terminal or not ao_channels or ao_data is None: raise Exception( "Cannot progam device. Some arguments are missing.") self.ao_task.ClearTask( ) #clear the last task and create a new one with new parameters & instructions self.ao_task = Task() self.ao_task.CreateAOVoltageChan(ao_channels, "", -10.0, 10.0, DAQmx_Val_Volts, None) self.ao_task.CfgSampClkTiming(clock_terminal, 1000000, DAQmx_Val_Rising, DAQmx_Val_FiniteSamps, ao_data.shape[0]) self.ao_task.WriteAnalogF64(ao_data.shape[0], False, 10.0, DAQmx_Val_GroupByScanNumber, ao_data, self.ao_read, None) self.ao_task.StartTask() #finally start the task def transition_to_manual(self, more_reps, abort): """ Stop buffered mode """ if abort: self.wait_for_rerun = False 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.ao_task.StartTask() self.do_task.StartTask() else: self.wait_for_rerun = True
class AnalogOutput(object): ## This function is a constructor for the AnalogOutput class. # # It creates the internal variables required to perform functions within the # class. This function does not initialize any hardware. def __init__(self): ## The DAQmx task reference. self.taskRef = Task() ## This is a boolean that is true when the DAQmx task has been initialized. self.initialized = False ## This is the status of the DAQmx task. # # A value greater than 0 means that an error has occurred. When the status # is greater than 0 an error should be reported by the class. self.status = int32() ## @var sampleRate # This is the sample rate of the analog output. self._sampleRate = 100e3 ## @var numChannels # This is the number of channels configured in the task. self._numChannels = 0 ## @var samplesPerChannel # This is the number of samples per channel that will be # generated in Finite mode. self._samplesPerChannel = 100 ## @var clkSource # This is the sample clock source terminal. It can be set to an # internal clock or external clock such as a PFI line i.e. "/PXI1Slot3/PFI15." self._clkSource = '' ## @var startTriggerSource # This is the start trigger source terminal. The software # ignores this value when the triggerType is set to "Software". Otherwise when # the triggerType is "Hardware," this terminal is used to start analog # generation. Example Value: "/PXI1Slot3/PFI0" self._startTriggerSource = '' ## @var pauseTriggerSource # The source terminal of the pause trigger. This can be # any PFI or backplane trigger such as 'PFI5' and 'PXI_TRIG5' self._pauseTriggerSource = '' ## This is the start trigger terminal of the NI-Sync card. # # Setting this value will make sure that the start trigger will be # propogated through the PXI backplane. If there is no sync card needed # leave the value default. self.startTriggerSyncCard = '' ## This is the mode of operation for the analog outputs. # # There are currently three modes available. Static mode is where one # static voltage is set with no need for a sample clock. Finite mode is # where a finite number of voltages will be set at a sample clock rate. # Continuous mode is where a sequence of voltages are generated at a sample # rate and then repeated until the stop() method is called. self.mode = dutil.Mode.Finite ## The trigger type for the analog outputs. # # There are currently two trigger types - "Software" and # "Hardware." The "Software" mode means that analog output channels are not # syncronized. While "Hardware" means that analog output channels are # syncronized to a start trigger. The startTriggerSouce attribute must be # configured appropriately. self.triggerType = dutil.TriggerType.Software ## The number of times to iterate over a Finite number of samples. # # This value is only useful in the "Finite" mode. It is the number of # times that a sequence of voltages will be looped. The default is allways 1. self.loops = 1 ## The estimated time to generate the samples for a Finite generation. # # Once the input buffer of the analog input is configured, the # amount of time it takes to generate the voltages in the buffer can be # estimated. This is a function of the sample rate and the number of samples # per channel. (This attribute is for internal use only. This attribute may # not return an accurate value.) self.estAcqTime = 0 ## The analog output buffer. # # This is the data that is stored in the buffer of the Analog Output card. self.buff = None self._timeoutPad = 0.01 def _getDone(self): done = bool32() if self.initialized: self.status = self.taskRef.GetTaskComplete(ctypes.byref(done)) else: done.value = 1 return bool(done.value) ## @var done # Returns the task done status. # # This mode works differently depending on the mode. <br /> # <ul> # <li><B>Static and Continuous</B>: done is false after a start # method and true</li> # only after a stop method. # <li><B>Finite</B>: done is false until all samples are # generated.</li></ul> done = property(_getDone) def _getPauseTriggerSource(self): if self.initialized: buffSize = uInt32(255) buff = ctypes.create_string_buffer(buffSize.value) self.status = self.taskRef.GetDigLvlPauseTrigSrc(buff, buffSize) self._pauseTriggerSource = buff.value return self._pauseTriggerSource def _setPauseTriggerSource(self, value): if self.initialized: if value == '': self.status = self.taskRef.SetPauseTrigType(DAQmx_Val_None) self.status = self.taskRef.ResetDigLvlPauseTrigSrc() else: self.status = self.taskRef.SetDigLvlPauseTrigWhen( DAQmx_Val_High) self.status = self.taskRef.SetPauseTrigType(DAQmx_Val_DigLvl) self.status = self.taskRef.SetDigLvlPauseTrigSrc(value) self._pauseTriggerSource = value pauseTriggerSource = property(_getPauseTriggerSource, _setPauseTriggerSource) ## Initializes the analog outputs based on the object's configuration. # @param self The object pointer. # @param physicalChannel A string representing the device and analog # output channels. Example Value: "PXI1Slot3/ao0:7" def init(self, physicalChannel): self.__createTask(physicalChannel) self.initialized = True #Finite Mode if self.mode == dutil.Mode.Finite: self.status = self.taskRef.SetWriteRegenMode(DAQmx_Val_AllowRegen) self.__configTiming(DAQmx_Val_FiniteSamps) #Continuous Mode elif self.mode == dutil.Mode.Continuous: self.status = self.taskRef.SetWriteRegenMode(DAQmx_Val_AllowRegen) self.__configTiming(DAQmx_Val_ContSamps) #Static Mode elif self.mode == dutil.Mode.Static: self.setSampleRate(self._sampleRate) self.setSamplesPerChannel(1) self.pauseTriggerSource = self._pauseTriggerSource #print self.samplesPerChannel #print self._sampleRate #print self.clkSource #print self.startTriggerSource ## This function returns the samples per channel configured in the DAQmx Task. # @param self The object pointer. def getSamplesPerChannel(self): if self.initialized: samplesPerChannel = uInt64() self.status = self.taskRef.GetSampQuantSampPerChan( ctypes.byref(samplesPerChannel)) self._samplesPerChannel = samplesPerChannel.value return self._samplesPerChannel ## This function sets the samples per channel in the DAQmx Task. # @param self The object pointer. # @param value The value to set the samples per channel. def setSamplesPerChannel(self, value): if self.initialized: self.status = self.taskRef.SetSampQuantSampPerChan(uInt64(value)) self._samplesPerChannel = value ## This funciton deletes the samplesPerChannel variable inside the AnalogOutput # object. # # It is an internal function that is called in the class destructor. It should # not be called. def _delSamplesPerChannel(self): """ This funciton deletes the samplesPerChannel variable inside the AnalogOutput object. It is an internal function that is called in the class destructor. It should not be called. """ del self._samplesPerChannel samplesPerChannel = property(getSamplesPerChannel, setSamplesPerChannel, _delSamplesPerChannel) ## This function returns the sample clock source configured in the DAQmx Task. # @param self The object pointer. def getClkSource(self): if self.initialized: buffSize = uInt32(255) buff = ctypes.create_string_buffer(buffSize.value) self.status = self.taskRef.GetSampClkSrc(buff, buffSize) self._clkSource = buff.value return self._clkSource ## This function sets the sample clock source in the DAQmx Task. # @param self The object pointer. # @param value The string value for the clock source terminal. def setClkSource(self, value): if self.initialized: self.status = self.taskRef.SetSampClkSrc(value) value = self.getClkSource() self._clkSource = value ## This function deletes the clkSource variable within the AnalogOutput object. # # It is an internal function that is called in the class destructor. It should # not be called. def _delClkSource(self): del self._clkSource clkSource = property(getClkSource, setClkSource, _delClkSource) ## This function return the start trigger source configured in the DAQmx Task. # @param self The object pointer. def getStartTriggerSource(self): if self.initialized: buffSize = uInt32(255) buff = ctypes.create_string_buffer(buffSize.value) self.status = self.taskRef.GetDigEdgeStartTrigSrc(buff, buffSize) self._startTriggerSource = buff.value return self._startTriggerSource ## This function sets the start trigger source in the DAQmx Task. # @param self The object pointer. # @param value The string vaue of the start trigger source. # Example value: "\PXI1Slot3\PFI0" def setStartTriggerSource(self, value): if self.initialized: self.status = self.taskRef.SetDigEdgeStartTrigSrc(value) value = self.getStartTriggerSource() self._startTriggerSource = value ## This function deletes the startTriggerSource variable within the AnalogOutput object. # # It is an internal function that is called in the class destructor. It should # not be called. def _delStartTriggerSource(self): del self._startTriggerSource startTriggerSource = property(getStartTriggerSource, setStartTriggerSource, _delStartTriggerSource) ## This function returns the number of channels configured in the DAQmx Task. # @param self The object pointer. def getNumChannels(self): if self.initialized: numChannels = uInt32() self.status = self.taskRef.GetTaskNumChans( ctypes.byref(numChannels)) self._numChannels = numChannels.value return self._numChannels numChannels = property(getNumChannels) ## This function returns the sample rate configured in the DAQmx Task. # @param self The object pointer. def getSampleRate(self): if self.initialized: sampleRate = float64() self.status = self.taskRef.GetSampClkRate(ctypes.byref(sampleRate)) self._sampleRate = sampleRate.value return self._sampleRate ## This funciton sets the sample rate in the DAQmx Task. # @param self The object pointer. # @param value The value of the sample rate. def setSampleRate(self, value): if self.initialized: self.status = self.taskRef.SetSampClkRate(float64(value)) self._sampleRate = value ## This function deletes the sample rate variable inside the AnalogOutput object. # @param self The object pointer. def _delSampleRate(self): del self._sampleRate sampleRate = property(getSampleRate, setSampleRate, _delSampleRate) ## This function returns a 1D numpy array of samples with random voltages. # The returned value is intended to be used to write samples to the buffer with # the writeToBuffer() method. # @param self The object pointer. # @param numChannels The number of channels to generate. If this parameter is # not provided, Then the function will generate the number of channels configured # in the analog output task. def createTestBuffer(self, numChannels=0): numChannels = numChannels if numChannels > 0 else self.getNumChannels() return numpy.float64( numpy.random.rand(self._samplesPerChannel * numChannels)) ## This function returns a 1D numpy array of sine waves. The returned # value is intended to be used to write samples to the buffer with the # writeToBuffer() method. # @param self The object pointer. def createSineTestBuffer(self): from .createSineWave import createSineWave numChannels = self.getNumChannels() for i in range(numChannels): data = createSineWave(10, 100e3, self._sampleRate, self._samplesPerChannel, ((2 * numpy.pi) / numChannels) * i) if i == 0: sineData = data['amplitude'] else: sineData = numpy.append(sineData, data['amplitude']) return sineData ## This function writes the specified values into the buffer. # @param self The object pointer. # @param data This is a 1D 64-bit floating point numpy array that contians data # for each channel. Channels are non-interleaved (channel1 n-samples then # channel2 n-samples). def writeToBuffer(self, data): autostart = self.mode == dutil.Mode.Static self.buff = data samplesWritten = int32() self.status = self.taskRef.WriteAnalogF64(self._samplesPerChannel, autostart, 10, DAQmx_Val_GroupByChannel, data, ctypes.byref(samplesWritten), None) return samplesWritten.value ## This function starts the analog output generation. # @param self The object pointer. def start(self): self.status = self.taskRef.StartTask() ## This functions waits for the analog output generation to complete. # @param self The object pointer. def waitUntilDone(self): sampPerChan = uInt64() self.status = self.taskRef.GetSampQuantSampPerChan( ctypes.byref(sampPerChan)) self.estAcqTime = (self.loops * sampPerChan.value) / self._sampleRate #print 'SamplesPerChannel: ' + str(sampPerChan.value) #print 'Estimated Acquisition Time: ' + str(self.estAcqTime) #if (self.estAcqTime >= 0.01 and self.mode != dutil.Mode.Static): if self.mode != dutil.Mode.Static: self.status = self.taskRef.WaitUntilTaskDone( float64(self.estAcqTime + self._timeoutPad)) ## This function stops the analog output generation. # @param self The object pointer. def stop(self): self.status = self.taskRef.StopTask() def __createTask(self, physicalChannel): """ This is a private method that creates the Task object for use inside the AnalogOutput class.""" self.status = self.taskRef.CreateAOVoltageChan(physicalChannel, "", -10, 10, DAQmx_Val_Volts, None) def __configTiming(self, sampleMode): """ This is a private method that configures the timing for the Analog Output class. """ totalSamples = self._samplesPerChannel * self.loops onDemand = bool32() self.status = self.taskRef.GetOnDemandSimultaneousAOEnable( ctypes.byref(onDemand)) #print 'On Demand: ' + str(onDemand.value) #print 'Trigger Type: ' + str(self.triggerType) #print 'Software Trigger Type: ' + str(dutil.TriggerType.Software) if self.triggerType == dutil.TriggerType.Software: #print 'Software Timing' self.status = self.taskRef.CfgSampClkTiming( 'OnboardClock', float64(self._sampleRate), DAQmx_Val_Rising, sampleMode, uInt64(totalSamples)) elif self.triggerType == dutil.TriggerType.Hardware: #print 'Hardware Timing' self.status = self.taskRef.CfgSampClkTiming( self._clkSource, float64(self._sampleRate), DAQmx_Val_Falling, sampleMode, uInt64(totalSamples)) self.status = self.taskRef.CfgDigEdgeStartTrig( self._startTriggerSource, DAQmx_Val_Rising) if self.startTriggerSyncCard != '': DAQmxConnectTerms(self.startTriggerSyncCard, self._startTriggerSource, DAQmx_Val_DoNotInvertPolarity) ## This function will close connection to the analog output device and channels. # @param self The object pointer. def close(self): self.initialized = False if self.startTriggerSyncCard != '': DAQmxDisconnectTerms(self._startTriggerSource, self.startTriggerSyncCard) self.status = self.taskRef.ClearTask() self.taskRef = Task() ## This is the destructor for the AnalogOutput Class. # @param self The object pointer. def __del__(self): if self.initialized: self.close() del self.taskRef del self.initialized del self.status del self.sampleRate del self._numChannels del self.samplesPerChannel del self.clkSource del self.startTriggerSource del self.startTriggerSyncCard del self.mode del self.triggerType del self.loops del self.estAcqTime
# In[35]: # analog output parameters num_AO_samples = 10000 AO_sample_rate = 20000.0 amplitude = 3 # This defines the range over which we sample x_freq = 2.0 y_freq = 200.0 written = ni.int32() waveform, t = gen_waveform(x_freq, y_freq, num_AO_samples, AO_sample_rate, amplitude) AO_task = Task() AO_task.CreateAOVoltageChan("/Dev1/ao0:1", "", -10.0, 10.0, ni.DAQmx_Val_Volts, None) #AO_task.StartTask() # Specify Sample Clock Timing AO_task.CfgSampClkTiming("OnboardClock", AO_sample_rate, ni.DAQmx_Val_Rising, ni.DAQmx_Val_ContSamps, num_AO_samples) #Trigger on the counter. PFI12 is the output of counter 0 AO_task.CfgDigEdgeStartTrig("/Dev1/PFI12", ni.DAQmx_Val_Rising) # ## Analog input # --------------------------------------------------------------------------------------------------------------------------------------------- # In[36]: # Define analog input task AI_task = Task()
from PyDAQmx import Task import PyDAQmx import numpy as np import time from MultiChannelAnalogInput import * writeTask = Task() writeTask.CreateAOVoltageChan("/Dev1/ao0", "", 0.0, 5.0, PyDAQmx.DAQmx_Val_Volts, None) anIn = MultiChannelAnalogInput(["Dev1/ai0", "Dev1/ai1", "Dev1/ai2"], (0.0, 5.0)) anIn.configure() def setVoltage(value): conversionFactor = 1.5927 writeTask.StartTask() writeTask.WriteAnalogScalarF64(1, 5.0, conversionFactor * value, None) writeTask.StopTask() def getVoltages(freq=10000, Nsamples=1): sum0 = 0 sum1 = 0 sum2 = 0 for i in range(Nsamples): vals = anIn.readAll() sum0 += vals['Dev1/ai0']