Exemplo n.º 1
0
def init_dev(nchan, tc_types):
    interface = InterfaceType.USB
    tscale = TempScale.CELSIUS
    daq_list = get_daq_device_inventory(interface)
    ndev = len(daq_list)
    input_mode = AiInputMode.SINGLE_ENDED
    tc_dev = None
    ps_dev = None

    # Listing devices and finding USB-TC

    if ndev == 0:
        print('** No devices connected : terminating **')
        exit()
    else:
        str = '\nThe following USB devices are conected :-\n\n'
        for daq in daq_list:
            str += '%s' % (daq.product_name)
            str += '\t (%s)\n' % (daq.unique_id)
            if daq.product_name == 'USB-TC':
                tc_dev = DaqDevice(daq)
            elif daq.product_name == 'USB-201':
                ps_dev = DaqDevice(daq)
        print(str)
        if tc_dev == None:
            print('\n**USB-TC failed to connect**\n')
            exit(0)
        if ps_dev == None:
            print('\n**USB-201 failed to connect**\n')
            exit(0)

        # Connect TC device and get current info / configuration

        at_dev = tc_dev.get_ai_device()
        at_inf = at_dev.get_info()
        tc_dev.connect()
        at_cnf = at_dev.get_config()
        for c in range(nchan):
            at_cnf.set_chan_tc_type(c, tc_types[c])
            tc_typ = at_cnf.get_chan_tc_type(c)
            print('Channel %d is of TC type : %s' % (c, tc_typ.name))

        # Connect pressure sensor DAQ

        ap_dev = ps_dev.get_ai_device()
        ap_inf = ap_dev.get_info()
        ps_dev.connect()
        ap_cnf = ap_dev.get_config()
        ap_rng = ap_inf.get_ranges(input_mode)[0]

        ans = raw_input('\nPress RETURN to continue and Ctrl-C to stop\n')
    return tc_dev, at_dev, ps_dev, ap_dev, ap_rng
Exemplo n.º 2
0
 def get_radiacion(self):
     # Get a list of available DAQ devices
     devices = get_daq_device_inventory(InterfaceType.USB)
     # Create a DaqDevice Object and connect to the device
     daq_device = DaqDevice(devices[0])
     daq_device.connect()
     # Get AiDevice and AiInfo objects for the analog input subsystem
     ai_device = daq_device.get_ai_device()
     ai_info = ai_device.get_info()
     data = ai_device.a_in(1, AiInputMode.SINGLE_ENDED, Range.BIP10VOLTS,
                           AInFlag.DEFAULT)
     r = data / (80.86 * pow(10, -6))
     daq_device.disconnect()
     daq_device.release()
     return round(r, 2)
Exemplo n.º 3
0
 def get_temperatura(self):
     # Get a list of available DAQ devices
     devices = get_daq_device_inventory(InterfaceType.USB)
     # Create a DaqDevice Object and connect to the device
     daq_device = DaqDevice(devices[0])
     daq_device.connect()
     # Get AiDevice and AiInfo objects for the analog input subsystem
     ai_device = daq_device.get_ai_device()
     ai_info = ai_device.get_info()
     data = ai_device.a_in(0, AiInputMode.SINGLE_ENDED, Range.BIP10VOLTS,
                           AInFlag.DEFAULT)
     temp = data * -10
     #print'Temperatura ', round(temp, 2), "C"
     daq_device.disconnect()
     daq_device.release()
     return round(temp, 2)
Exemplo n.º 4
0
from uldaq import (get_daq_device_inventory, DaqDevice, InterfaceType,
                   AiInputMode, Range, AInFlag)
from math import pow
import time

try:
    # Get a list of available DAQ devices
    devices = get_daq_device_inventory(InterfaceType.USB)
    # Create a DaqDevice Object and connect to the device
    daq_device = DaqDevice(devices[0])
    daq_device.connect()
    # Get AiDevice and AiInfo objects for the analog input subsystem
    ai_device = daq_device.get_ai_device()
    ai_info = ai_device.get_info()

    while True:
        data = ai_device.a_in(0, AiInputMode.DIFFERENTIAL, Range.BIP10VOLTS,
                              AInFlag.DEFAULT)
        temp = data * -10
        #temp=-3.9257018186617643*-10
        print 'Temperatura ', round(temp, 2), "C"

        data = ai_device.a_in(1, AiInputMode.SINGLE_ENDED, Range.BIP10VOLTS,
                              AInFlag.DEFAULT)
        r = data / (80.86 * pow(10, -6))
        #r = 0.06733283546054736/ (80.86*(pow(10, -6)))
        print 'Radiacion ', round(r, 2), "W/m2"
        time.sleep(5)

    daq_device.disconnect()
    daq_device.release()
Exemplo n.º 5
0
def signal_processing(channel_total, srate, stime):
    low_channel = min(channel_total)
    high_channel = max(channel_total)
    num_scan_channels = high_channel - low_channel + 1
    srate = srate
    samples_per_channel = srate * stime
    data_buffer = create_float_buffer(num_scan_channels, samples_per_channel)
    range_index = 0
    descriptor_index = 0
    interface_type = InterfaceType.USB
    flags = AInScanFlag.DEFAULT
    input_mode = AiInputMode.SINGLE_ENDED
    scan_options = ScanOption.DEFAULTIO
    daq_device = None
    ai_device = None
    status = ScanStatus.IDLE
    try:
        # Get descriptors for all of the available DAQ devices.
        devices = get_daq_device_inventory(interface_type)
        number_of_devices = len(devices)
        if number_of_devices == 0:
            raise Exception('Error: No DAQ devices found')
        # Create the DAQ device object associated with the specified descriptor index.
        daq_device = DaqDevice(devices[descriptor_index])
        # Get the AiDevice object and verify that it is valid.
        ai_device = daq_device.get_ai_device()
        if ai_device is None:
            raise Exception(
                'Error: The DAQ device does not support analog input')
        # Verify that the specified device supports hardware pacing for analog input.
        ai_info = ai_device.get_info()
        if not ai_info.has_pacer():
            raise Exception(
                '\nError: The specified DAQ device does not support hardware paced analog input'
            )
        # Establish a connection to the DAQ device.
        descriptor = daq_device.get_descriptor()
        print('\nConnecting to', descriptor.dev_string, '- please wait...')
        daq_device.connect()
        ranges = ai_info.get_ranges(input_mode)
        if range_index >= len(ranges):
            range_index = len(ranges) - 1
        try:
            print('Start sampling...')
            rate = ai_device.a_in_scan(low_channel, high_channel, input_mode,
                                       Range.BIP5VOLTS, samples_per_channel,
                                       rate, scan_options, flags, data_buffer)
            print("mem = ", daq_device.get_info().get_mem_info())
            print('data scanning')
            datas = []
            ai_device.scan_wait(WaitType.WAIT_UNTIL_DONE, -1)
            for channel_number in channel_total:
                datas.append(data_buffer[channel_number::num_scan_channels])

        except (ValueError, NameError, SyntaxError):
            pass
    except Exception as e:
        print('\n', e)
    finally:
        # Stop the acquisition if it is still running.
        ai_device.scan_stop()
        daq_device.disconnect()
        daq_device.release()
        return datas
        print("get data finished")
