Exemplo n.º 1
0
def single_channel_scan(channel=0):
	global size
	global rate

	address = select_hat_device(HatIDs.MCC_118)
	hat = mcc118(address)

	channels = [channel]
	channel_mask = chan_list_to_mask(channels)
	options = OptionFlags.DEFAULT

	hat.a_in_scan_start(channel_mask, size, rate, options)					# size, rate
	raw = hat.a_in_scan_read(size, size/rate+1)						# size, rate
	hat.a_in_scan_cleanup()

	raw_data = np.array(raw.data)
	fft_data = fftpack.fft(raw_data)
	fft_data = np.abs(fft_data[0:size]) * 2 / (0.6 * size)
	fft_data = fft_data[:len(fft_data)/2]

	return raw_data, fft_data
Exemplo n.º 2
0
 def acq_start(self):
     """
     def acq_start(self):
         acqusition start
     """
     
     
     channel_mask = chan_list_to_mask(self.ai_ch)
     
     if self.mode =='continuous':
         samples_per_channel = 0
         options = OptionFlags.CONTINUOUS    
                     
         self.hat.a_in_scan_start(channel_mask, samples_per_channel, self.scan_rate,options)                 
         self.record_cont()
         
         
     elif self.mode=='trigger':
         samples_per_channel = self.read_request_size
         options = OptionFlags.EXTTRIGGER
         trigger_mode = TriggerModes.RISING_EDGE
         
         self.hat.trigger_mode(trigger_mode)
         
         self.hat.a_in_scan_start(channel_mask, samples_per_channel, self.scan_rate,options) 
         self.record_withtrigger()
         
     elif self.mode =='finite':
         samples_per_channel = self.read_request_size
         options = OptionFlags.DEFAULT
         self.hat.a_in_scan_start(channel_mask, samples_per_channel, self.scan_rate,options) 
         self.record_N_sample()
         
         
     else:
         print('not implmented\n')
         raise      
     self.worker.clear_datflag()
Exemplo n.º 3
0
def main():
    """
    This function is executed automatically when the module is run directly.
    """
    # Store the channels in a list and convert the list to a channel mask that
    # can be passed as a parameter to the MCC 118 functions.
    channels = [0, 1, 2, 3]
    channel_mask = chan_list_to_mask(channels)
    num_channels = len(channels)

    samples_per_channel = 10000
    scan_rate = 1000.0
    options = OptionFlags.EXTTRIGGER
    trigger_mode = TriggerModes.RISING_EDGE

    try:
        # Select an MCC 118 HAT device to use.
        address = select_hat_device(HatIDs.MCC_118)
        hat = mcc118(address)

        print('\nSelected MCC 118 HAT device at address', address)

        actual_scan_rate = hat.a_in_scan_actual_rate(num_channels, scan_rate)

        print('\nMCC 118 continuous scan example')
        print('    Functions demonstrated:')
        print('         mcc118.trigger_mode')
        print('         mcc118.a_in_scan_status')
        print('         mcc118.a_in_scan_start')
        print('         mcc118.a_in_scan_read')
        print('    Channels: ', end='')
        print(', '.join([str(chan) for chan in channels]))
        print('    Requested scan rate: ', scan_rate)
        print('    Actual scan rate: ', actual_scan_rate)
        print('    Samples per channel', samples_per_channel)
        print('    Options: ', enum_mask_to_string(OptionFlags, options))
        print('    Trigger Mode: ', trigger_mode.name)

        #try:
        #input('\nPress ENTER to continue ...')
        #except (NameError, SyntaxError):
        #pass

        hat.trigger_mode(trigger_mode)

        # Configure and start the scan.
        hat.a_in_scan_start(channel_mask, samples_per_channel, scan_rate,
                            options)

        try:
            # wait for the external trigger to occur
            print('\nWaiting for trigger ... hit Ctrl-C to cancel the trigger')
            wait_for_trigger(hat)

            print('\nStarting scan ... Press Ctrl-C to stop\n')

            # Display the header row for the data table.
            print('Samples Read    Scan Count', end='')
            for chan in channels:
                print('    Channel ', chan, sep='', end='')
            print('')

            read_and_display_data(hat, samples_per_channel, num_channels)

        except KeyboardInterrupt:
            # Clear the '^C' from the display.
            print(CURSOR_BACK_2, ERASE_TO_END_OF_LINE, '\n')

    except (HatError, ValueError) as err:
        print('\n', err)
Exemplo n.º 4
0
def main():  # pylint: disable=too-many-locals, too-many-statements
    """
    This function is executed automatically when the module is run directly.
    """
    # Store the channels in a list and convert the list to a channel mask that
    # can be passed as a parameter to the MCC 172 functions.
    channels = [0, 1]
    channel_mask = chan_list_to_mask(channels)
    num_channels = len(channels)

    samples_per_channel = 10000
    scan_rate = 10240.0
    options = OptionFlags.EXTTRIGGER
    trigger_mode = TriggerModes.RISING_EDGE

    try:
        # Select an MCC 172 HAT device to use.
        address = select_hat_device(HatIDs.MCC_172)
        hat = mcc172(address)

        print('\nSelected MCC 172 HAT device at address', address)

        # Turn on IEPE supply?
        iepe_enable = get_iepe()

        for channel in channels:
            hat.iepe_config_write(channel, iepe_enable)

        # Configure the clock and wait for sync to complete.
        hat.a_in_clock_config_write(SourceType.LOCAL, scan_rate)

        synced = False
        while not synced:
            (_source_type, actual_scan_rate,
             synced) = hat.a_in_clock_config_read()
            if not synced:
                sleep(0.005)

        print('\nMCC 172 continuous scan example')
        print('    Functions demonstrated:')
        print('         mcc172.trigger_mode')
        print('         mcc172.a_in_clock_config_write')
        print('         mcc172.a_in_clock_config_read')
        print('         mcc172.a_in_scan_start')
        print('         mcc172.a_in_scan_read')
        print('         mcc172.a_in_scan_stop')
        print('         mcc172.a_in_scan_cleanup')
        print('    IEPE power: ', end='')
        if iepe_enable == 1:
            print('on')
        else:
            print('off')
        print('    Channels: ', end='')
        print(', '.join([str(chan) for chan in channels]))
        print('    Requested scan rate: ', scan_rate)
        print('    Actual scan rate: ', actual_scan_rate)
        print('    Samples per channel', samples_per_channel)
        print('    Options: ', enum_mask_to_string(OptionFlags, options))
        print('    Trigger Mode: ', trigger_mode.name)

        try:
            input('\nPress ENTER to continue ...')
        except (NameError, SyntaxError):
            pass

        hat.trigger_config(SourceType.LOCAL, trigger_mode)

        # Configure and start the scan.
        hat.a_in_scan_start(channel_mask, samples_per_channel, options)

        try:
            # wait for the external trigger to occur
            print('\nWaiting for trigger ... hit Ctrl-C to cancel the trigger')
            wait_for_trigger(hat)

            print('\nStarting scan ... Press Ctrl-C to stop\n')

            # Display the header row for the data table.
            print('Samples Read    Scan Count', end='')
            for chan in channels:
                print('       Channel ', chan, sep='', end='')
            print('')

            read_and_display_data(hat, samples_per_channel, num_channels)

        except KeyboardInterrupt:
            # Clear the '^C' from the display.
            print(CURSOR_BACK_2, ERASE_TO_END_OF_LINE, '\n')
            hat.a_in_scan_stop()

        hat.a_in_scan_cleanup()

    except (HatError, ValueError) as err:
        print('\n', err)
