Exemplo n.º 1
0
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
Exemplo n.º 2
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
Exemplo n.º 3
0
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
Exemplo n.º 4
0
def connect_analog_io_port_RSE(devport, samples, rate):
    '''
    Initialize task for reading from analog input port for Voltage measurement
    in    devport = Device/port e.g. Dev1/ai2
    out   task = Task handle
    '''
    logger.info("temp: {}".format(devport))
    max_num_samples = samples
    task = Task()
    task.CreateAIVoltageChan(devport, '', DAQmx_Val_RSE, -10.0, 10.0,
                             DAQmx_Val_Volts, None)
    task.CfgSampClkTiming('', float64(rate), DAQmx_Val_Rising,
                          DAQmx_Val_FiniteSamps, uInt64(max_num_samples))
    task.StartTask()
    return task
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
Exemplo n.º 6
0
def supported_AI_ranges_for_non_differential_input(device_name, AI_ranges):
    """Try AI ranges to see which are actually allowed for non-differential input, since
    the largest range may only be available for differential input, which we don't
    attempt to support (though we could with a little effort)"""
    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
Exemplo n.º 7
0
def trigger_analog_input(devport, samples, rate, edge_selection):
    '''
    Using PFI to Trigger an Analog Input Acquisition
    in    devport = Device/port e.g. Dev2/PFI0
    out   task = Task handle
    '''
    logger.info("testlog, Device: {}".format(devport))
    max_num_samples = samples
    task = Task()
    task.CreateAIVoltageChan(devport, '', DAQmx_Val_RSE, -10.0, 10.0,
                             DAQmx_Val_Volts, None)
    task.CfgSampClkTiming('', float64(rate), DAQmx_Val_Rising,
                          DAQmx_Val_FiniteSamps, uInt64(max_num_samples))
    #logger.info("trigger analog input -function, 1: {}")
    if edge_selection == 'R':
        task.CfgDigEdgeStartTrig("/Dev2/PFI0", DAQmx_Val_Rising)
        logger.info("testlog, trigger analog input -function, Rising: {}")
    else:
        task.CfgDigEdgeStartTrig("/Dev2/PFI0", DAQmx_Val_Falling)
        logger.info("testlog, trigger analog input -function, Falling: {}")
    task.StartTask()
    return task
Exemplo n.º 8
0
def AI_filter_delay(device_name):
    """Determine the filter delay for dynamic signal acquistion devices.

    Returns the delay in clock cycles. Absolute delay will vary with sample rate.
    
    Args:
        device_name (str): NI-MAX device name

    Returns:
        int: Number of analog input delays ticks between task start and acquisition start.
    """
    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_PseudoDiff, 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_filter_delay = float64()
    sample_timebase_rate = float64()

    # get delay in number of clock samples
    task.SetAIFilterDelayUnits("", c.DAQmx_Val_SampleClkPeriods)

    task.GetAIFilterDelay("", start_filter_delay)
    task.GetSampClkTimebaseRate(sample_timebase_rate)

    task.ClearTask()

    return int(start_filter_delay.value)
Exemplo n.º 9
0
class daq(object):
    """This class prepares and configures a DAQ system for an analog adquisition. The required
    arguments are the name of the device as a string (p.e. 'Dev3'), the adquisition time in seconds
    (adqTime), the sampling frequency in Hz (adqFreq), the channels to read as a list of integer values
    with the available channels, the voltage range of the channels as a list with the maximum positive
    voltage value and with the same length as the channel list.
    
    Optional arguments:
        - mode = 'FiniteSamps': sets the adquisiton mode to finite sampling (default) or continuous 'ContSamps'
        - trigger = None: sets the trigger mode. If None it is taken as the clock edge. Otherwise,
                    a 2-element list can be passed, the first value being the channel number and the second
                    the voltage value to configure the trigger to an analog channel in rising mode.
    
    This class only contemplates reading volts signal of analog inputs in differential configuration.
    Future versions might implement other possibilities."""
    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])
        # In the case the DAQ accept a trigger from one of the analog channels we could also setup it as
        #
    def start(self):
        self.ai.StartTask()

    def stop(self):
        self.ai.StopTask()
        self.data = np.zeros((self.N_samples * self.N_channels, ),
                             dtype=np.float64)

    def read_analog(self, timeout=10.0):
        """Calls the ReadAnalogF64 with the configured parameters.
        
        Optional arguments:
            - timeout = 10.0: timeout in number of seconds.
        """
        self.ai.ReadAnalogF64(self.N_samples, timeout,
                              DAQmx_Val_GroupByChannel,
                              self.data, self.N_samples * self.N_channels,
                              byref(self.read), None)
        return self.data.reshape((self.N_samples, self.N_channels), order="F")

    def clear(self):
        self.ai.ClearTask()