Exemplo n.º 6
0
def main():
    daq_device = None

    descriptor_index = 0
    range_index = 0
    interface_type = InterfaceType.USB
    low_channel = 0
    high_channel = 3

    try:
        # Get descriptors for all of the available DAQ devices.
        devices = get_daq_device_inventory(interface_type)
        number_of_devices = len(devices)
        if number_of_devices == 0:
            raise Exception('Error: No DAQ devices found')

        print('Found', number_of_devices, 'DAQ device(s):')
        for i in range(number_of_devices):
            print('  ', devices[i].product_name, ' (', devices[i].unique_id, ')', sep='')

        # Create the DAQ device object associated with the specified descriptor index.
        daq_device = DaqDevice(devices[descriptor_index])

        # Get the AiDevice object and verify that it is valid.
        ai_device = daq_device.get_ai_device()
        if ai_device is None:
            raise Exception('Error: The DAQ device does not support analog input')

        # Establish a connection to the DAQ device.
        descriptor = daq_device.get_descriptor()
        print('\nConnecting to', descriptor.dev_string, '- please wait...')
        daq_device.connect()

        ai_info = ai_device.get_info()

        # The default input mode is SINGLE_ENDED.
        input_mode = AiInputMode.SINGLE_ENDED
        # If SINGLE_ENDED input mode is not supported, set to DIFFERENTIAL.
        if ai_info.get_num_chans_by_mode(AiInputMode.SINGLE_ENDED) <= 0:
            input_mode = AiInputMode.DIFFERENTIAL

        # Get the number of channels and validate the high channel number.
        number_of_channels = ai_info.get_num_chans_by_mode(input_mode)
        if high_channel >= number_of_channels:
            high_channel = number_of_channels - 1

        # Get a list of supported ranges and validate the range index.
        ranges = ai_info.get_ranges(input_mode)
        if range_index >= len(ranges):
            range_index = len(ranges) - 1

        print('\n', descriptor.dev_string, ' ready', sep='')
        print('    Function demonstrated: ai_device.a_in()')
        print('    Channels: ', low_channel, '-', high_channel)
        print('    Input mode: ', input_mode.name)
        print('    Range: ', ranges[range_index].name)
        try:
            input('\nHit ENTER to continue\n')
        except (NameError, SyntaxError):
            pass

        system('clear')

        try:
            while True:
                try:
                    reset_cursor()
                    print('Please enter CTRL + C to terminate the process\n')
                    print('Active DAQ device: ', descriptor.dev_string, ' (',
                          descriptor.unique_id, ')\n', sep='')

                    # Display data for the specified analog input channels.
                    for channel in range(low_channel, high_channel + 1):
                        data = ai_device.a_in(channel, input_mode, ranges[range_index], AInFlag.DEFAULT)
                        print('Channel(', channel, ') Data: ', '{:.6f}'.format(data), sep='')

                    sleep(0.1)
                except (ValueError, NameError, SyntaxError):
                    break
        except KeyboardInterrupt:
            pass

    except Exception as e:
        print('\n', e)

    finally:
        if daq_device:
            if daq_device.is_connected():
                daq_device.disconnect()
            daq_device.release()
def main():
    daq_device = None
    ai_device = None
    status = ScanStatus.IDLE

    descriptor_index = 0
    range_index = 0
    interface_type = InterfaceType.USB
    low_channel = 0
    high_channel = 3
    samples_per_channel = 10000
    rate = 100
    scan_options = ScanOption.DEFAULTIO | ScanOption.CONTINUOUS
    flags = AInScanFlag.DEFAULT

    try:
        # Get descriptors for all of the available DAQ devices.
        devices = get_daq_device_inventory(interface_type)
        number_of_devices = len(devices)
        if number_of_devices == 0:
            raise Exception('Error: No DAQ devices found')

        print('Found', number_of_devices, 'DAQ device(s):')
        for i in range(number_of_devices):
            print('  ',
                  devices[i].product_name,
                  ' (',
                  devices[i].unique_id,
                  ')',
                  sep='')

        # Create the DAQ device object associated with the specified descriptor index.
        daq_device = DaqDevice(devices[descriptor_index])

        # Get the AiDevice object and verify that it is valid.
        ai_device = daq_device.get_ai_device()
        if ai_device is None:
            raise Exception(
                'Error: The DAQ device does not support analog input')

        # Verify that the specified device supports hardware pacing for analog input.
        ai_info = ai_device.get_info()
        if not ai_info.has_pacer():
            raise Exception(
                '\nError: The specified DAQ device does not support hardware paced analog input'
            )

        # Establish a connection to the DAQ device.
        descriptor = daq_device.get_descriptor()
        print('\nConnecting to', descriptor.dev_string, '- please wait...')
        daq_device.connect()

        # The default input mode is SINGLE_ENDED.
        input_mode = AiInputMode.SINGLE_ENDED
        # If SINGLE_ENDED input mode is not supported, set to DIFFERENTIAL.
        if ai_info.get_num_chans_by_mode(AiInputMode.SINGLE_ENDED) <= 0:
            input_mode = AiInputMode.DIFFERENTIAL

        # Get the number of channels and validate the high channel number.
        number_of_channels = ai_info.get_num_chans_by_mode(input_mode)
        if high_channel >= number_of_channels:
            high_channel = number_of_channels - 1
        channel_count = high_channel - low_channel + 1

        # Get a list of supported ranges and validate the range index.
        ranges = ai_info.get_ranges(input_mode)
        if range_index >= len(ranges):
            range_index = len(ranges) - 1

        # Get a list of supported queue types.
        queue_types = ai_info.get_queue_types()
        if len(queue_types) == 0:
            raise Exception('Error: The device does not support a gain queue')

        # Assign each channel in the queue an input mode (SE/DIFF) and a range.  If multiple
        # ranges are supported, we will cycle through them and repeat ranges if the number
        # of channels exceeds the number of ranges.
        #
        # This block of code could be used to set other queue elements such as the input mode
        # and channel list.
        queue_list = []
        for i in range(channel_count):
            queue_element = AiQueueElement()
            queue_element.channel = i
            queue_element.input_mode = input_mode
            queue_element.range = ranges[range_index]

            queue_list.append(queue_element)

            range_index += 1
            if range_index >= len(ranges):
                range_index = 0

        # Load the queue.
        ai_device.a_in_load_queue(queue_list)

        data = create_float_buffer(channel_count, samples_per_channel)

        print('\n', descriptor.dev_string, ' ready', sep='')
        print('    Function demonstrated: ai_device.a_in_load_queue()')
        print('    Channels: ', low_channel, '-', high_channel)
        for i in range(channel_count):
            print('        Channel:', queue_list[i].channel, ', Input mode:',
                  AiInputMode(queue_list[i].input_mode).name, ', Range:',
                  Range(queue_list[i].range).name)
        print('    Samples per channel: ', samples_per_channel)
        print('    Rate: ', rate, 'Hz')
        print('    Scan options:', display_scan_options(scan_options))
        try:
            input('\nHit ENTER to continue\n')
        except (NameError, SyntaxError):
            pass

        # Start the acquisition.
        #
        # When using the queue, the low_channel, high_channel, input_mode, and range
        # parameters are ignored since they are specified in queue_array.
        rate = ai_device.a_in_scan(low_channel, high_channel, input_mode,
                                   ranges[range_index], samples_per_channel,
                                   rate, scan_options, flags, data)

        system('clear')

        try:
            while True:
                try:
                    # Get the status of the background operation
                    status, transfer_status = ai_device.get_scan_status()

                    reset_cursor()
                    print('Please enter CTRL + C to terminate the process\n')
                    print('Active DAQ device: ',
                          descriptor.dev_string,
                          ' (',
                          descriptor.unique_id,
                          ')\n',
                          sep='')

                    print('actual scan rate = ', '{:.6f}'.format(rate), 'Hz\n')

                    index = transfer_status.current_index
                    print('currentTotalCount = ',
                          transfer_status.current_total_count)
                    print('currentScanCount = ',
                          transfer_status.current_scan_count)
                    print('currentIndex = ', index, '\n')

                    # Display the data.
                    for i in range(channel_count):
                        print('chan =', i + low_channel, ': ',
                              '{:.6f}'.format(data[index + i]))

                    sleep(0.1)
                except (ValueError, NameError, SyntaxError):
                    break
        except KeyboardInterrupt:
            pass

    except Exception as e:
        print('\n', e)

    finally:
        if daq_device:
            # Stop the acquisition if it is still running.
            if status == ScanStatus.RUNNING:
                ai_device.scan_stop()
            if daq_device.is_connected():
                daq_device.disconnect()
            daq_device.release()