Exemplo n.º 5
0
def main():
    """
    This function is executed automatically when the module is run directly.
    """

    # Store the channels in a list and convert the list to a channel mask that
    # can be passed as a parameter to the MCC 118 functions.

    no_of_channels = 1  # Creates the list of channels.
    channels = np.ndarray.tolist(np.arange((no_of_channels), dtype=int))
    channel_mask = chan_list_to_mask(channels)
    num_channels = len(channels)

    samples = 4000
    if (num_channels % 2) == 0:
        samples_per_channel = int(samples / num_channels)
    else:
        samples_per_channel = int(mt.ceil(samples / num_channels))

    scan_rate = 4000
    options = OptionFlags.DEFAULT
    timeout = 10.0

    try:
        # Select an MCC 118 HAT device to use.
        address = select_hat_device(HatIDs.MCC_118)
        hat = mcc118(address)

        print('\nSelected MCC 118 HAT device at address', address)

        actual_scan_rate = hat.a_in_scan_actual_rate(num_channels, scan_rate)

        print('\nMCC 118 continuous scan example')
        print('    Functions demonstrated:')
        print('         mcc118.a_in_scan_start')
        print('         mcc118.a_in_scan_read')
        print('    Channels: ', end='')
        print(', '.join([str(chan) for chan in channels]))
        print('    Requested scan rate: ', scan_rate)
        print('    Actual scan rate: ', actual_scan_rate)
        print('    Samples per channel', samples_per_channel)
        print('    Options: ', enum_mask_to_string(OptionFlags, options))

        #try:
        #input('\nPress ENTER to continue ...')
        #except (NameError, SyntaxError):
        #pass

        # Configure and start the scan.
        hat.a_in_scan_start(channel_mask, samples_per_channel, scan_rate,
                            options)

        print('Starting scan ... Press Ctrl-C to stop\n')
        """Try reading when scanning?"""
        read_output = hat.a_in_scan_read_numpy(
            samples_per_channel * num_channels,
            timeout)  # Changed the sampling size to create even arrays
        chan_data = np.zeros([samples_per_channel, num_channels])
        chan_title = []

        ####  NEW CODE ###################################################################

        for i in range(num_channels):
            for j in range(samples_per_channel):
                if j == 0:
                    y = str('Channel') + ' ' + str(i)
                    chan_title.append(str(y))
            if i < samples_per_channel - num_channels:
                chan_data[:, i] = read_output[i::num_channels]

        chan_final = np.concatenate((np.reshape(np.array(chan_title),
                                                (1, num_channels)), chan_data),
                                    axis=0)
        np.savetxt('foo.csv', chan_final, fmt='%5s', delimiter=',')

        ########################################################################################
        """
        for i in range (num_channels):
            for j in range (samples_per_channel):
                if j==0:
                    y = str("Channel") + " " + str(i)
                    chan_data.append(y)#[i,j] = str("Channel") + " " + str(i)
            x= read_output.data[i]
            chan_data.append(x)
            #chan_data[:,i] = read_output.data[i]
        chan_data2 = np.asarray(chan_data, dtype = str)
        print(y)
        print(x)
        print(chan_data2)
        f = open("bar.txt", "a")
        f.write(chan_data2)
        f.close   
        #np.savetxt("foo.csv", chan_data, delimiter=",")
        """

        # Display the header row for the data table.
        print('Samples Read    Scan Count', end='')
        for chan in channels:
            print('    Channel ', chan, sep='', end='')
        print('')

        try:
            read_and_display_data(hat, samples_per_channel, num_channels)

        except KeyboardInterrupt:
            # Clear the '^C' from the display.
            print(CURSOR_BACK_2, ERASE_TO_END_OF_LINE, '\n')

    except (HatError, ValueError) as err:
        print('\n', err)
Exemplo n.º 6
0
def fswtl():
    # Update Status
    status.config(text="Running...")
    status.update()
    """The following implementation of looping the triggered scan is not big, nor clever, but was the only
    way I could find of making it work.  Set loop to run while i < 6 but never actually iterate i (i'm a bad person).
    Because of this there's no clean way to exit the loop, as the UI window is frozen whenever any of this background
    code is running"""
    i = 1
    while i < 6:
        """This function is executed automatically when the module is run directly.
           """

        # Store the channels in a list and convert the list to a channel mask that
        # can be passed as a parameter to the MCC 118 functions.
        no_of_channels = int(chanvar.get())  # Creates the list of channels.
        channels = np.ndarray.tolist(np.arange((no_of_channels), dtype=int))
        channel_mask = chan_list_to_mask(channels)
        num_channels = len(channels)

        samples_per_channel = int(
            float(totvar.get()) / 1000 * int(ratevar.get()))

        if (num_channels % 2) == 0:
            samples = int(samples_per_channel * num_channels)
        else:
            samples = int(mt.ceil(samples_per_channel * num_channels))

        scan_rate = int(ratevar.get())
        options = OptionFlags.EXTTRIGGER
        trigger_mode = TriggerModes.ACTIVE_HIGH
        timeout = 5.0

        try:
            # Select an MCC 118 HAT device to use.
            address = select_hat_device(HatIDs.MCC_118)
            hat = mcc118(address)

            print('\nSelected MCC 118 HAT device at address', address)

            actual_scan_rate = hat.a_in_scan_actual_rate(
                num_channels, scan_rate)

            print('\nMCC 118 continuous scan example')
            print('    Functions demonstrated:')
            print('         mcc118.trigger_mode')
            print('         mcc118.a_in_scan_status')
            print('         mcc118.a_in_scan_start')
            print('         mcc118.a_in_scan_read')
            print('    Channels: ', end='')
            print(', '.join([str(chan) for chan in channels]))
            print('    Requested scan rate: ', scan_rate)
            print('    Actual scan rate: ', actual_scan_rate)
            print('    Samples per channel', samples_per_channel)
            print('    Options: ', enum_mask_to_string(OptionFlags, options))
            print('    Trigger Mode: ', trigger_mode.name)

            hat.trigger_mode(trigger_mode)

            # Configure and start the scan.
            hat.a_in_scan_start(channel_mask, samples_per_channel, scan_rate,
                                options)

            try:
                # wait for the external trigger to occur
                print(
                    '\nWaiting for trigger ... hit Ctrl-C to cancel the trigger'
                )
                status.config(text="Waiting...")
                status.update()
                wait_for_trigger(hat)

                print('\nStarting scan ... Press Ctrl-C to stop\n')
                status.config(text="Triggered")
                status.update()
                """read complete output data and place int array"""
                read_output = hat.a_in_scan_read_numpy(samples_per_channel,
                                                       timeout)
                """create a blank array"""
                chan_data = np.zeros([samples_per_channel, num_channels])
                """create title array"""
                chan_title = []
                force_data = read_output.data * 12
                """iterate through the array per channel to split out every other
                sample into the correct column"""

                for i in range(num_channels):
                    for j in range(samples_per_channel):
                        if j == 0:
                            y = str('Channel') + ' ' + str(i)
                            chan_title.append(str(y))
                    if i < samples_per_channel - num_channels:
                        chan_data[:, i] = force_data[i::num_channels]

                print('Iterated through loop\n')

                chan_final = np.concatenate(
                    (np.reshape(np.array(chan_title),
                                (1, num_channels)), chan_data),
                    axis=0)
                #np.savetxt('foo.csv', chan_final, fmt='%5s', delimiter=',')

                now = datetime.datetime.now()
                ID = int(idvar.get())
                force = float("{0:.2f}".format(max(read_output.data) * 12))
                t = temperature()
                temp = t[0]

                print(force)
                print(temp)

                # read the cycle count from the number set in the UI
                cyc = int(counter.get())

                # upload stuff to database
                database_upload(now, ID, force, t, cyc)

                hat.a_in_scan_stop()
                hat.a_in_scan_cleanup()

                # Counter stepping
                counter.set(counter.get() + 1)

                # counter value is stored in a text file so can be edited offline
                # open the text file and update the number for the next loop
                f = open('count.txt', 'w')
                f.write(str(counter.get()))
                f.close()

                #plot(force_data)
                resultswindow(force, t)

            except KeyboardInterrupt:
                # Clear the '^C' from the display.
                print(CURSOR_BACK_2, ERASE_TO_END_OF_LINE, '\n')

        except (HatError, ValueError) as err:
            print('\n', err)
Exemplo n.º 7
0
while True:

    # start time
    import time
    t = time.time()
    '''-------------------------------------------------------M C C 1 1 8   S C A N-----------------------------------------------------'''

    from daqhats import mcc118, OptionFlags, HatIDs, HatError
    from daqhats_utils import select_hat_device, chan_list_to_mask

    address = select_hat_device(HatIDs.MCC_118)
    hat = mcc118(address)

    channels = [0]
    channel_mask = chan_list_to_mask(channels)
    sample_size = 2048
    rate = 10000
    options = OptionFlags.DEFAULT

    request = sample_size
    timeout = 3

    hat.a_in_scan_start(channel_mask, sample_size, rate, options)
    raw = hat.a_in_scan_read(request, timeout)
    hat.a_in_scan_cleanup()

    if len(raw.data) == sample_size:
        '''----------------------------------------------F F T /  F F T   P E A K S-------------------------------------------------'''

        import numpy as np