Exemplo n.º 10
0
class Recorder(RecorderParent):
    """
     Sets up the recording stream through a National Instrument

     Attributes
     ----------
    device_name: str
        Name of the device to be used for recording
    max_value: float
        Maximum value of recorded data
    """
#---------------- INITIALISATION METHODS -----------------------------------
    def __init__(self,channels = 1,rate = 30000.0, chunk_size = 1000,
                 num_chunk = 4,device_name = None):
        """
        Re-implemented from RecorderParent
        """

        super().__init__(channels = channels,rate = rate,
             chunk_size = chunk_size,num_chunk = num_chunk)
        print('You are using National Instrument for recording')

        self.device_name = None
        self.set_device_by_name(device_name);

        self.open_recorder()
        self.trigger_init()

        self.max_value = 10;

#---------------- DEVICE SETTING METHODS -----------------------------------
    def set_device_by_name(self, name):
        """
         Set the recording audio device by name.
         Uses the first device found if no such device found.
        """
        devices = self.available_devices()[0]
        selected_device = None
        if not devices:
            print('No NI devices found')
            return

        if not name in devices:
            print('Input device name not found, using the first device')
            selected_device = devices[0]
        else:
            selected_device = name

        print('Selected devices: %s' % selected_device)
        self.device_name = selected_device

     # Get audio device names
    def available_devices(self):
        """
        Get all the available input National Instrument devices.

        Returns
        ----------
        devices_name: List of str
            Name of the device, e.g. Dev0
        device_type: List of str
            Type of device, e.g. USB-6003
        """
        numBytesneeded = pdaq.DAQmxGetSysDevNames(None,0)
        databuffer = pdaq.create_string_buffer(numBytesneeded)
        pdaq.DAQmxGetSysDevNames(databuffer,numBytesneeded)

        #device_list = []
        devices_name = pdaq.string_at(databuffer).decode('utf-8').split(',')

        device_type = []
        for dev in devices_name:
            numBytesneeded = pdaq.DAQmxGetDevProductType(dev,None,0)
            databuffer = pdaq.create_string_buffer(numBytesneeded)
            pdaq.DAQmxGetDevProductType(dev,databuffer,numBytesneeded)
            device_type.append(pdaq.string_at(databuffer).decode('utf-8'))

        #device_list.append(devices_name)
        #device_list.append(device_type)

        return(devices_name,device_type)

    # Display the current selected device info
    def current_device_info(self):
        """
        Prints information about the current device set
        """
        device_info = {}
        info = ('Category', 'Type','Product', 'Number',
                'Analog Trigger Support','Analog Input Trigger Types','Analog Input Channels (ai)', 'Analog Output Channels (ao)',
                'ai Minimum Rate(Hz)', 'ai Maximum Rate(Single)(Hz)', 'ai Maximum Rate(Multi)(Hz)',
                'Digital Trigger Support','Digital Input Trigger Types','Digital Ports', 'Digital Lines', 'Terminals')
        funcs = (pdaq.DAQmxGetDevProductCategory, pdaq.DAQmxGetDevProductType,
                 pdaq.DAQmxGetDevProductNum, pdaq.DAQmxGetDevSerialNum,
                 pdaq.DAQmxGetDevAnlgTrigSupported,  pdaq.DAQmxGetDevAITrigUsage,
                 pdaq.DAQmxGetDevAIPhysicalChans,pdaq.DAQmxGetDevAOPhysicalChans,
                 pdaq.DAQmxGetDevAIMinRate, pdaq.DAQmxGetDevAIMaxSingleChanRate, pdaq.DAQmxGetDevAIMaxMultiChanRate,
                 pdaq.DAQmxGetDevDigTrigSupported,pdaq.DAQmxGetDevDITrigUsage,
                 pdaq.DAQmxGetDevDIPorts,pdaq.DAQmxGetDevDILines,
                 pdaq.DAQmxGetDevTerminals)
        var_types = (pdaq.int32, str, pdaq.uint32, pdaq.uint32,
                     pdaq.bool32,pdaq.int32,str,str,
                     pdaq.float64, pdaq.float64, pdaq.float64,
                     pdaq.bool32,pdaq.int32,str,str,str)

        for i,f,v in zip(info,funcs,var_types):
            try:
                if v == str:
                    nBytes = f(self.device_name,None,0)
                    string_ptr = pdaq.create_string_buffer(nBytes)
                    f(self.device_name,string_ptr,nBytes)
                    if any( x in i for x in ('Channels','Ports')):
                        device_info[i] = len(string_ptr.value.decode().split(','))
                    else:
                        device_info[i] = string_ptr.value.decode()
                else:
                    data = v()
                    f(self.device_name,data)
                    if 'Types' in i:
                        device_info[i] = bin(data.value)[2:].zfill(6)
                    else:
                        device_info[i] = data.value
            except Exception as e:
                print(e)
                device_info[i] = '-'

        pp.pprint(device_info)

    def set_channels(self):
        """
        Create the string to initiate the channels when assigning a Task

        Returns
        ----------
        channelname: str
            The channel names to be used when assigning Task
            e.g. Dev0/ai0:Dev0/ai1
        """
        if self.channels >1:
            channelname =  '%s/ai0:%s/ai%i' % (self.device_name, self.device_name,self.channels-1)
        elif self.channels == 1:
            channelname = '%s/ai0' % self.device_name

        print('Channels Name: %s' % channelname)
        return channelname