Exemplo n.º 8
0
def stream(low_channel, high_channel, sample_rate, data_file):
    """Analog input scan example."""
    daq_device = None
    ai_device = None
    status = ScanStatus.IDLE
    device_number = 0

    dt = 0.1  # how often save a chunk of data
    range_index = 0
    buffer_margin = 20
    interface_type = InterfaceType.ANY
    samples_per_channel = int(buffer_margin * dt * sample_rate)
    scan_options = ScanOption.CONTINUOUS
    flags = AInScanFlag.DEFAULT

    try:
        # Get descriptors for all of the available DAQ devices.
        devices = get_daq_device_inventory(interface_type)
        number_of_devices = len(devices)
        if number_of_devices == 0:
            raise RuntimeError('Error: No DAQ devices found')
        print('Found', number_of_devices, 'DAQ device(s):')
        print('using device', device_number)
        descriptor_index = device_number
        if descriptor_index not in range(number_of_devices):
            raise RuntimeError('Error: Invalid descriptor index')

        # Create the DAQ device from the descriptor at the specified index.
        daq_device = DaqDevice(devices[descriptor_index])

        # Get the AiDevice object and verify that it is valid.
        ai_device = daq_device.get_ai_device()
        if ai_device is None:
            raise RuntimeError('Error: The DAQ device does not support analog '
                               'input')

        # Verify the specified device supports hardware pacing for analog input.
        ai_info = ai_device.get_info()
        if not ai_info.has_pacer():
            raise RuntimeError('\nError: The specified DAQ device does not '
                               'support hardware paced analog input')

        # Establish a connection to the DAQ device.
        descriptor = daq_device.get_descriptor()
        print('\nConnecting to', descriptor.dev_string, '- please wait...')
        # For Ethernet devices using a connection_code other than the default
        # value of zero, change the line below to enter the desired code.
        try:
            daq_device.connect(connection_code=0)
        except TypeError:
            daq_device.connect()

        # The default input mode is SINGLE_ENDED.
        input_mode = AiInputMode.SINGLE_ENDED
        # If SINGLE_ENDED input mode is not supported, set to DIFFERENTIAL.
        if ai_info.get_num_chans_by_mode(AiInputMode.SINGLE_ENDED) <= 0:
            input_mode = AiInputMode.DIFFERENTIAL

        # Get the number of channels and validate the high channel number.
        number_of_channels = ai_info.get_num_chans_by_mode(input_mode)
        if high_channel >= number_of_channels:
            high_channel = number_of_channels - 1
        channel_count = high_channel - low_channel + 1

        # Get a list of supported ranges and validate the range index.
        ranges = ai_info.get_ranges(input_mode)
        if range_index >= len(ranges):
            range_index = len(ranges) - 1

        # Allocate a buffer to receive the data.0
        data = create_float_buffer(channel_count, samples_per_channel)

        print('\n', descriptor.dev_string, ' ready', sep='')
        print('    Function demonstsample_rated: ai_device.a_in_scan()')
        print('    Channels: ', low_channel, '-', high_channel)
        print('    Input mode: ', input_mode.name)
        print('    Range: ', ranges[range_index].name)
        print('    Samples per channel: ', samples_per_channel)
        print('    Rate: ', sample_rate, 'Hz')
        print('    Scan options:', display_scan_options(scan_options))

        # Start the acquisition.
        sample_rate = ai_device.a_in_scan(low_channel, high_channel,
                                          input_mode, ranges[range_index],
                                          samples_per_channel, sample_rate,
                                          scan_options, flags, data)

        print()
        print('acquiring data ..', end='')
        stdout.flush()

        with open(data_file, 'w') as f:

            save_count = 0
            last_save_index = 0
            buffer_size = samples_per_channel * channel_count

            while not done:

                # Get the status of the background operation
                status, transfer_status = ai_device.get_scan_status()
                current_index = transfer_status.current_index
                if current_index < 0:
                    continue
                num_to_save = (current_index -
                               last_save_index) % buffer_size + channel_count

                # Write data to file
                for i in range(num_to_save):
                    if i % channel_count == 0:
                        f.write('{} '.format(save_count))
                        save_count += 1
                    save_index = (last_save_index + i) % buffer_size
                    f.write('{}'.format(data[save_index]))
                    if i % channel_count == (channel_count - 1):
                        f.write('\n')
                    else:
                        f.write(' ')
                last_save_index = (current_index + channel_count) % buffer_size

                sleep(dt)
            print('done')

    except RuntimeError as error:
        print('\n', error)

    finally:
        if daq_device:
            # Stop the acquisition if it is still running.
            if status == ScanStatus.RUNNING:
                ai_device.scan_stop()
            if daq_device.is_connected():
                daq_device.disconnect()
            daq_device.release()
