def createCOPulseTask(chan, freq, delay, duty, numPulses=4, edge=DAQmx_Val_Rising, triggerSource="PFI0"): th = Task() th.CreateCOPulseChanFreq(chan, "", DAQmx_Val_Hz, DAQmx_Val_Low, delay, freq, duty) th.CfgDigEdgeStartTrig(triggerSource, edge) th.CfgImplicitTiming(DAQmx_Val_FiniteSamps, numPulses) th.SetTrigAttribute(DAQmx_StartTrig_Retriggerable, True) return th
def createCOPulseTask2(chan, totTime, delay, pulseWidth, numPulses=4, edge=DAQmx_Val_Rising, triggerSource="PFI0"): th = Task() #th.CreateCOPulseChanFreq ( chan, "", DAQmx_Val_Hz, DAQmx_Val_Low, delay, freq, th.CreateCOPulseChanTime(chan, "", DAQmx_Val_Seconds, DAQmx_Val_Low, delay, totTime - pulseWidth, pulseWidth) th.CfgDigEdgeStartTrig(triggerSource, edge) th.CfgImplicitTiming(DAQmx_Val_FiniteSamps, numPulses) th.SetTrigAttribute(DAQmx_StartTrig_Retriggerable, True) return th
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)
pmt1_signal.StopTask() pmt1_signal.ClearTask() user_input = input('Enter v to start the stimulation or x to exit: ') if user_input == 'v': pmt_stim = ReadPMT1() pulse = Task() pulse.CreateCOPulseChanFreq( b"/%s/ctr0" % device, "", PyDAQmx.DAQmx_Val_Hz, PyDAQmx.DAQmx_Val_Low, stim_off, stim_freq, pulse_width / ((1 / stim_freq) * 1000) ) #initial delay, freq, duty cycle=pulse width over period (both in sec) pulse.CfgImplicitTiming( PyDAQmx.DAQmx_Val_FiniteSamps, stim_on * stim_freq ) #last is the number of pulses to generate in Finite mode stim_data = [] pmt_stim.StartTask() for c in range(cycles): pulse.StartTask() pulse.WaitUntilTaskDone(-1) pulse.StopTask() time.sleep(stim_off) pmt_stim.StopTask() stim_data = cycles * ( stim_off * sampling_freq * [0] + stim_on * sampling_freq * [1]) + stim_off * sampling_freq * [0] print('Visual stimulation finished, saving data')
pmt1_gain_val = float(input("Enter voltage gain between 0.1 and 1.25 V: ")) if first_pass == True: # Generate gating pulses # gate = Task() # gate.CreateCOPulseChanTime(b"/%s/ctr0"%device,"",PyDAQmx.DAQmx_Val_Seconds,PyDAQmx.DAQmx_Val_Low,10,5,5) #initial delay, low time, high time # gate.CfgImplicitTiming(PyDAQmx.DAQmx_Val_ContSamps,buffer_size) # gate.StartTask() # Generate pulse pulse = Task() pulse.CreateCOPulseChanTime(b"/%s/ctr0"%device,"",PyDAQmx.DAQmx_Val_Seconds,PyDAQmx.DAQmx_Val_Low,30,15,15) #initial delay, low time, high time pulse.CfgImplicitTiming(PyDAQmx.DAQmx_Val_ContSamps,buffer_size) #last is the number of pulses to generate in Finite mode pulse.StartTask() #PyDAQmx.DAQmxConnectTerms(b"/%s/PFI4"%device, b"/%s/PFI3"%device, PyDAQmx.DAQmx_Val_InvertPolarity) # gate.StartTask() # pulse.StartTask() # Write out voltage # led_data = np.ones(1)*4 #np.concatenate((np.ones(95)*4, np.zeros(5))) # led = Task() # led.CreateAOVoltageChan(b"/%s/ao0"%device,"LED",0,5,PyDAQmx.DAQmx_Val_Volts,None) # led.CfgSampClkTiming(b"/%s/Ctr0Source"%device,sampling_freq,PyDAQmx.DAQmx_Val_Rising, PyDAQmx.DAQmx_Val_ContSamps,buffer_size) # led.StartTask() # led.WriteAnalogF64(100,1,10.0,PyDAQmx.DAQmx_Val_GroupByChannel,led_data,None,None) #led = LED()
class digFreqGenerator(object): 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 _getStartTriggerSource(self): if self.initialized: buffSize = uInt32(255) buff = ctypes.create_string_buffer(buffSize.value) self.status = self.Task.GetDigEdgeStartTrigSrc(buff, buffSize) self._startTriggerSource = buff.value return self._startTriggerSource def _setStartTriggerSource(self, value): if self.initialized: self.status = self.Task.SetDigEdgeStartTrigSrc(value) #value = self._getStartTriggerSource() self._startTriggerSource = value startTriggerSource = property(_getStartTriggerSource, _setStartTriggerSource) def _getNumberOfPulses(self): if self.initialized: sampPerChan = uInt32() self.status = self.Task.GetSampQuantSampPerChan(sampPerChan) self._numberOfPulses = sampPerChan.value return self._numberOfPulses def _setNumberOfPulses(self, value): if self.initialized: self.status = self.Task.SetSampQuantSampPerChan(value) if value > 0: self.status = self.Task.SetSampQuantSampMode( DAQmx_Val_FiniteSamps) else: self.status = self.Task.SetSampQuantSampMode( DAQmx_Val_ContSamps) self._numberOfPulses = value numberOfPulses = property(_getNumberOfPulses, _setNumberOfPulses) def init(self, counter=None): if counter is not None: self.counter = counter self.status = self.Task.CreateCOPulseChanFreq(self.counter, '', DAQmx_Val_Hz, DAQmx_Val_Low, numpy.float64(self.initialDelay), numpy.float64(self.frequency), numpy.float64(self.dutyCycle)) if self._numberOfPulses > 0: self.status = self.Task.CfgImplicitTiming(DAQmx_Val_FiniteSamps, uInt64(self._numberOfPulses)) else: self.status = self.Task.CfgImplicitTiming(DAQmx_Val_ContSamps, uInt64(int(1e6))) if self.triggerType == TriggerType.Hardware: self.status = self.Task.CfgDigEdgeStartTrig( self._startTriggerSource, DAQmx_Val_Rising) self.status = self.Task.SetStartTrigRetriggerable(bool32(True)) self.initialized = True def _getOutputTerm(self): buffSize = uInt32(255) buff = ctypes.create_string_buffer(buffSize.value) self.status = self.Task.GetCOPulseTerm(self.counter, buff, buffSize) return buff.value def _setOutputTerm(self, term = 'PFI0'): self.status = self.Task.SetCOPulseTerm(self.counter, term) outputTerm = property(_getOutputTerm, _setOutputTerm) def start(self): self.status = self.Task.StartTask() def waitUntilDone(self): self.status = self.Task.WaitUntilTaskDone(self.timeout) def stop(self): retriggerable = bool32() self.status = self.Task.GetStartTrigRetriggerable(retriggerable) try: if retriggerable == 0: self.status = self.Task.StopTask() except DAQError as e: print(e.error) print(retriggerable.value) if e.error == 200010 and retriggerable.value == 1: print('caught') pass else: raise e def close(self): self.status = self.Task.ClearTask() self.Task = Task() self.initialized = False
class pCounter(object): ## This function is the constructor for the pCounter class. # # It creates internal variables required to perform functions within # the class. This function does not initialize any hardware. # @param self The object pointer. def __init__(self, **kwargs): #super(pCounter, self).__init__() ## The string that identifies the DAQmx device and counter # for the counter that is used to count edges. # # Example: PXISlot5/ctr0 self.edgeCounter = '' ## The string that identifies the DAQmx device and counter # for the counter that is used to create the sample clock. # # Example: /PXI1Slot5/ctr0 self.clockCounter = '' ## A boolean that enables the start trigger. # # The default is false, which disables the start trigger. # The measurement will immediately start when the start() # method is called. # A true value will make the measurement start when a digital # trigger is received on the line specified by the triggerSource # variable. self.enableStartTrigger = False ## A string that identifies the DAQmx digital line that will # be used as an input to the edge counter. # # Default: PFI0 self.edgeCntrTerm = kwargs.get('edgeCntrTerm', 'PFI0') self._triggerClkSource = 'Ctr0InternalOutput' ## A string that identifies the DAQmx digital line that will # be used as the start trigger. # # Default: PFI1 self.triggerSource = 'PFI1' ## A string that identifies the DAQmx digital line that will # output the sample clock. # # Default: PFI12 self.clockSourceTerm = kwargs.get('clockSourceterm', 'PFI12') ## The task reference for the edge counter. self.edgeCntrTask = Task() ## The task reference for the sample clock counter. self.clockCntrTask = Task() ## @var samples # This is the number of samples to take. It is the size # of the data array returned by the read() method. self._samples = kwargs.get('samples', None) ## @var sampleRate # This is the sample rate to use when counting edges. self._sampleRate = kwargs.get('sampleRate', None) ## @var acqTime # This is the time in milliseconds for a full acquisition # period. self._acqTime = None ## @var binTime # This is the time in millisenconds to take a single sample. self._binTime = None self._status = int32() ## This is the time to wait for a start trigger. # # If the timeout passes, then an error is generated. Ignore # this variable if the start trigger is disabled. self.timeout = kwargs.get('timeout', 1) self._samplesRead = None def _calcBinAndAcq(self): self._binTime = 1000. / self._sampleRate self._acqTime = (self._samples - 1.) * self._binTime def _calcSampsAndSampRate(self): self._sampleRate = 1000 / self._binTime self._samples = int((self._acqTime / self._binTime) + 1) def _getSamples(self): return self._samples def _setSamples(self, value): self._samples = value if self._sampleRate: self._calcBinAndAcq() samples = property(_getSamples, _setSamples) def _getSampleRate(self): return self._sampleRate def _setSampleRate(self, value): self._sampleRate = value if self._samples: self._calcBinAndAcq() sampleRate = property(_getSampleRate, _setSampleRate) def _getBinTime(self): return self._binTime def _setBinTime(self, value): self._binTime = value if self._acqTime: self._calcSampsAndSampRate() binTime = property(_getBinTime, _setBinTime) def _getAcqTime(self): return self._acqTime def _setAcqTime(self, value): self._acqTime = value if self._binTime: self._calcSampsAndSampRate() acqTime = property(_getAcqTime, _setAcqTime) ## This function initializes the pCounter class and opens a # reference to the DAQmx device(s). # # If specifiying a acqTime and binTime or samples and sampleRate, # only one pair of parameters need to be provided. When specifying # acqTime and binTime, the samples and sampleRate are calculated. # When specifying the samples and sampleRate, the acqTime and # binTime are calculated. # # @param self The object pointer. # @param clockCounter The string that identifies the DAQmx # device and counter for the counter that is used to create # the sample clock. # @param edgeCounter The string that identifies the DAQmx # device and counter for the counter that is used to count edges. # @param acqTime This is the time in milliseconds for a full # acquisition period. # @param binTime This is the time in millisenconds to take a # single sample. # @param samples The number of samples for the pCounter to take. # @param sampleRate The frequency of the samples taken by the # pCounter. def init(self, clockCounter=None, edgeCounter=None, acqTime=None, binTime=None, samples=None, sampleRate=None): if edgeCounter: self.edgeCounter = edgeCounter if clockCounter: self.clockCounter = clockCounter if samples and sampleRate: self._samples = samples self._sampleRate = sampleRate self._calcBinandAcq() if acqTime and binTime: self._acqTime = acqTime self._binTime = binTime self._calcSampsAndSampRate() # Setup the Edge Counter self._status = self.edgeCntrTask.CreateCICountEdgesChan( self.edgeCounter, '', DAQmx_Val_Rising, 0, DAQmx_Val_CountUp) self._status = self.edgeCntrTask.SetCICountEdgesTerm( self.edgeCounter, self.edgeCntrTerm) self._status = self.edgeCntrTask.CfgSampClkTiming( self._triggerClkSource, float64(self._sampleRate), DAQmx_Val_Rising, DAQmx_Val_FiniteSamps, uInt64(self._samples + 1)) # Setup the Clock Source Counter self._status = self.clockCntrTask.CreateCOPulseChanFreq( self.clockCounter, '', DAQmx_Val_Hz, DAQmx_Val_Low, 0, float64(self._sampleRate), float64(0.5)) self._status = self.clockCntrTask.SetCOPulseTerm( self.clockCounter, self.clockSourceTerm) self._status = self.clockCntrTask.CfgImplicitTiming( DAQmx_Val_ContSamps, uInt64(self._samples + 1)) if self.enableStartTrigger: self._status = self.clockCntrTask.CfgDigEdgeStartTrig( self.triggerSource, DAQmx_Val_Rising) ## This function initializes the pCounter class using the # chassis config file and opens a reference to the DAQmx device(s). # # @param self The object reference. # @param filepath The path to the chassis config file. def initFromFile(self, filepath): from .chassisConfigParser import chassisConfigParser config = chassisConfigParser() edgeCounter, clockCounter = config.readCntrSection(filepath) self.init(clockCounter, edgeCounter) ## This function starts the measurement. # # If the start trigger is enabled, then a the pCounter waits # for that digital trigger. Otherwise the measurement takes # place immediately. # @param self The object pointer. def start(self): self._status = self.edgeCntrTask.StartTask() self._status = self.clockCntrTask.StartTask() ## This function stops the measurement. # # It needs to be called everytime the start() method is called. # @param self The object pointer. def stop(self): self._status = self.edgeCntrTask.StopTask() self._status = self.clockCntrTask.StopTask() ## This function returns an array of the edge counts with an # array size equal to the number of samples. # # @param self The object pointer. def read(self): samplesRead = int32() data = np.zeros(self._samples + 1, dtype=np.uint32) self._status = self.edgeCntrTask.ReadCounterU32( int32(self._samples + 1), float64(self.timeout), data, uInt32(self._samples + 1), ctypes.byref(samplesRead), None) self._samplesRead = samplesRead.value dataDelta = [] for i, item in enumerate(data): if i > 0: dataDelta.append(item - preValue) preValue = item length = len(dataDelta) dataSum = 0 for item in dataDelta: dataSum += item mean = float(dataSum / length) sqSum = 0 for item in dataDelta: sq = np.square(item - mean) sqSum += sq stdDev = sqrt(sqSum / length) return dataDelta, mean, stdDev ## This function performs the start(), read(), and stop() methods # in one function call. # # This is useful for when the results of the read() method can be # retrieved immediately after a start() # @param self The object pointer. def measure(self): # Start the Tasks self.start() # Read the data data, mean, stdDev = self.read() # Stop the Tasks self.stop() return data, mean, stdDev ## This function closes the refences to the DAQmx devices. # # @param self The object pointer. def close(self): self._status = self.edgeCntrTask.ClearTask() self.edgeCntrTask = Task() self._status = self.clockCntrTask.ClearTask() self.clockCntrTask = Task() ## This function is the destructor for the pCounter class. # # It deletes internal variables and closes the references to # the DAQmx devices if they are not already closed. # @param self The object pointer. def __del__(self): self.close() del self.edgeCounter del self.clockCounter del self.enableStartTrigger del self.edgeCntrTerm del self._triggerClkSource del self.triggerSource del self.clockSourceTerm del self.edgeCntrTask del self.clockCntrTask del self._samples del self._sampleRate del self._acqTime del self._binTime del self._status del self.timeout del self._samplesRead
data = np.zeros(1000) read = PyDAQmx.int32() PyDAQmx.DAQmxWaitUntilTaskDone(task.taskHandle,PyDAQmx.float64(10.0)) task.ReadAnalogF64(1000, 10.0, PyDAQmx.DAQmx_Val_GroupByChannel, data, 1000, PyDAQmx.byref(read), None) print read plt.plot(data) plt.show() """ task.CreateCIFreqChan("Dev2/ctr1", "", 10.0, 100.0,PyDAQmx.DAQmx_Val_Hz,PyDAQmx.DAQmx_Val_Rising, PyDAQmx.DAQmx_Val_LowFreq1Ctr, 0.01,40, None) task.CfgImplicitTiming(PyDAQmx.DAQmx_Val_FiniteSamps, 10) task.StartTask() data = np.zeros(100) read = PyDAQmx.int32() PyDAQmx.DAQmxWaitUntilTaskDone(task.taskHandle,PyDAQmx.float64(10.0)) task.ReadCounterF64(100, 10.0,data,100, PyDAQmx.byref(read), None) print read print np.mean(data) #int32 DAQmxReadCounterF64 (TaskHandle taskHandle, int32 numSampsPerChan, float64 timeout, float64 readArray[], uInt32 arraySizeInSamps, int32 *sampsPerChanRead, bool32 *reserved); """ DAQmxErrChk(DAQmxCreateTask("DAQTaskInProject3", &taskOut));
def shutter_open(shutter_port): value = 5 shutter_task.WriteAnalogScalarF64(1, 10.0, value, None) # ## Trigger # --------------------------------------------------------------------------------------------------------------------------------------------- # In[39]: triggerTask = Task() triggerTask.CreateCOPulseChanFreq("/Dev1/ctr0", "", ni.DAQmx_Val_Hz, ni.DAQmx_Val_Low, 0.0, AI_sample_rate, 0.5) triggerTask.CfgImplicitTiming(ni.DAQmx_Val_FiniteSamps, 1) # # Run tasks # --------------------------------------------------------------------------------------------------------------------------------------------- # In[40]: #Setup the data that will be output on the trigger AO_task.WriteAnalogF64(num_AO_samples, 0, 10.0, ni.DAQmx_Val_GroupByChannel, waveform, ni.byref(written), None) # In[41]: AI_task.StartTask() #This will start on the trigger AO_task.StartTask() #This will start on the trigger triggerTask.StartTask() # Start counter and trigger tasks