Exemplo n.º 8
0
def main():  # pylint: disable=too-many-locals, too-many-statements
    """
    This function is executed automatically when the module is run directly.
    """

    # Store the channels in a list and convert the list to a channel mask that
    # can be passed as a parameter to the MCC 172 functions.
    channels = [0, 1]
    channel_mask = chan_list_to_mask(channels)
    num_channels = len(channels)

    samples_per_channel = 0

    options = OptionFlags.CONTINUOUS

    scan_rate = 10240.0

    try:
        # Select an MCC 172 HAT device to use.
        address = select_hat_device(HatIDs.MCC_172)
        hat = mcc172(address)

        print('\nSelected MCC 172 HAT device at address', address)

        # Turn on IEPE supply?
        iepe_enable = get_iepe()

        for channel in channels:
            hat.iepe_config_write(channel, iepe_enable)

        # Configure the clock and wait for sync to complete.
        hat.a_in_clock_config_write(SourceType.LOCAL, scan_rate)

        synced = False
        while not synced:
            (_source_type, actual_scan_rate,
             synced) = hat.a_in_clock_config_read()
            if not synced:
                sleep(0.005)

        print('\nMCC 172 continuous scan example')
        print('    Functions demonstrated:')
        print('         mcc172.iepe_config_write')
        print('         mcc172.a_in_clock_config_write')
        print('         mcc172.a_in_clock_config_read')
        print('         mcc172.a_in_scan_start')
        print('         mcc172.a_in_scan_read')
        print('         mcc172.a_in_scan_stop')
        print('         mcc172.a_in_scan_cleanup')
        print('    IEPE power: ', end='')
        if iepe_enable == 1:
            print('on')
        else:
            print('off')
        print('    Channels: ', end='')
        print(', '.join([str(chan) for chan in channels]))
        print('    Requested scan rate: ', scan_rate)
        print('    Actual scan rate: ', actual_scan_rate)
        print('    Options: ', enum_mask_to_string(OptionFlags, options))

        try:
            input('\nPress ENTER to continue ...')
        except (NameError, SyntaxError):
            pass

        # Configure and start the scan.
        # Since the continuous option is being used, the samples_per_channel
        # parameter is ignored if the value is less than the default internal
        # buffer size (10000 * num_channels in this case). If a larger internal
        # buffer size is desired, set the value of this parameter accordingly.
        hat.a_in_scan_start(channel_mask, samples_per_channel, options)

        print('Starting scan ... Press Ctrl-C to stop\n')

        # Display the header row for the data table.
        print('Samples Read    Scan Count', end='')
        for chan, item in enumerate(channels):
            print('       Channel ', item, sep='', end='')
        print('')

        try:
            read_and_display_data(hat, num_channels)

        except KeyboardInterrupt:
            # Clear the '^C' from the display.
            print(CURSOR_BACK_2, ERASE_TO_END_OF_LINE, '\n')
            print('Stopping')

            hat.a_in_scan_stop()
            hat.a_in_scan_cleanup()

            # Turn off IEPE supply
            for channel in channels:
                hat.iepe_config_write(channel, 0)

    except (HatError, ValueError) as err:
        print('\n', err)
Exemplo n.º 9
0
def main():
    """
    This function is executed automatically when the module is run directly.
    """

    # Store the channels in a list and convert the list to a channel mask that
    # can be passed as a parameter to the MCC 118 functions.
    no_of_channels = 1  # Creates the list of channels.
    channels = np.ndarray.tolist(np.arange((no_of_channels), dtype=int))
    channel_mask = chan_list_to_mask(channels)
    num_channels = len(channels)

    samples_per_channel = 4000
    if (num_channels % 2) == 0:
        samples = int(samples_per_channel * num_channels)
    else:
        samples = int(mt.ceil(samples_per_channel * num_channels))

    scan_rate = 4000
    options = OptionFlags.DEFAULT
    timeout = 10.0

    try:
        # Select an MCC 118 HAT device to use.
        address = select_hat_device(HatIDs.MCC_118)
        hat = mcc118(address)

        print('\nSelected MCC 118 HAT device at address', address)

        actual_scan_rate = hat.a_in_scan_actual_rate(num_channels, scan_rate)

        print('\nMCC 118 continuous scan example')
        print('    Functions demonstrated:')
        print('         mcc118.a_in_scan_start')
        print('         mcc118.a_in_scan_read')
        print('    Channels: ', end='')
        print(', '.join([str(chan) for chan in channels]))
        print('    Requested scan rate: ', scan_rate)
        print('    Actual scan rate: ', actual_scan_rate)
        print('    Samples per channel', samples_per_channel)
        print('    Options: ', enum_mask_to_string(OptionFlags, options))

        #try:
        #input('\nPress ENTER to continue ...')
        #except (NameError, SyntaxError):
        #pass

        # Configure and start the scan.
        hat.a_in_scan_start(channel_mask, samples_per_channel, scan_rate,
                            options)

        print('Starting scan ... Press Ctrl-C to stop\n')
        """read complete output data and place int array"""
        read_output = hat.a_in_scan_read_numpy(samples_per_channel, timeout)
        """create a blank array"""
        chan_data = np.zeros([samples_per_channel, num_channels])
        """create title array"""
        chan_title = []
        force_data = read_output.data * 12
        """iterate through the array per channel to split out every other
        sample into the correct column"""

        for i in range(num_channels):
            for j in range(samples_per_channel):
                if j == 0:
                    y = str('Channel') + ' ' + str(i)
                    chan_title.append(str(y))
            if i < samples_per_channel - num_channels:
                chan_data[:, i] = force_data[i::num_channels]

        print('Iterated through loop\n')

        chan_final = np.concatenate((np.reshape(np.array(chan_title),
                                                (1, num_channels)), chan_data),
                                    axis=0)
        np.savetxt('foo.csv', chan_final, fmt='%5s', delimiter=',')

        now = datetime.datetime.now()
        ID = 2
        Force = np.float(max(chan_data))
        t1, t2 = temperature()

        print(Force)
        print(t1)
        print(t2)
        #database_upload(now, ID, Force, Temp)
        # Display the header row for the data table.
        #print('Samples Read    Scan Count', end='')
        #for chan in channels:
        #print('    Channel ', chan, sep='', end='')
        #print('')

        #try:
        #read_and_display_data(hat, samples_per_channel, num_channels)

        #except KeyboardInterrupt:
        # Clear the '^C' from the display.
        #print(CURSOR_BACK_2, ERASE_TO_END_OF_LINE, '\n')

    except (HatError, ValueError) as err:
        print('\n', err)
Exemplo n.º 10
0
def main(): # pylint: disable=too-many-locals, too-many-statements
    """
    This function is executed automatically when the module is run directly.
    """

    channels = [0, 1]
    channel_mask = chan_list_to_mask(channels)

    samples_per_channel = 12800
    scan_rate = 51200.0
    options = OptionFlags.DEFAULT

    try:
        # Select an MCC 172 HAT device to use.
        address = select_hat_device(HatIDs.MCC_172)
        hat = mcc172(address)

        print('\nSelected MCC 172 HAT device at address', address)

        # Turn on IEPE supply?
        iepe_enable = get_iepe()

        for channel in channels:
            hat.iepe_config_write(channel, iepe_enable)

        # Configure the clock and wait for sync to complete.
        hat.a_in_clock_config_write(SourceType.LOCAL, scan_rate)

        synced = False
        while not synced:
            (_source_type, actual_scan_rate, synced) = hat.a_in_clock_config_read()
            if not synced:
                sleep(0.005)

        print('\nMCC 172 Multi channel FFT example')
        print('    Functions demonstrated:')
        print('         mcc172.iepe_config_write')
        print('         mcc172.a_in_clock_config_write')
        print('         mcc172.a_in_clock_config_read')
        print('         mcc172.a_in_scan_start')
        print('         mcc172.a_in_scan_read_numpy')
        print('         mcc172.a_in_scan_stop')
        print('         mcc172.a_in_scan_cleanup')
        print('    IEPE power: ', end='')
        if iepe_enable == 1:
            print('on')
        else:
            print('off')
        print('    Channels: ', end='')
        print(', '.join([str(chan) for chan in channels]))
        print('    Requested scan rate: ', scan_rate)
        print('    Actual scan rate: ', actual_scan_rate)
        print('    Samples per channel', samples_per_channel)
        print('    Options: ', enum_mask_to_string(OptionFlags, options))

        try:
            input('\nPress ENTER to continue ...')
        except (NameError, SyntaxError):
            pass

        # Configure and start the scan.
        hat.a_in_scan_start(channel_mask, samples_per_channel, options)

        print('Starting scan ... Press Ctrl-C to stop\n')

        try:
            read_and_display_data(hat, channels, samples_per_channel,
                                  actual_scan_rate)

        except KeyboardInterrupt:
            # Clear the '^C' from the display.
            print(CURSOR_BACK_2, ERASE_TO_END_OF_LINE, '\n')
            hat.a_in_scan_stop()

        hat.a_in_scan_cleanup()

    except (HatError, ValueError) as err:
        print('\n', err)