Exemplo n.º 9
0
def daq_setup(rate=500000, samples_per_channel=500000 * 10, resistor=0.1):
    """Analog input scan example."""
    global bench_over
    bench_over = False  # beginning of a new cycle
    daq_device = None
    status = ScanStatus.IDLE
    # samples_per_channel (int): the number of A/D samples to collect from each channel in the scan.
    # rate (float): A/D sample rate in samples per channel per second.

    range_index = 0
    interface_type = InterfaceType.ANY
    low_channel = 0
    high_channel = 0
    scan_options = ScanOption.CONTINUOUS
    flags = AInScanFlag.DEFAULT

    # Get descriptors for all of the available DAQ devices.
    devices = get_daq_device_inventory(interface_type)
    number_of_devices = len(devices)
    if number_of_devices == 0:
        raise RuntimeError('Error: No DAQ devices found')

    print('Found', number_of_devices, 'DAQ device(s):')
    for i in range(number_of_devices):
        print('  [',
              i,
              '] ',
              devices[i].product_name,
              ' (',
              devices[i].unique_id,
              ')',
              sep='')

    descriptor_index = 0
    if descriptor_index not in range(number_of_devices):
        raise RuntimeError('Error: Invalid descriptor index')

    # Create the DAQ device from the descriptor at the specified index.
    daq_device = DaqDevice(devices[descriptor_index])

    # Get the AiDevice object and verify that it is valid.
    ai_device = daq_device.get_ai_device()

    if ai_device is None:
        raise RuntimeError('Error: The DAQ device does not support analog '
                           'input')

    # Verify the specified device supports hardware pacing for analog input.
    ai_info = ai_device.get_info()

    if not ai_info.has_pacer():
        raise RuntimeError('\nError: The specified DAQ device does not '
                           'support hardware paced analog input')

    # Establish a connection to the DAQ device.
    descriptor = daq_device.get_descriptor()
    print('\nConnecting to', descriptor.dev_string, '- please wait...')
    # For Ethernet devices using a connection_code other than the default
    # value of zero, change the line below to enter the desired code.
    daq_device.connect(connection_code=0)

    # The default input mode is DIFFERENTIAL.
    input_mode = AiInputMode.DIFFERENTIAL

    # Get the number of channels and validate the high channel number.
    number_of_channels = ai_info.get_num_chans_by_mode(input_mode)

    if high_channel >= number_of_channels:
        high_channel = number_of_channels - 1
    channel_count = high_channel - low_channel + 1

    # Get a list of supported ranges and validate the range index.
    ranges = ai_info.get_ranges(input_mode)
    if range_index >= len(ranges):
        range_index = len(ranges) - 1
    meas_range = ranges[1]

    data_dir = "data_dir"
    if not os.path.isdir(data_dir):
        os.mkdir(data_dir)

    # define name of a datafile and delete if it exists in the data directory
    data_fname = "test_data"
    #if os.path.isfile(os.path.join(data_dir, data_fname)):
    #os.remove(os.path.join(data_dir, data_fname))

    # Allocate a buffer to receive the data.
    data = create_float_buffer(channel_count, samples_per_channel)
    # ranges[1] = Range.BIP5VOLTS

    return daq_device, low_channel, high_channel, input_mode, meas_range, samples_per_channel, rate, scan_options, flags, data, data_dir, data_fname