#---------------- STREAMING METHODS -----------------------------------
    # Convert data obtained into a proper array
    def audiodata_to_array(self,data):
        """
        Re-implemented from RecorderParent
        """
        return data.reshape((-1,self.channels))/(2**15) *10.0

    # Callback function for audio streaming
    def stream_audio_callback(self):
        """
        Callback function for audio streaming.
        First, it writes data to the circular buffer,
        then record data if it is recording,
        finally check for any trigger.

        Returns 0 as part of the callback format.
        More info can be found in PyDAQmx documentation on Task class
        """
        in_data = np.zeros(self.chunk_size*self.channels,dtype = np.int16)
        read = pdaq.int32()
        self.audio_stream.ReadBinaryI16(self.chunk_size,10.0,pdaq.DAQmx_Val_GroupByScanNumber,
                           in_data,self.chunk_size*self.channels,pdaq.byref(read),None)

        data_array = self.audiodata_to_array(in_data)
        self.write_buffer(data_array)
        #self.rEmitter.newdata.emit()

        if self.recording:
            self.record_data(data_array)
         # Trigger check
        if self.trigger:
            self._trigger_check_threshold(data_array)

        return 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

    # Start the streaming
    def stream_start(self):
        """
        Re-implemented from RecorderParent.
        """
        if self.audio_stream:
            task_done = pdaq.bool32()
            self.audio_stream.GetTaskComplete(task_done)
            if task_done.value:
                self.audio_stream.StartTask()
            else:
                print('stream already started')
        else:
            print('No audio stream is set up')
    # Stop the streaming
    def stream_stop(self):
        """
        Re-implemented from RecorderParent.
        """
        if self.audio_stream:
            task_done = pdaq.bool32()
            self.audio_stream.GetTaskComplete(task_done)
            if not task_done.value:
                self.audio_stream.StopTask()
            else:
                print('stream already stopped')
        else:
            print('No audio stream is set up')

    # Close the stream, probably needed if any parameter of the stream is changed
    def stream_close(self):
        """
        Re-implemented from RecorderParent.
        """
        if self.audio_stream:
            self.audio_stream.StopTask()
            self.audio_stream.ClearTask()
            self.audio_stream = None