def main():  # pylint: disable=too-many-locals, too-many-statements, too-many-branches
    """
    This function is executed automatically when the module is run directly.
    """
    hats = []
    # Define the channel list for each HAT device
    chans = [{0, 1}, {0, 1}]
    # Define the options for each HAT device
    options = [OptionFlags.EXTTRIGGER, OptionFlags.EXTTRIGGER]
    samples_per_channel = 10000
    sample_rate = 10240.0  # Samples per second
    trigger_mode = TriggerModes.RISING_EDGE

    try:
        # Get an instance of the selected hat device object.
        hats = select_hat_devices(HatIDs.MCC_172, DEVICE_COUNT)

        # Validate the selected channels.
        for i, hat in enumerate(hats):
            validate_channels(chans[i], hat.info().NUM_AI_CHANNELS)

        # Turn on IEPE supply?
        iepe_enable = get_iepe()

        for i, hat in enumerate(hats):
            for channel in chans[i]:
                # Configure IEPE.
                hat.iepe_config_write(channel, iepe_enable)
            if hat.address() != MASTER:
                # Configure the slave clocks.
                hat.a_in_clock_config_write(SourceType.SLAVE, sample_rate)
                # Configure the trigger.
                hat.trigger_config(SourceType.SLAVE, trigger_mode)

        # Configure the master clock and start the sync.
        hats[MASTER].a_in_clock_config_write(SourceType.MASTER, sample_rate)
        synced = False
        while not synced:
            (_source_type, actual_rate, synced) = \
                hats[MASTER].a_in_clock_config_read()
            if not synced:
                sleep(0.005)

        # Configure the master trigger.
        hats[MASTER].trigger_config(SourceType.MASTER, trigger_mode)

        print('MCC 172 multiple HAT example using external clock and',
              'external trigger options')
        print('    Functions demonstrated:')
        print('         mcc172.trigger_mode')
        print('         mcc172.a_in_clock_config_write')
        print('         mcc172.a_in_clock_config_read')
        print('         mcc172.a_in_scan_start')
        print('         mcc172.a_in_scan_read')
        print('         mcc172.a_in_scan_stop')
        print('         mcc172.a_in_scan_cleanup')
        print('    IEPE power: ', end='')
        if iepe_enable == 1:
            print('on')
        else:
            print('off')
        print('    Samples per channel:', samples_per_channel)
        print('    Requested Sample Rate: {:.3f} Hz'.format(sample_rate))
        print('    Actual Sample Rate: {:.3f} Hz'.format(actual_rate))
        print('    Trigger type:', trigger_mode.name)

        for i, hat in enumerate(hats):
            print('    HAT {}:'.format(i))
            print('      Address:', hat.address())
            print('      Channels: ', end='')
            print(', '.join([str(chan) for chan in chans[i]]))
            options_str = enum_mask_to_string(OptionFlags, options[i])
            print('      Options:', options_str)

        print(
            '\n*NOTE: Connect a trigger source to the TRIG input terminal on HAT 0.'
        )

        try:
            input("\nPress 'Enter' to continue")
        except (NameError, SyntaxError):
            pass

        # Start the scan.
        for i, hat in enumerate(hats):
            chan_mask = chan_list_to_mask(chans[i])
            hat.a_in_scan_start(chan_mask, samples_per_channel, options[i])

        print('\nWaiting for trigger ... Press Ctrl-C to stop scan\n')

        try:
            # Monitor the trigger status on the master device.
            wait_for_trigger(hats[MASTER])
            # Read and display data for all devices until scan completes
            # or overrun is detected.
            read_and_display_data(hats, chans)

        except KeyboardInterrupt:
            # Clear the '^C' from the display.
            print(CURSOR_BACK_2, ERASE_TO_END_OF_LINE, '\nAborted\n')

    except (HatError, ValueError) as error:
        print('\n', error)

    finally:
        for hat in hats:
            hat.a_in_scan_stop()
            hat.a_in_scan_cleanup()
Exemplo n.º 12
0
def fs():
    # Update Status
    status.config(text="Running...")
    status.update()
    """
        This function is executed automatically when the module is run directly.
        """

    # Store the channels in a list and convert the list to a channel mask that
    # can be passed as a parameter to the MCC 118 functions.
    no_of_channels = int(chanvar.get())  # Creates the list of channels.
    channels = np.ndarray.tolist(np.arange((no_of_channels), dtype=int))
    channel_mask = chan_list_to_mask(channels)
    num_channels = len(channels)

    samples_per_channel = int(float(totvar.get()) / 1000 * int(ratevar.get()))
    if (num_channels % 2) == 0:
        samples = int(samples_per_channel * num_channels)
    else:
        samples = int(mt.ceil(samples_per_channel * num_channels))

    scan_rate = int(ratevar.get())
    options = OptionFlags.DEFAULT
    timeout = 10.0

    try:
        # Select an MCC 118 HAT device to use.
        address = select_hat_device(HatIDs.MCC_118)
        hat = mcc118(address)

        print('\nSelected MCC 118 HAT device at address', address)

        actual_scan_rate = hat.a_in_scan_actual_rate(num_channels, scan_rate)

        print('\nMCC 118 continuous scan example')
        print('    Functions demonstrated:')
        print('         mcc118.a_in_scan_start')
        print('         mcc118.a_in_scan_read')
        print('    Channels: ', end='')
        print(', '.join([str(chan) for chan in channels]))
        print('    Requested scan rate: ', scan_rate)
        print('    Actual scan rate: ', actual_scan_rate)
        print('    Samples per channel', samples_per_channel)
        print('    Options: ', enum_mask_to_string(OptionFlags, options))

        # Configure and start the scan.
        hat.a_in_scan_start(channel_mask, samples_per_channel, scan_rate,
                            options)

        try:
            print('Starting scan ... Press Ctrl-C to stop\n')
            status.config(text="Scanning...")
            status.update()

            """read complete output data and place int array"""
            read_output = hat.a_in_scan_read_numpy(samples_per_channel, timeout)
            """create a blank array"""
            chan_data = np.zeros([samples_per_channel, num_channels])
            """create title array"""
            chan_title = []
            force_data = read_output.data * 12
            """iterate through the array per channel to split out every other
            sample into the correct column"""

            for i in range(num_channels):
                for j in range(samples_per_channel):
                    if j == 0:
                        y = str('Channel') + ' ' + str(i)
                        chan_title.append(str(y))
                if i < samples_per_channel - num_channels:
                    chan_data[:, i] = force_data[i::num_channels]

            print('Iterated through loop\n')

            chan_final = np.concatenate((np.reshape(np.array(chan_title), (1, num_channels)), chan_data), axis=0)
            np.savetxt('foo.csv', chan_final, fmt='%5s', delimiter=',')

            now = datetime.datetime.now()
            ID = int(idvar.get())
            Force = float("{0:.2f}".format(max(force_data)))
            Temp = temperature()

            hat.a_in_scan_stop()
            hat.a_in_scan_cleanup()

            print(Force)
            print(Temp)
            database_upload(now, ID, Force, Temp)

            Plot(force_data)
            ResultsWindow(Force, Temp)

            # Update Status
            status.config(text="Finished...")
            status.update()
            
        except KeyboardInterrupt:
            # Clear the '^C' from the display.
            print(CURSOR_BACK_2, ERASE_TO_END_OF_LINE, '\n')

    except (HatError, ValueError) as err:
        print('\n', err)