def main():
    daq_device = None
    ai_device = None
    status = ScanStatus.IDLE

    descriptor_index = 0
    range_index = 0
    iepe_mode = IepeMode.ENABLED
    coupling = CouplingMode.AC
    sensor_sensitivity = 1.0  # volts per unit
    interface_type = InterfaceType.USB
    low_channel = 0
    high_channel = 3
    samples_per_channel = 10000
    rate = 100
    scan_options = ScanOption.CONTINUOUS
    flags = AInScanFlag.DEFAULT

    try:
        # Get descriptors for all of the available DAQ devices.
        devices = get_daq_device_inventory(interface_type)
        number_of_devices = len(devices)

        # Verify at least one DAQ device is detected.
        if number_of_devices == 0:
            raise Exception('Error: No DAQ devices found')

        print('Found', number_of_devices, 'DAQ device(s):')
        for i in range(number_of_devices):
            print('  ',
                  devices[i].product_name,
                  ' (',
                  devices[i].unique_id,
                  ')',
                  sep='')

        # Create a DaqDevice object from the first descriptor.
        daq_device = DaqDevice(devices[descriptor_index])

        # Get the AiDevice object and verify that it is valid.
        ai_device = daq_device.get_ai_device()
        if ai_device is None:
            raise Exception(
                'Error: The DAQ device does not support analog input')

        # Verify the device supports hardware pacing for analog input.
        ai_info = ai_device.get_info()
        if not ai_info.has_pacer():
            raise Exception('Error: The DAQ device does not support hardware ',
                            'paced analog input')

        # Verify the device supports IEPE
        if not ai_info.supports_iepe():
            raise Exception('Error: The DAQ device does not support IEPE')

        # Establish a connection to the DAQ device.
        descriptor = daq_device.get_descriptor()
        print('\nConnecting to', descriptor.dev_string, '- please wait...')
        daq_device.connect()

        # The default input mode is SINGLE_ENDED.
        input_mode = AiInputMode.SINGLE_ENDED
        # If SINGLE_ENDED input mode is not supported, set to DIFFERENTIAL.
        if ai_info.get_num_chans_by_mode(AiInputMode.SINGLE_ENDED) <= 0:
            input_mode = AiInputMode.DIFFERENTIAL

        # Get the number of channels and validate the high channel number.
        number_of_channels = ai_info.get_num_chans_by_mode(input_mode)
        if high_channel >= number_of_channels:
            high_channel = number_of_channels - 1
        channel_count = high_channel - low_channel + 1

        # Get a list of supported ranges and validate the range index.
        ranges = ai_info.get_ranges(input_mode)
        if range_index >= len(ranges):
            range_index = len(ranges) - 1

        # Set IEPE mode, AC coupling and sensor sensitivity for each channel
        ai_config = ai_device.get_config()
        for chan in range(low_channel, high_channel + 1):
            ai_config.set_chan_iepe_mode(chan, iepe_mode)
            ai_config.set_chan_coupling_mode(chan, coupling)
            ai_config.set_chan_sensor_sensitivity(chan, sensor_sensitivity)

        data = create_float_buffer(channel_count, samples_per_channel)

        print('\n', descriptor.dev_string, ' ready', sep='')
        print('    Function demonstrated: ai_device.a_in_scan()')
        print('    Channels: ', low_channel, '-', high_channel)
        print('    Input mode: ', input_mode.name)
        print('    Range: ', ranges[range_index].name)
        print('    Samples per channel: ', samples_per_channel)
        print('    Rate: ', rate, 'Hz')
        print('    Scan options:', display_scan_options(scan_options))
        print('    Sensor Sensitivity: {:.6f}'.format(sensor_sensitivity),
              '(V/unit)')
        try:
            input('\nHit ENTER to continue\n')
        except (NameError, SyntaxError):
            pass

        system('clear')

        rate = ai_device.a_in_scan(low_channel, high_channel, input_mode,
                                   ranges[range_index], samples_per_channel,
                                   rate, scan_options, flags, data)

        try:
            while True:
                try:
                    status, transfer_status = ai_device.get_scan_status()

                    index = transfer_status.current_index
                    if index >= 0:
                        system('clear')
                        print('Please enter CTRL + C to terminate the process',
                              '\n')
                        print('Active DAQ device: ',
                              descriptor.dev_string,
                              ' (',
                              descriptor.unique_id,
                              ')\n',
                              sep='')
                        print('Actual scan rate = {:.6f}\n'.format(rate))
                        print('currentTotalCount = ',
                              transfer_status.current_total_count)
                        print('currentScanCount = ',
                              transfer_status.current_scan_count)
                        print('currentIndex = ', index, '\n')

                        for i in range(channel_count):
                            print('chan ', i + low_channel, ' = ',
                                  '{:.6f}'.format(data[index + i]))

                    sleep(0.1)
                except (ValueError, NameError, SyntaxError):
                    break
        except KeyboardInterrupt:
            pass

    except Exception as e:
        print('\n', e)

    finally:
        if daq_device:
            # Stop the acquisition if it is still running.
            if status == ScanStatus.RUNNING:
                ai_device.scan_stop()
            if daq_device.is_connected():
                daq_device.disconnect()
            daq_device.release()
def main():
    global rate
    daq_device = None
    ai_device = None
    ai_info = None

    descriptor_index = 0
    range_index = 0
    interface_type = InterfaceType.USB
    low_channel = 0
    high_channel = 3
    samples_per_channel = 10000
    rate = 100
    flags = AInScanFlag.DEFAULT
    event_types = (DaqEventType.ON_DATA_AVAILABLE
                   | DaqEventType.ON_END_OF_INPUT_SCAN
                   | DaqEventType.ON_INPUT_SCAN_ERROR)

    ScanParams = namedtuple('ScanParams',
                            'buffer high_chan low_chan descriptor status')

    # set the scan options for a FINITE scan ... to set the scan options for
    # a continuous scan, uncomment the line that or's the SO_CONTINUOUS option
    # into to the scanOptions variable
    scan_options = ScanOption.DEFAULTIO
    # scan_options |= ScanOption.CONTINUOUS

    try:
        # Get descriptors for all of the available DAQ devices.
        devices = get_daq_device_inventory(interface_type)
        number_of_devices = len(devices)
        if number_of_devices == 0:
            raise Exception('Error: No DAQ devices found')

        print('Found', number_of_devices, 'DAQ device(s):')
        for i in range(number_of_devices):
            print('  ',
                  devices[i].product_name,
                  ' (',
                  devices[i].unique_id,
                  ')',
                  sep='')

        # Create the DAQ device object from the specified descriptor index.
        daq_device = DaqDevice(devices[descriptor_index])

        # Get the AiDevice object and verify that it is valid.
        ai_device = daq_device.get_ai_device()
        if ai_device is None:
            raise Exception('Error: The DAQ device does not support analog '
                            'input')

        # Verify the device supports hardware pacing for analog input.
        ai_info = ai_device.get_info()
        if not ai_info.has_pacer():
            raise Exception(
                '\nError: The specified DAQ device does not support'
                ' hardware paced analog input')

        # Establish a connection to the DAQ device.
        descriptor = daq_device.get_descriptor()
        print('\nConnecting to', descriptor.dev_string, '- please wait...')
        daq_device.connect()

        # The default input mode is SINGLE_ENDED.
        input_mode = AiInputMode.SINGLE_ENDED
        # If SINGLE_ENDED input mode is not supported, set to DIFFERENTIAL.
        if ai_info.get_num_chans_by_mode(AiInputMode.SINGLE_ENDED) <= 0:
            input_mode = AiInputMode.DIFFERENTIAL

        # Get the number of channels and validate the high channel number.
        number_of_channels = ai_info.get_num_chans_by_mode(input_mode)
        if high_channel >= number_of_channels:
            high_channel = number_of_channels - 1
        channel_count = high_channel - low_channel + 1

        # Get a list of supported ranges and validate the range index.
        ranges = ai_info.get_ranges(input_mode)
        if range_index >= len(ranges):
            range_index = len(ranges) - 1

        # Allocate a buffer to receive the data.
        data = create_float_buffer(channel_count, samples_per_channel)

        # Store the user data for use in the callback function.
        scan_status = {'complete': False, 'error': False}
        user_data = ScanParams(data, high_channel, low_channel, descriptor,
                               scan_status)

        # Enable the event to be notified every time 100 samples are available.
        available_sample_count = 100
        daq_device.enable_event(event_types, available_sample_count,
                                event_callback_function, user_data)

        print('\n', descriptor.dev_string, 'ready', sep='')
        print('    Function demonstrated: daq_device.enable_event()')
        print('    Channels: ', low_channel, '-', high_channel)
        print('    Input mode: ', input_mode.name)
        print('    Range: ', ranges[range_index].name)
        print('    Samples per channel: ', samples_per_channel)
        print('    Rate: ', rate, 'Hz')
        print('    Scan options:', display_scan_options(scan_options))
        try:
            input('\nHit ENTER to continue\n')
        except (NameError, SyntaxError):
            pass

        system('clear')

        # Start the finite acquisition.
        rate = ai_device.a_in_scan(low_channel, high_channel, input_mode,
                                   ranges[range_index], samples_per_channel,
                                   rate, scan_options, flags, data)

        # Wait here until the scan is done ... events will be handled in the
        # event handler (eventCallbackFunction).
        # The scan_status values are set in the event handler callback.
        while not scan_status['complete'] and not scan_status['error']:
            sleep(0.1)

    except KeyboardInterrupt:
        pass
    except (ValueError, NameError, SyntaxError):
        pass
    except Exception as e:
        print('\n', e)
    finally:
        if daq_device:
            if daq_device.is_connected():
                # Stop the acquisition if it is still running.
                if ai_device and ai_info and ai_info.has_pacer():
                    ai_device.scan_stop()
                daq_device.disable_event(event_types)
                daq_device.disconnect()
            daq_device.release()