Exemplo n.º 11
0
class AnalogInput(object):
    ## This function is a constructor for the AnalogInput 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()

        ## A boolean that is set to True when the AnalogInput card is 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 input.
        self._sampleRate = 100e3

        ## @var samplesPerChannel
        #  This is the number of samples per channel that will be
        #  acquired in Finite mode.
        self._samplesPerChannel = 100

        ## @var numChannels
        #  This is the number of channels configured in the task.
        self._numChannels = 0

        ## This is the timeout in seconds for functions in the task to timeout.
        self.timeout = 1

        ## This is the mode of operation for the analog inputs.
        #
        #  There are currently three modes available.
        #  Static mode is where one static voltage is acquired with no need
        #  for a sample clock.
        #  Finite mode is where a finite number of voltages will be acquired 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.Static

    ## Initializes the analog inputs based on the object's configuration.
    #  @param self The object pointer.
    #  @param physicalChannel A string representing the device and analog
    #  input channels. Example Value: "PXI1Slot3/ao0:7"
    def init(self, physicalChannel):
        self.__createTask(physicalChannel)
        self.getNumChannels()
        self.initialized = True

        #Static Mode
        if self.mode == dutil.Mode.Static:
            self.setSampleRate(self._sampleRate)
            self.setSamplesPerChannel(1)

    def __createTask(self, physicalChannel):
        """
        This is a private method that creates the Task object for use inside the
        AnalogInput class."""
        terminalConfig = DAQmx_Val_Cfg_Default
        self.status = self.taskRef.CreateAIVoltageChan(physicalChannel, "",
                terminalConfig, -10, 10, DAQmx_Val_Volts, None)

    ## 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

    sampleRate = property(getSampleRate, setSampleRate)

    ## 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

    samplesPerChannel = property(getSamplesPerChannel, setSamplesPerChannel)

    ## 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 reads the data from the analogn input based on previous
    #  configuration.
    #  @param self The object reference.
    def read(self):
        timeout = float64(self.timeout)
        arraySize = uInt32(self._numChannels * self._samplesPerChannel)
        readArray = numpy.zeros((arraySize.value,), dtype = numpy.float64)
        samplesRead = int32()
        self.taskRef.ReadAnalogF64(self._samplesPerChannel, timeout,
                DAQmx_Val_GroupByChannel, readArray, arraySize,
                ctypes.byref(samplesRead), None) 
        return readArray
    
    ## 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 AnalogInput Class.
    #  @param self The object pointer.
    def __del__(self):
        if self.initialized:
            self.close()
Exemplo n.º 12
0
from PyDAQmx import Task
import numpy as np
import PyDAQmx
import matplotlib.pyplot as plt
ext_start_trigger = False

task = Task()

"""
task.CreateAIVoltageChan("Dev2/ai0", "",PyDAQmx.DAQmx_Val_RSE , -10.0, 10.0, PyDAQmx.DAQmx_Val_Volts, None)
task.CfgSampClkTiming("", 10000, PyDAQmx.DAQmx_Val_Rising, PyDAQmx.DAQmx_Val_FiniteSamps, 1000)

if ext_start_trigger:
    task.DAQmxCfgDigEdgeStartTrig("chan",  PyDAQmx.DAQmx_Val_Rising)
else:
    pass
    #task.DAQmxDisableStartTrig()
#task.AutoRegisterEveryNSamplesEvent(PyDAQmx.DAQmx_Val_Acquired_Into_Buffer, self.nsamples, 0)
#task.AutoRegisterDoneEvent(0)


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()
"""
#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()
AI_task.CreateAIVoltageChan("/Dev1/ai1", "", ni.DAQmx_Val_RSE, -10.0, 10.0,
                            ni.DAQmx_Val_Volts, None)

# In[37]:

# set analog input parameters
num_images = 1
num_AI_samples = num_AO_samples * num_images
AI_sample_rate = 20000
data = np.zeros((num_AI_samples, ), dtype=np.float64)
read = ni.int32()
#AI_task.StopTask()
AI_task.CfgSampClkTiming("OnboardClock", AI_sample_rate, ni.DAQmx_Val_Rising,
                         ni.DAQmx_Val_ContSamps, num_AI_samples)

AI_task.CfgDigEdgeStartTrig("/Dev1/PFI12", ni.DAQmx_Val_Rising)