Exemplo n.º 13
0
def fswtl():
    # Update Status
    status.config(text="Running...")
    status.update()

    i = 1
    while i < 6:
        """This function is executed automatically when the module is run directly.
           """

        # Store the channels in a list and convert the list to a channel mask that
        # can be passed as a parameter to the MCC 118 functions.
        no_of_channels = int(chanvar.get())  # Creates the list of channels.
        channels = np.ndarray.tolist(np.arange((no_of_channels), dtype=int))
        channel_mask = chan_list_to_mask(channels)
        num_channels = len(channels)

        samples_per_channel = int(float(totvar.get()) / 1000 * int(ratevar.get()))

        if (num_channels % 2) == 0:
            samples = int(samples_per_channel * num_channels)
        else:
            samples = int(mt.ceil(samples_per_channel * num_channels))

        scan_rate = int(ratevar.get())
        options = OptionFlags.EXTTRIGGER
        trigger_mode = TriggerModes.ACTIVE_HIGH
        timeout = 5.0

        try:
            # Select an MCC 118 HAT device to use.
            address = select_hat_device(HatIDs.MCC_118)
            hat = mcc118(address)

            hat.trigger_mode(trigger_mode)

            # Configure and start the scan.
            hat.a_in_scan_start(channel_mask, samples_per_channel, scan_rate,
                                options)

            try:
                # wait for the external trigger to occur
                print('\nWaiting for trigger ... hit Ctrl-C to cancel the trigger')
                status.config(text="Waiting...")
                status.update()
                wait_for_trigger(hat)

                print('\nStarting scan ... Press Ctrl-C to stop\n')
                status.config(text="Triggered")
                status.update()

                """read complete output data and place int array"""
                read_output = hat.a_in_scan_read_numpy(samples_per_channel, timeout)
                """create a blank array"""
                chan_data = np.zeros([samples_per_channel, num_channels])
                """create title array"""
                chan_title = []
                force_data = read_output.data * 12
                """iterate through the array per channel to split out every other
                sample into the correct column"""

                for i in range(num_channels):
                    for j in range(samples_per_channel):
                        if j == 0:
                            y = str('Channel') + ' ' + str(i)
                            chan_title.append(str(y))
                    if i < samples_per_channel - num_channels:
                        chan_data[:, i] = force_data[i::num_channels]

                print('Iterated through loop\n')



                now = datetime.datetime.now()
                ID = int(idvar.get())
                Force = float("{0:.2f}".format(max(read_output.data) * 12))
                t = temperature()

                Cyc = int(counter.get())

                database_upload(now, ID, Force, t, Cyc)

                hat.a_in_scan_stop()
                hat.a_in_scan_cleanup()

                # Counter stepping
                counter.set(counter.get() + 1)
                f = open('count.txt', 'w')
                f.write(str(counter.get()))
                f.close()

                ResultsWindow(Force, t)

            except KeyboardInterrupt:
                # Clear the '^C' from the display.
                print(CURSOR_BACK_2, ERASE_TO_END_OF_LINE, '\n')

        except (HatError, ValueError) as err:
            print('\n', err)
Exemplo n.º 14
0
def fs():
    # Update Status
    status.config(text="Running...")
    status.update()
    """
        This function is executed automatically when the module is run directly.
        """

    # Store the channels in a list and convert the list to a channel mask that
    # can be passed as a parameter to the MCC 118 functions.
    no_of_channels = int(chanvar.get())  # Creates the list of channels.
    channels = np.ndarray.tolist(np.arange((no_of_channels), dtype=int))
    channel_mask = chan_list_to_mask(channels)
    num_channels = len(channels)

    samples_per_channel = int(float(totvar.get()) / 1000 * int(ratevar.get()))
    if (num_channels % 2) == 0:
        samples = int(samples_per_channel * num_channels)
    else:
        samples = int(mt.ceil(samples_per_channel * num_channels))

    scan_rate = int(ratevar.get())
    options = OptionFlags.DEFAULT
    timeout = 10.0

    try:
        # Select an MCC 118 HAT device to use.
        address = select_hat_device(HatIDs.MCC_118)
        hat = mcc118(address)

        # Configure and start the scan.
        hat.a_in_scan_start(channel_mask, samples_per_channel, scan_rate,
                            options)

        try:
            print('Starting scan ... Press Ctrl-C to stop\n')
            status.config(text="Scanning...")
            status.update()

            """read complete output data and place int array"""
            read_output = hat.a_in_scan_read_numpy(samples_per_channel, timeout)
            """create a blank array"""
            chan_data = np.zeros([samples_per_channel, num_channels])
            """create title array"""
            chan_title = []
            force_data = read_output.data * 12
            """iterate through the array per channel to split out every other
            sample into the correct column"""

            for i in range(num_channels):
                for j in range(samples_per_channel):
                    if j == 0:
                        y = str('Channel') + ' ' + str(i)
                        chan_title.append(str(y))
                if i < samples_per_channel - num_channels:
                    chan_data[:, i] = force_data[i::num_channels]

            print('Iterated through loop\n')

            now = datetime.datetime.now()
            ID = int(idvar.get())
            Force = float("{0:.2f}".format(max(force_data)))
            t = temperature()


            hat.a_in_scan_stop()
            hat.a_in_scan_cleanup()

            Cyc = None

            ResultsWindow(Force, t)

            # Update Status
            status.config(text="Finished...")
            status.update()
            
        except KeyboardInterrupt:
            # Clear the '^C' from the display.
            print(CURSOR_BACK_2, ERASE_TO_END_OF_LINE, '\n')

    except (HatError, ValueError) as err:
        print('\n', err)
Exemplo n.º 15
0
def main():
    """
    This function is executed automatically when the module is run directly.
    """

    # Store the channels in a list and convert the list to a channel mask that
    # can be passed as a parameter to the MCC 128 functions.
    channels = [0, 1, 2, 3]
    channel_mask = chan_list_to_mask(channels)
    num_channels = len(channels)

    input_mode = AnalogInputMode.SE
    input_range = AnalogInputRange.BIP_10V

    samples_per_channel = 0

    options = OptionFlags.CONTINUOUS

    scan_rate = 1000.0

    try:
        # Select an MCC 128 HAT device to use.
        address = select_hat_device(HatIDs.MCC_128)
        hat = mcc128(address)

        hat.a_in_mode_write(input_mode)
        hat.a_in_range_write(input_range)

        print('\nSelected MCC 128 HAT device at address', address)

        actual_scan_rate = hat.a_in_scan_actual_rate(num_channels, scan_rate)

        print('\nMCC 128 continuous scan example')
        print('    Functions demonstrated:')
        print('         mcc128.a_in_scan_start')
        print('         mcc128.a_in_scan_read')
        print('         mcc128.a_in_scan_stop')
        print('         mcc128.a_in_scan_cleanup')
        print('         mcc128.a_in_mode_write')
        print('         mcc128.a_in_range_write')
        print('    Input mode: ', input_mode_to_string(input_mode))
        print('    Input range: ', input_range_to_string(input_range))
        print('    Channels: ', end='')
        print(', '.join([str(chan) for chan in channels]))
        print('    Requested scan rate: ', scan_rate)
        print('    Actual scan rate: ', actual_scan_rate)
        print('    Options: ', enum_mask_to_string(OptionFlags, options))

        try:
            input('\nPress ENTER to continue ...')
        except (NameError, SyntaxError):
            pass


        # Configure and start the scan.
        # Since the continuous option is being used, the samples_per_channel
        # parameter is ignored if the value is less than the default internal
        # buffer size (10000 * num_channels in this case). If a larger internal
        # buffer size is desired, set the value of this parameter accordingly.
        hat.a_in_scan_start(channel_mask, samples_per_channel, scan_rate,
                            options)

        print('Starting scan ... Press Ctrl-C to stop\n')

        # Display the header row for the data table.
        print('Samples Read    Scan Count', end='')
        for chan, item in enumerate(channels):
            print('    Channel ', item, sep='', end='')
        print('')

        try:
            read_and_display_data(hat, num_channels)

        except KeyboardInterrupt:
            # Clear the '^C' from the display.
            print(CURSOR_BACK_2, ERASE_TO_END_OF_LINE, '\n')
            print('Stopping')
            hat.a_in_scan_stop()
            hat.a_in_scan_cleanup()

    except (HatError, ValueError) as err:
        print('\n', err)