Exemplo n.º 12
0
def main():
    daq_device = None

    descriptor_index = 0
    interface_type = InterfaceType.USB
    low_channel = 0
    high_channel = 3
    scale = TempScale.CELSIUS

    try:
        # Get descriptors for all of the available DAQ devices.
        devices = get_daq_device_inventory(interface_type)
        number_of_devices = len(devices)
        if number_of_devices == 0:
            raise Exception('Error: No DAQ devices found')

        print('Found', number_of_devices, 'DAQ device(s):')
        for i in range(number_of_devices):
            print('  ',
                  devices[i].product_name,
                  ' (',
                  devices[i].unique_id,
                  ')',
                  sep='')

        # Create the DAQ device object for the specified descriptor index.
        daq_device = DaqDevice(devices[descriptor_index])

        # Get the AiDevice object and verify that it is valid.
        ai_device = daq_device.get_ai_device()
        if ai_device is None:
            raise Exception(
                'Error: The DAQ device does not support analog input')

        # Verify that the DAQ device has temperature channels.
        ai_info = ai_device.get_info()
        chan_types = ai_info.get_chan_types()
        if (AiChanType.TC not in chan_types
                and AiChanType.RTD not in chan_types
                and AiChanType.SEMICONDUCTOR not in chan_types
                and AiChanType.THERMISTOR not in chan_types):
            raise Exception(
                'Error: The DAQ device does not support temperature channels')

        # Verify the DAQ device has the specified number of channels
        number_of_channels = ai_info.get_num_chans()
        if high_channel >= number_of_channels:
            high_channel = number_of_channels - 1

        # Establish a connection to the DAQ device.
        descriptor = daq_device.get_descriptor()
        print('\nConnecting to', descriptor.dev_string, '- please wait...')
        daq_device.connect()

        print('\n', descriptor.dev_string, ' ready', sep='')
        print('    Function demonstrated: ai_device.t_in()')
        print('    Channels: ', low_channel, '-', high_channel)
        # Display channel configuration information.
        ai_config = ai_device.get_config()
        for chan in range(low_channel, high_channel + 1):
            # Set the specified analog channels to TC type if the specified
            # DAQ device is a USB-2408 or USB-2416 device
            if (descriptor.product_id == USB_2416_ID
                    or descriptor.product_id == USB_2416_4AO_ID
                    or descriptor.product_id == USB_2408_ID
                    or descriptor.product_id == USB_2408_2AO_ID):
                ai_config.set_chan_type(chan, AiChanType.TC)

            chan_type = -1
            chan_type_str = 'N/A'
            try:
                chan_type = ai_config.get_chan_type(chan)
                chan_type_str = chan_type.name
            except ULException as ul_error:
                if ul_error.error_code != ULError.CONFIG_NOT_SUPPORTED:
                    raise ul_error

            if chan_type == AiChanType.TC:
                tc_type = ai_config.get_chan_tc_type(chan)
                chan_type_str += ' Type ' + tc_type.name
            elif (chan_type == AiChanType.RTD
                  or chan_type == AiChanType.THERMISTOR):
                connect_type = ai_config.get_chan_sensor_connection_type(chan)
                chan_type_str += ' ' + connect_type.name
            print('        Channel', chan, 'type:', chan_type_str)
        print('    Temperature scaling:', scale.name)

        try:
            input('\nHit ENTER to continue\n')
        except (NameError, SyntaxError):
            pass

        system('clear')

        try:
            while True:
                try:
                    display_strings = []
                    # Read data for the specified analog input channels.
                    for channel in range(low_channel, high_channel + 1):
                        try:
                            data = ai_device.t_in(channel, scale)
                            display_strings.append('Channel(' + str(channel) +
                                                   ') Data: ' +
                                                   '{:10.6f}'.format(data))
                        except ULException as ul_error:
                            if ul_error.error_code == ULError.OPEN_CONNECTION:
                                display_strings.append('Channel(' +
                                                       str(channel) +
                                                       ') Data: ' +
                                                       'Open Connection')
                            else:
                                raise ul_error

                    reset_cursor()
                    print('Please enter CTRL + C to terminate the process\n')
                    print('Active DAQ device: ',
                          descriptor.dev_string,
                          ' (',
                          descriptor.unique_id,
                          ')\n',
                          sep='')

                    # Display data for the specified analog input channels.
                    for display_string in display_strings:
                        clear_eol()
                        print(display_string)

                    sleep(0.3)
                except (ValueError, NameError, SyntaxError):
                    break

        except KeyboardInterrupt:
            pass

    except Exception as e:
        print('\n', e)

    finally:
        if daq_device:
            if daq_device.is_connected():
                daq_device.disconnect()
            daq_device.release()
Exemplo n.º 13
0
def main(data_write_mode = ''):
    daq_device = None
    ai_device = None
    status = ScanStatus.IDLE

    descriptor_index = 0
    range_index = 0
    interface_type = InterfaceType.USB
    low_channel = 0
    high_channel = 0
    rate = 100000                # Samples/second/channel
    buffer_length = 200000
    f_transmit = 36000          # fundamental frequency of transmitter
    channel_num = high_channel-low_channel+1
    samples_per_channel = int(float(buffer_length)/float(channel_num))
    file_length = 2             # Seconds
    rows_of_data = (float(file_length)/((float(buffer_length)/2)/(float(rate)*float(channel_num))))*((float(buffer_length)/2)/float(channel_num))
    scan_options = ScanOption.CONTINUOUS
    flags = AInScanFlag.DEFAULT

    #CONTROL ALGORITHM PARAMETERS:
    velocity = 1    #tune speed
    beta = 0.01        #tune turning
    heading = 0
    past_freq = f_transmit
    dH = -1.0001

    try:
        # Get descriptors for all of the available DAQ devices.
        devices = get_daq_device_inventory(interface_type)
        number_of_devices = len(devices)
        if number_of_devices == 0:
            raise Exception('Error: No DAQ devices found')

        print('Found', number_of_devices, 'DAQ device(s):')
        for i in range(number_of_devices):
            print('  ', devices[i].product_name, ' (', devices[i].unique_id, ')', sep='')

        # Create the DAQ device object associated with the specified descriptor index.
        daq_device = DaqDevice(devices[descriptor_index])

        # Get the AiDevice object and verify that it is valid.
        ai_device = daq_device.get_ai_device()
        if ai_device is None:
            raise Exception('Error: The DAQ device does not support analog input')

        # Verify that the specified device supports hardware pacing for analog input.
        ai_info = ai_device.get_info()
        if not ai_info.has_pacer():
            raise Exception('\nError: The specified DAQ device does not support hardware paced analog input')

        # Establish a connection to the DAQ device.
        descriptor = daq_device.get_descriptor()
        print('\nConnecting to', descriptor.dev_string, '- please wait...')
        daq_device.connect()

        # The default input mode is SINGLE_ENDED.
        input_mode = AiInputMode.SINGLE_ENDED
        # If SINGLE_ENDED input mode is not supported, set to DIFFERENTIAL.
        if ai_info.get_num_chans_by_mode(AiInputMode.SINGLE_ENDED) <= 0:
            input_mode = AiInputMode.DIFFERENTIAL

        # Get the number of channels and validate the high channel number.
        number_of_channels = ai_info.get_num_chans_by_mode(input_mode)
        if high_channel >= number_of_channels:
            high_channel = number_of_channels - 1
        channel_count = high_channel - low_channel + 1

        # Get a list of supported ranges and validate the range index.
        ranges = ai_info.get_ranges(input_mode)
        if range_index >= len(ranges):
            range_index = len(ranges) - 1

        # Allocate a buffer to receive the data.
        data = create_float_buffer(channel_count, samples_per_channel)

        print('\n', descriptor.dev_string, ' ready', sep='')
        print('    Function demonstrated: ai_device.a_in_scan()')
        print('    Channels: ', low_channel, '-', high_channel)
        print('    Input mode: ', input_mode.name)
        print('    Range: ', ranges[range_index].name)
        print('    Samples per channel: ', samples_per_channel)
        print('    Rate: ', rate, 'Hz')
        print('    Scan options:', display_scan_options(scan_options))
        print("    Output File Rows:" +str(rows_of_data))

        try:
            input('\nHit ENTER to continue\n')
        except (NameError, SyntaxError):
            pass
        system('clear')
        print('\nHit ^C to exit\n')

        #Set up threshold for where the dumps should occur in the buffer
        #Currently configured for dumping half of the buffer
        threshold = (float(len(data))/2) - (float(len(data))/2)%channel_count
        data_range = [range(int(threshold)),range(int(threshold),len(data))]

        #Setting up whether or not to write in binary mode
        write_mode = 'w'+data_write_mode

        # Start the acquisition.
        rate = ai_device.a_in_scan(low_channel, high_channel, input_mode, ranges[range_index], samples_per_channel,
                                   rate, scan_options, flags, data)
        #open first text file
        start=time.time()
        f=open('./data/'+'{:.6f}'.format(start)+".txt",write_mode)

        try:
            past_index = -1         #Initiated at -1 to because index is -1 until buffer is written to
            while True:
                #Get the status of the background operation
                status, transfer_status = ai_device.get_scan_status()

                #Make new file after fixed amount of time set by 'file_length'
                if time.time()-start>=file_length:
                    f.close
                    start=time.time()
                    f=open('./data/'+'{:.6f}'.format(start)+".txt",write_mode)

                #get current index in filling the buffer to know when to clear it
                index = transfer_status.current_index

                #write half buffer to txt file, find max freq, and update heading if buffer fills past halfway point
                if past_index<=threshold and index>threshold:
                    #dumps data
                    data_fft, data_dump = dump_data(f, data, data_range[0], channel_count)
                    #find fundamental frequency within 500Hz of f_transmit
                    freq = fourier_analysis(data_fft,rate,f_transmit,500)
                    #new heading
                    past_freq, heading, dH = heading_adjust(freq, past_freq, beta, heading, dH)
                    print('HEADING: %s     FREQ: %d    dH: %d' %(str(heading), past_freq,dH))

                    nav_solution(dH,heading)

                #write half buffer to txt file, find max freq, and update heading if buffer filled to end and is overwriting first half
                if past_index>index:
                    #dumps data
                    data_fft, data_dump = dump_data(f, data, data_range[1], channel_count)
                    #find fundamental frequency within 500Hz of f_transmit
                    freq = fourier_analysis(data_fft,rate,f_transmit,500)
                    #new heading
                    past_freq, heading, dH = heading_adjust(freq, past_freq, beta, heading, dH)
                    print('HEADING: %s     FREQ: %d    dH: %d' %(str(heading), past_freq,dH))

                    nav_solution(dH,heading)

                past_index = index

        except KeyboardInterrupt:
            pass

    except Exception as e:
        print('\n', e)

    finally:
        if daq_device:
            # Stop the acquisition if it is still running.
            if status == ScanStatus.RUNNING:
                ai_device.scan_stop()
            if daq_device.is_connected():
                daq_device.disconnect()
            daq_device.release()