Exemplo n.º 16
0
    def __init__(self):

        # define variables
        self.sample_size = 1024
        self.wf_upp_ylim = 2
        self.wf_low_ylim = 0
        self.rate = 10000

        self.channels = [0]
        self.channel_mask = chan_list_to_mask(self.channels)
        self.options = OptionFlags.DEFAULT

        self.request = self.sample_size
        self.timeout = 11

        self.address = select_hat_device(HatIDs.MCC_118)
        self.hat = mcc118(self.address)

        self.x = np.arange(0, self.sample_size)
        self.f = np.linspace(0, self.rate, self.sample_size)

        # configure pyqtgraph window
        pg.setConfigOptions(antialias=True)
        self.traces = dict()
        self.app = QtGui.QApplication(sys.argv)
        self.win = pg.GraphicsWindow(title='Spectrum Analyzer')
        self.win.setWindowTitle('Spectrum Analyzer')
        self.win.setGeometry(5, 115, 1910, 1070)

        # configure waveform and spectrum graphs
        wf_xlabels = [(0, '0'),
                      (self.sample_size / 2, str(self.sample_size / 2)),
                      (self.sample_size, str(self.sample_size))]
        wf_xaxis = pg.AxisItem(orientation='bottom')
        wf_xaxis.setTicks([wf_xlabels])

        wf_ylabels = [(0, '0'), (self.wf_upp_ylim, str(self.wf_upp_ylim)),
                      (self.wf_low_ylim, str(self.wf_low_ylim))]
        wf_yaxis = pg.AxisItem(orientation='left')
        wf_yaxis.setTicks([wf_ylabels])

        sp_xlabels = [(0, '0'), (self.rate / 4, str(self.rate / 4)),
                      (self.rate / 2, str(self.rate / 2))]
        sp_xaxis = pg.AxisItem(orientation='bottom')
        sp_xaxis.setTicks([sp_xlabels])

        self.waveform = self.win.addPlot(
            title='WAVEFORM',
            row=1,
            col=1,
            axisItems={
                'bottom': wf_xaxis,
                'left': wf_yaxis
            },
        )
        self.spectrum = self.win.addPlot(
            title='SPECTRUM',
            row=2,
            col=1,
            axisItems={'bottom': sp_xaxis},
        )
Exemplo n.º 17
0
def cs():
    READ_ALL_AVAILABLE = -1

    no_of_channels = int(chanvar.get())  # Creates the list of channels.
    channels = np.ndarray.tolist(np.arange((no_of_channels), dtype=int))
    channel_mask = chan_list_to_mask(channels)
    num_channels = len(channels)

    samples_per_channel = 0

    options = OptionFlags.CONTINUOUS

    scan_rate = int(ratevar.get())

    try:
        # Select an MCC 118 HAT device to use.
        address = select_hat_device(HatIDs.MCC_118)
        hat = mcc118(address)

        print('\nSelected MCC 118 HAT device at address', address)

        actual_scan_rate = hat.a_in_scan_actual_rate(num_channels, scan_rate)

        print('\nMCC 118 continuous scan example')
        print('    Functions demonstrated:')
        print('         mcc118.a_in_scan_start')
        print('         mcc118.a_in_scan_read')
        print('         mcc118.a_in_scan_stop')
        print('    Channels: ', end='')
        print(', '.join([str(chan) for chan in channels]))
        print('    Requested scan rate: ', scan_rate)
        print('    Actual scan rate: ', actual_scan_rate)
        print('    Options: ', enum_mask_to_string(OptionFlags, options))

        # try:
        # input('\nPress ENTER to continue ...')
        # except (NameError, SyntaxError):
        # pass

        # Configure and start the scan.
        # Since the continuous option is being used, the samples_per_channel
        # parameter is ignored if the value is less than the default internal
        # buffer size (10000 * num_channels in this case). If a larger internal
        # buffer size is desired, set the value of this parameter accordingly.
        hat.a_in_scan_start(channel_mask, samples_per_channel, scan_rate,
                            options)

        print('Starting scan ... Press Ctrl-C to stop\n')

        # Display the header row for the data table.
        print('Samples Read    Scan Count', end='')
        for chan, item in enumerate(channels):
            print('    Channel ', item, sep='', end='')
        print('')

        total_samples_read = 0
        read_request_size = READ_ALL_AVAILABLE

        # When doing a continuous scan, the timeout value will be ignored in the
        # call to a_in_scan_read because we will be requesting that all available
        # samples (up to the default buffer size) be returned.
        timeout = 5.0
        
        # Read all of the available samples (up to the size of the read_buffer which
        # is specified by the user_buffer_size).  Since the read_request_size is set
        # to -1 (READ_ALL_AVAILABLE), this function returns immediately with
        # whatever samples are available (up to user_buffer_size) and the timeout
        # parameter is ignored.
        while True:
            read_result = hat.a_in_scan_read(read_request_size, timeout)

            # Check for an overrun error
            if read_result.hardware_overrun:
                print('\n\nHardware overrun\n')
                break
            elif read_result.buffer_overrun:
                print('\n\nBuffer overrun\n')
                break

            samples_read_per_channel = int(len(read_result.data) / num_channels)
            total_samples_read += samples_read_per_channel
            
            if samples_read_per_channel > 0:
                index = samples_read_per_channel * num_channels - num_channels
                sausage = read_result.data[index] > 2
                if sausage == False:
                    print("Waiting for trigger")
                else:
                    print("Triggered")
                    for i in range(num_channels):
                        print('{:10.5f}'.format(read_result.data[index + i]), 'V ',
                              end='')
                    stdout.flush()

                sleep(0.1)

    except (HatError, ValueError) as err:
        print('\n', err)
Exemplo n.º 18
0
def main():
    """
    This function is executed automatically when the module is run directly.
    """

    # Store the channels in a list and convert the list to a channel mask that
    # can be passed as a parameter to the MCC 118 functions.
    channels = [0, 1, 2, 3]
    channel_mask = chan_list_to_mask(channels)
    num_channels = len(channels)

    samples_per_channel = 4000
    scan_rate = 4000.0
    timeout = 1.0
    options = OptionFlags.DEFAULT

    try:
        # Select an MCC 118 HAT device to use.
        address = select_hat_device(HatIDs.MCC_118)
        hat = mcc118(address)

        print('\nSelected MCC 118 HAT device at address', address)

        actual_scan_rate = hat.a_in_scan_actual_rate(num_channels, scan_rate)

        print('\nMCC 118 continuous scan example')
        print('    Functions demonstrated:')
        print('         mcc118.a_in_scan_start')
        print('         mcc118.a_in_scan_read')
        print('    Channels: ', end='')
        print(', '.join([str(chan) for chan in channels]))
        print('    Requested scan rate: ', scan_rate)
        print('    Actual scan rate: ', actual_scan_rate)
        print('    Samples per channel', samples_per_channel)
        print('    Options: ', enum_mask_to_string(OptionFlags, options))

        #try:
        #input('\nPress ENTER to continue ...')
        #except (NameError, SyntaxError):
        #pass

        # Configure and start the scan.
        hat.a_in_scan_start(channel_mask, samples_per_channel, scan_rate,
                            options)

        print('Starting scan ... Press Ctrl-C to stop\n')
        """Try reading when scanning?"""
        read_output = hat.a_in_scan_read_numpy(samples_per_channel, timeout)
        chan_data = np.zeros([samples_per_channel, num_channels])
        for i in range(num_channels):
            chan_data[:, i] = read_output.data[i]

        np.savetxt("foo.csv", chan_data, delimiter=",")

        # Display the header row for the data table.
        #print('Samples Read    Scan Count', end='')
        #for chan in channels:
        #print('    Channel ', chan, sep='', end='')
        #print('')

        #try:
        #read_and_display_data(hat, samples_per_channel, num_channels)

        #except KeyboardInterrupt:
        # Clear the '^C' from the display.
        #print(CURSOR_BACK_2, ERASE_TO_END_OF_LINE, '\n')

    except (HatError, ValueError) as err:
        print('\n', err)