Exemplo n.º 14
0
def main():
    daq_device = None
    ai_device = None
    status = ScanStatus.IDLE

    descriptor_index = 0
    range_index = 0
    trigger_type_index = 0
    interface_type = InterfaceType.USB
    low_channel = 0
    high_channel = 3
    samples_per_channel = 10000
    rate = 100
    scan_options = ScanOption.CONTINUOUS | ScanOption.EXTTRIGGER
    flags = AInScanFlag.DEFAULT

    try:
        # Get descriptors for all of the available DAQ devices.
        devices = get_daq_device_inventory(interface_type)
        number_of_devices = len(devices)
        if number_of_devices == 0:
            raise Exception('Error: No DAQ devices found')

        print('Found', number_of_devices, 'DAQ device(s):')
        for i in range(number_of_devices):
            print('  ', devices[i].product_name, ' (', devices[i].unique_id, ')', sep='')

        # Create the DAQ device object associated with the specified descriptor index.
        daq_device = DaqDevice(devices[descriptor_index])

        # Get the AiDevice object and verify that it is valid.
        ai_device = daq_device.get_ai_device()
        if ai_device is None:
            raise Exception('Error: The DAQ device does not support analog input')

        # Verify that the specified device supports hardware pacing for analog input.
        ai_info = ai_device.get_info()
        if not ai_info.has_pacer():
            raise Exception('\nError: The specified DAQ device does not support hardware paced analog input')

        # Establish a connection to the DAQ device.
        descriptor = daq_device.get_descriptor()
        print('\nConnecting to', descriptor.dev_string, '- please wait...')
        daq_device.connect()

        # The default input mode is SINGLE_ENDED.
        input_mode = AiInputMode.SINGLE_ENDED
        # If SINGLE_ENDED input mode is not supported, set to DIFFERENTIAL.
        if ai_info.get_num_chans_by_mode(AiInputMode.SINGLE_ENDED) <= 0:
            input_mode = AiInputMode.DIFFERENTIAL

        # Get the number of channels and validate the high channel number.
        number_of_channels = ai_info.get_num_chans_by_mode(input_mode)
        if high_channel >= number_of_channels:
            high_channel = number_of_channels - 1
        channel_count = high_channel - low_channel + 1

        # Get a list of supported ranges and validate the range index.
        ranges = ai_info.get_ranges(input_mode)
        if range_index >= len(ranges):
            range_index = len(ranges) - 1

        # Get a list of trigger types.
        trigger_types = ai_info.get_trigger_types()
        if len(trigger_types) == 0:
            raise Exception('Error: The device does not support an external trigger')

        # Set the trigger.
        #
        # This example uses the default values for setting the trigger so there is no need to call this function.
        # If you want to change the trigger type (or any other trigger parameter), uncomment this function call and
        # change the trigger type (or any other parameter)
        ai_device.set_trigger(trigger_types[trigger_type_index], 0, 0, 0, 0)

        data = create_float_buffer(channel_count, samples_per_channel)

        print('\n', descriptor.dev_string, ' ready', sep='')
        print('    Function demonstrated: ai_device.set_trigger()')
        print('    Channels: ', low_channel, '-', high_channel)
        print('    Input mode: ', input_mode.name)
        print('    Range: ', ranges[range_index].name)
        print('    Samples per channel: ', samples_per_channel)
        print('    Rate: ', rate, 'Hz')
        print('    Scan options:', display_scan_options(scan_options))
        print('    Trigger type:', trigger_types[trigger_type_index].name)
        try:
            input('\nHit ENTER to continue\n')
        except (NameError, SyntaxError):
            pass

        system('clear')

        ai_device.a_in_scan(low_channel, high_channel, input_mode, ranges[range_index], samples_per_channel, rate,
                            scan_options, flags, data)

        print('Please enter CTRL + C to quit waiting for trigger\n')
        print('Waiting for trigger ...\n')

        try:
            while True:
                try:
                    status, transfer_status = ai_device.get_scan_status()

                    index = transfer_status.current_index
                    if index >= 0:
                        system('clear')
                        print('Please enter CTRL + C to terminate the process\n')
                        print('Active DAQ device: ', descriptor.dev_string,
                              ' (', descriptor.unique_id, ')\n', sep='')

                        print('currentTotalCount = ',  transfer_status.current_total_count)
                        print('currentScanCount = ',  transfer_status.current_scan_count)
                        print('currentIndex = ',  index, '\n')

                        for i in range(channel_count):
                            print('chan =',
                                  i + low_channel, ': ',
                                  '{:.6f}'.format(data[index + i]))

                    sleep(0.1)
                except (ValueError, NameError, SyntaxError):
                    break
        except KeyboardInterrupt:
            pass

    except Exception as e:
        print('\n', e)

    finally:
        if daq_device:
            # Stop the acquisition if it is still running.
            if status == ScanStatus.RUNNING:
                ai_device.scan_stop()
            if daq_device.is_connected():
                daq_device.disconnect()
            daq_device.release()
Exemplo n.º 15
0
class DAQ:
    def __init__(self, options, cb):
        self.serial = options['serial']
        self.rate = int(options['rate'])
        self.samples_per_channel = int(options['samples_per_channel'])
        self.low_channel = int(options['low_channel'])
        self.high_channel = int(options['high_channel'])
        self.channel_count = int(self.high_channel) - int(self.low_channel) + 1
        self.flags = AInScanFlag.DEFAULT
        self.scan_option = ScanOption.CONTINUOUS
        self.event_types = DaqEventType.ON_DATA_AVAILABLE | DaqEventType.ON_END_OF_INPUT_SCAN | DaqEventType.ON_INPUT_SCAN_ERROR
        self.ScanParams = namedtuple('ScanParams', 'buffer high_chan low_chan')
        self.event_callback = cb
        self.status = ScanStatus
        self.daq_device = None
        self.ai_device = None
        self.data = None
        self.input_mode = None
        self.scan_event_parameters_daq = None
        self.range = options['range']

    def configure_mode(self, mode):
        if mode == "DIFFERENTIAL":
            self.input_mode = AiInputMode.DIFFERENTIAL
        elif mode == "SINGLE_ENDED":
            self.input_mode = AiInputMode.SINGLE_ENDED

        if self.range == '1':
            self.range = Range.BIP1VOLTS
        elif self.range == '2':
            self.range = Range.BIP2VOLTS
        elif self.range == '4':
            self.range = Range.BIP4VOLTS
        elif self.range == '5':
            self.range = Range.BIP5VOLTS
        elif self.range == '10':
            self.range = Range.BIP10VOLTS
        elif self.range == '20':
            self.range = Range.BIP20VOLTS
        elif self.range == '15':
            self.range = Range.BIP15VOLTS
        elif self.range == '30':
            self.range = Range.BIP30VOLTS
        elif self.range == '60':
            self.range = Range.BIP60VOLTS

    def initialize(self):
        connected_devices = get_daq_device_inventory(InterfaceType.USB)
        number_of_devices = len(connected_devices)

        if number_of_devices == 0:
            raise Exception(
                'OLYMPUS: RUNTIME ERROR - DAQ DEVICE NOT CONNECTED')

        for daqs in connected_devices:
            if daqs.unique_id == self.serial:
                self.daq_device = DaqDevice(daqs)
                self.ai_device = self.daq_device.get_ai_device()
                self.daq_device.connect()

        self.daq_data = create_float_buffer(self.channel_count,
                                            self.samples_per_channel)
        self.scan_event_parameters_daq = self.ScanParams(
            self.daq_data, self.high_channel, self.low_channel)

        return True

    def begin_acquisition(self):
        self.daq_device.enable_event(
            self.event_types, self.channel_count * self.samples_per_channel,
            self.event_callback, self.scan_event_parameters_daq)

        self.ai_device.a_in_scan(self.low_channel, self.high_channel,
                                 self.input_mode, self.range,
                                 self.samples_per_channel, self.rate,
                                 self.scan_option, self.flags, self.daq_data)