Exemplo n.º 19
0
def fswtl():
    # Update Status
    status.config(text="Running...")
    status.update()

    i = 1
    while i < 6:
        """This function is executed automatically when the module is run directly.
           """

        # Store the channels in a list and convert the list to a channel mask that
        # can be passed as a parameter to the MCC 118 functions.
        no_of_channels = int(chanvar.get())  # Creates the list of channels.
        channels = np.ndarray.tolist(np.arange((no_of_channels), dtype=int))
        channel_mask = chan_list_to_mask(channels)
        num_channels = len(channels)

        samples_per_channel = int(float(totvar.get()) / 1000 * int(ratevar.get()))

        if (num_channels % 2) == 0:
            samples = int(samples_per_channel * num_channels)
        else:
            samples = int(mt.ceil(samples_per_channel * num_channels))

        scan_rate = int(ratevar.get())
        options = OptionFlags.EXTTRIGGER
        trigger_mode = TriggerModes.ACTIVE_LOW
        timeout = 5.0

        try:
            # Select an MCC 118 HAT device to use.
            address = select_hat_device(HatIDs.MCC_118)
            hat = mcc118(address)

            print('\nSelected MCC 118 HAT device at address', address)

            actual_scan_rate = hat.a_in_scan_actual_rate(num_channels, scan_rate)

            print('\nMCC 118 continuous scan example')
            print('    Functions demonstrated:')
            print('         mcc118.trigger_mode')
            print('         mcc118.a_in_scan_status')
            print('         mcc118.a_in_scan_start')
            print('         mcc118.a_in_scan_read')
            print('    Channels: ', end='')
            print(', '.join([str(chan) for chan in channels]))
            print('    Requested scan rate: ', scan_rate)
            print('    Actual scan rate: ', actual_scan_rate)
            print('    Samples per channel', samples_per_channel)
            print('    Options: ', enum_mask_to_string(OptionFlags, options))
            print('    Trigger Mode: ', trigger_mode.name)

            hat.trigger_mode(trigger_mode)

            # Configure and start the scan.
            hat.a_in_scan_start(channel_mask, samples_per_channel, scan_rate,
                                options)

            try:
                # wait for the external trigger to occur
                print('\nWaiting for trigger ... hit Ctrl-C to cancel the trigger')
                status.config(text="Waiting...")
                status.update()
                wait_for_trigger(hat)

                print('\nStarting scan ... Press Ctrl-C to stop\n')
                status.config(text="Triggered")
                status.update()

                """read complete output data and place int array"""
                read_output = hat.a_in_scan_read_numpy(samples_per_channel, timeout)
                """create a blank array"""
                chan_data = np.zeros([samples_per_channel, num_channels])
                """create title array"""
                chan_title = []
                pressure_data = conv(read_output.data)
                """iterate through the array per channel to split out every other
                sample into the correct column"""

                for i in range(num_channels):
                    for j in range(samples_per_channel):
                        if j == 0:
                            y = str('Channel') + ' ' + str(i)
                            chan_title.append(str(y))
                    if i < samples_per_channel - num_channels:
                        chan_data[:, i] = pressure_data[i::num_channels]

                print('Iterated through loop\n')

                chan_final = np.concatenate((np.reshape(np.array(chan_title), (1, num_channels)), chan_data), axis=0)
                np.savetxt('pressure.csv', chan_final, fmt='%5s', delimiter=',')

                now = datetime.datetime.now()
                ID = int(idvar.get())
                PressureMax = float("{0:.2f}".format(max(pressure_data)))
                PressureMin = float("{0:.2f}".format(min(pressure_data)))
                t = temperature()
                Temp = t[0]

                print(PressureMax)
                print(PressureMin)
                print(Temp)

                Cyc = int(counter.get())

                database_upload(now, ID, PressureMax, PressureMin, t, Cyc)

                hat.a_in_scan_stop()
                hat.a_in_scan_cleanup()

                # Counter stepping
                counter.set(counter.get() + 1)
                f = open('count.txt', 'w')
                f.write(str(counter.get()))
                f.close()

                #Plot(pressure_data)
                ResultsWindow(PressureMax, t)

            except KeyboardInterrupt:
                # Clear the '^C' from the display.
                print(CURSOR_BACK_2, ERASE_TO_END_OF_LINE, '\n')

        except (HatError, ValueError) as err:
            print('\n', err)
Exemplo n.º 20
0
def main():
    """
    This function is executed automatically when the module is run directly.
    """
    # Store the channels in a list and convert the list to a channel mask that
    # can be passed as a parameter to the MCC 118 functions.
    channels = [0,1]
    channel_mask = chan_list_to_mask(channels)
    num_channels = len(channels)

    samples_per_channel = 4000
    scan_rate = 4000
    options = OptionFlags.EXTTRIGGER
    trigger_mode = TriggerModes.ACTIVE_HIGH
    timeout = 5.0

    try:
        # Select an MCC 118 HAT device to use.
        address = select_hat_device(HatIDs.MCC_118)
        hat = mcc118(address)

        print('\nSelected MCC 118 HAT device at address', address)

        actual_scan_rate = hat.a_in_scan_actual_rate(num_channels, scan_rate)

        print('\nMCC 118 continuous scan example')
        print('    Functions demonstrated:')
        print('         mcc118.trigger_mode')
        print('         mcc118.a_in_scan_status')
        print('         mcc118.a_in_scan_start')
        print('         mcc118.a_in_scan_read')
        print('    Channels: ', end='')
        print(', '.join([str(chan) for chan in channels]))
        print('    Requested scan rate: ', scan_rate)
        print('    Actual scan rate: ', actual_scan_rate)
        print('    Samples per channel', samples_per_channel)
        print('    Options: ', enum_mask_to_string(OptionFlags, options))
        print('    Trigger Mode: ', trigger_mode.name)

        #try:
            #input('\nPress ENTER to continue ...')
        #except (NameError, SyntaxError):
            #pass

        hat.trigger_mode(trigger_mode)

        # Configure and start the scan.
        hat.a_in_scan_start(channel_mask, samples_per_channel, scan_rate,
                            options)

        #try:
        # wait for the external trigger to occur
        print('\nWaiting for trigger ... hit Ctrl-C to cancel the trigger')
        wait_for_trigger(hat)

        print('\nStarting scan ... Press Ctrl-C to stop\n')

        """read complete output data and place int array"""
    	read_output = hat.a_in_scan_read_numpy(samples_per_channel, timeout)
    	"""create a blank array"""
    	chan_data = np.zeros([samples_per_channel, num_channels])
    	chan_title = []
        for i in range(num_channels):
            for j in range(samples_per_channel):
                if j ==0:
                    y = str('Channel') + ' ' + str(i)
                    chan_title.append(str(y))
            chan_data[:, i] = read_output.data[i]
        chan_final = np.concatenate((np.reshape(np.array(chan_title), (1, num_channels)), chan_data), axis = 0)
    
    	np.savetxt('force_data.csv', chan_final, fmt = '%5s', delimiter = ',')
    
    	for i in range (num_channels):
        	max_data = max(chan_data[:,i])
        	print("Max Ch",(i),":", max_data)

    	temperature()
    	print(temperature())
        print(max(read_output.data)*12)

        #except KeyboardInterrupt:
            # Clear the '^C' from the display.
            #print(CURSOR_BACK_2, ERASE_TO_END_OF_LINE, '\n')

    except (HatError, ValueError) as err:
        print('\n', err)
Exemplo n.º 21
0
    def __init__(self):

        self.sample_size = 1000
        self.wf_upp_ylim = 2
        self.wf_low_ylim = -2
        self.rate = 10000

        # pyqtgraph stuff
        pg.setConfigOptions(antialias=True)
        self.traces = dict()
        self.app = QtGui.QApplication(sys.argv)
        self.win = pg.GraphicsWindow(title='Spectrum Analyzer')
        self.win.setWindowTitle('Spectrum Analyzer')
        self.win.setGeometry(5, 115, 1910, 1070)

        wf_xlabels = [(0, '0'),
                      (self.sample_size / 2, str(self.sample_size / 2)),
                      (self.sample_size, str(self.sample_size))]
        wf_xaxis = pg.AxisItem(orientation='bottom')
        wf_xaxis.setTicks([wf_xlabels])

        wf_ylabels = [(0, '0'), (self.wf_upp_ylim, str(self.wf_upp_ylim)),
                      (self.wf_low_ylim, str(self.wf_low_ylim))]
        wf_yaxis = pg.AxisItem(orientation='left')
        wf_yaxis.setTicks([wf_ylabels])

        #sp_xlabels = [
        #    (np.log10(10), '10'), (np.log10(100), '100'),
        #    (np.log10(1000), '1000'), (np.log10(22050), '22050')
        #]
        sp_xlabels = [(0, '0'), (self.rate / 4, str(self.rate / 4)),
                      (self.rate / 2, str(self.rate / 2))]
        sp_xaxis = pg.AxisItem(orientation='bottom')
        sp_xaxis.setTicks([sp_xlabels])

        self.waveform = self.win.addPlot(
            title='WAVEFORM',
            row=1,
            col=1,
            axisItems={
                'bottom': wf_xaxis,
                'left': wf_yaxis
            },
        )
        self.spectrum = self.win.addPlot(
            title='SPECTRUM',
            row=2,
            col=1,
            axisItems={'bottom': sp_xaxis},
        )

        # pyaudio stuff
        #self.FORMAT = pyaudio.paInt16
        #self.CHANNELS = 1
        #self.RATE = 44100
        #self.CHUNK = 1024 * 2
        self.channels = [0]
        self.channel_mask = chan_list_to_mask(self.channels)
        self.options = OptionFlags.DEFAULT

        self.request = self.sample_size
        self.timeout = 11

        #self.p = pyaudio.PyAudio()
        #self.stream = self.p.open(
        #    format=self.FORMAT,
        #    channels=self.CHANNELS,
        #    rate=self.RATE,
        #    input=True,
        #    output=True,
        #    frames_per_buffer=self.CHUNK,
        #)
        # waveform and spectrum x points
        self.address = select_hat_device(HatIDs.MCC_118)
        self.hat = mcc118(self.address)

        #self.x = np.arange(0, 2 * self.CHUNK, 2)
        #self.f = np.linspace(0, self.RATE / 2, self.CHUNK / 2)
        self.x = np.arange(0, self.sample_size)
        self.f = np.linspace(0, self.rate, self.sample_size)
Exemplo n.º 22
0
def main():
    """
    This function is executed automatically when the module is run directly.
    """
    hats = []
    # Define the channel list for each HAT device
    chans = [{0, 1}, {0, 1}]
    # Define the options for each HAT device
    options = [OptionFlags.EXTTRIGGER, OptionFlags.EXTCLOCK]
    samples_per_channel = 10000
    sample_rate = 1000.0  # Samples per second
    trigger_mode = TriggerModes.RISING_EDGE

    try:
        # Get an instance of the selected hat device object.
        hats = select_hat_devices(HatIDs.MCC_118, DEVICE_COUNT)

        # Validate the selected channels.
        for i, hat in enumerate(hats):
            validate_channels(chans[i], hat.info().NUM_AI_CHANNELS)

        # Set the trigger mode for the master device.
        hats[MASTER].trigger_mode(trigger_mode)

        # Calculate the actual sample rate.
        actual_rate = hats[MASTER].a_in_scan_actual_rate(
            len(chans[MASTER]), sample_rate)

        print('MCC 118 multiple HAT example using external clock and',
              'external trigger options')
        print('    Functions demonstrated:')
        print('      mcc118.trigger_mode')
        print('      mcc118.a_in_scan_start')
        print('      mcc118.a_in_scan_status')
        print('      mcc118.a_in_scan_read')
        print('    Samples per channel:', samples_per_channel)
        print('    Requested Sample Rate: {:.3f} Hz'.format(sample_rate))
        print('    Actual Sample Rate: {:.3f} Hz'.format(actual_rate))
        print('    Trigger type:', trigger_mode.name)

        for i, hat in enumerate(hats):
            print('    HAT {}:'.format(i))
            print('      Address:', hat.address())
            print('      Channels: ', end='')
            print(', '.join([str(chan) for chan in chans[i]]))
            options_str = enum_mask_to_string(OptionFlags, options[i])
            print('      Options:', options_str)

        print('\n*NOTE: Connect the CLK terminals together on each MCC 118')
        print('       HAT device being used. Connect a trigger source')
        print('       to the TRIG input terminal on HAT 0.')

        try:
            input("\nPress 'Enter' to continue")
        except (NameError, SyntaxError):
            pass

        # Start the scan.
        for i, hat in enumerate(hats):
            chan_mask = chan_list_to_mask(chans[i])
            hat.a_in_scan_start(chan_mask, samples_per_channel, sample_rate,
                                options[i])

        print('\nWaiting for trigger ... Press Ctrl-C to stop scan\n')

        try:
            # Monitor the trigger status on the master device.
            wait_for_trigger(hats[MASTER])
            # Read and display data for all devices until scan completes
            # or overrun is detected.
            read_and_display_data(hats, chans)

        except KeyboardInterrupt:
            # Clear the '^C' from the display.
            print(CURSOR_BACK_2, ERASE_TO_END_OF_LINE, '\nAborted\n')

    except (HatError, ValueError) as error:
        print('\n', error)

    finally:
        for hat in hats:
            hat.a_in_scan_stop()
            hat.a_in_scan_cleanup()
Exemplo n.º 23
0
def fs():
    # Update Status message
    status.config(text="Running...")
    status.update()
    """"This function is executed automatically when the module is run directly."""

    # Store the channels in a list and convert the list to a channel mask that
    # can be passed as a parameter to the MCC 118 functions.
    no_of_channels = int(
        chanvar.get())  # Creates the list of channels from chanvar variable.
    channels = np.ndarray.tolist(np.arange((no_of_channels), dtype=int))
    channel_mask = chan_list_to_mask(channels)
    num_channels = len(channels)

    #calculate number of samples per channel to be recorded from sample duration and rate
    samples_per_channel = int(float(totvar.get()) / 1000 * int(ratevar.get()))
    if (num_channels % 2) == 0:
        samples = int(samples_per_channel * num_channels)
    else:
        samples = int(mt.ceil(samples_per_channel * num_channels))

    #pass sample rate to MCC code, set everything in the scanner to default, and set a timeout
    scan_rate = int(ratevar.get())
    options = OptionFlags.DEFAULT
    timeout = 10.0

    #MCC scanner code
    try:
        # Select an MCC 118 HAT device to use.
        address = select_hat_device(HatIDs.MCC_118)
        hat = mcc118(address)

        print('\nSelected MCC 118 HAT device at address', address)

        actual_scan_rate = hat.a_in_scan_actual_rate(num_channels, scan_rate)

        print('\nMCC 118 continuous scan example')
        print('    Functions demonstrated:')
        print('         mcc118.a_in_scan_start')
        print('         mcc118.a_in_scan_read')
        print('    Channels: ', end='')
        print(', '.join([str(chan) for chan in channels]))
        print('    Requested scan rate: ', scan_rate)
        print('    Actual scan rate: ', actual_scan_rate)
        print('    Samples per channel', samples_per_channel)
        print('    Options: ', enum_mask_to_string(OptionFlags, options))

        # Configure and start the scan.
        hat.a_in_scan_start(channel_mask, samples_per_channel, scan_rate,
                            options)

        try:
            print('Starting scan ... Press Ctrl-C to stop\n')
            #update status
            status.config(text="Scanning...")
            status.update()
            """read complete output data and place in array"""
            read_output = hat.a_in_scan_read_numpy(samples_per_channel,
                                                   timeout)
            """create a blank array"""
            chan_data = np.zeros([samples_per_channel, num_channels])
            """create title array"""
            chan_title = []
            force_data = read_output.data * 12
            """the force_data array is just a list of numbers which is samples per channel*no channels long,
            iterate through the force_data array per channel to split out each sample into the correct column
            based on the number of channels sampled"""
            for i in range(num_channels):
                for j in range(samples_per_channel):
                    if j == 0:
                        y = str('Channel') + ' ' + str(i)
                        chan_title.append(str(y))
                if i < samples_per_channel - num_channels:
                    chan_data[:, i] = force_data[i::num_channels]

            print('Iterated through loop\n')

            #used to output a text file containing channel data during testing
            chan_final = np.concatenate(
                (np.reshape(np.array(chan_title),
                            (1, num_channels)), chan_data),
                axis=0)
            #np.savetxt('foo.csv', chan_final, fmt='%5s', delimiter=',')
            """Create output variables used for database upload and IO window display"""
            now = datetime.datetime.now()
            ID = int(idvar.get())
            # find the max force
            force = float("{0:.2f}".format(max(force_data)))
            # create an array of temperature values
            t = temperature()
            # take the value from the first tc and call it Temp (used for testing)
            temp = t[0]

            #stop the scan and cleanup resources used by DAQHat
            hat.a_in_scan_stop()
            hat.a_in_scan_cleanup()

            # print results in terminal (used for bug fixing)
            print(force)
            print(temp)

            cyc = None

            database_upload(now, ID, force, t, cyc)

            # output results
            plot(force_data)
            resultswindow(force, t)

            # Update Status
            status.config(text="Finished...")
            status.update()

        except KeyboardInterrupt:
            # Clear the '^C' from the display.
            print(CURSOR_BACK_2, ERASE_TO_END_OF_LINE, '\n')

    except (HatError, ValueError) as err:
        print('\n', err)