コード例 #1
0
ファイル: mytest.py プロジェクト: sagamore66/PythonPiDAQ
def ResetMcc152():

    boardAddr = select_hat_device(HatIDs.MCC_152)
    board = mcc152(boardAddr)
    board.dio_reset()

    return jsonify("MCC152 RESET")
コード例 #2
0
def main():
    """
    This function is executed automatically when the module is run directly.
    """
    options = OptionFlags.DEFAULT

    print('MCC 152 all channel analog output example.')
    print('Writes the specified voltages to the analog outputs.')
    print("   Methods demonstrated:")
    print("      mcc152.a_out_write_all")
    print("      mcc152.info")
    print()

    # Get an instance of the selected hat device object.
    address = select_hat_device(HatIDs.MCC_152)

    print("\nUsing address {}.\n".format(address))

    hat = mcc152(address)

    run_loop = True
    error = False
    while run_loop and not error:
        # Get the values from the user.
        try:
            values = get_input_values()
        except ValueError:
            run_loop = False
        else:
            # Write the values.
            try:
                hat.a_out_write_all(values=values, options=options)
            except (HatError, ValueError):
                error = True
コード例 #3
0
def main():
    """
    This function is executed automatically when the module is run directly.
    """

    print("MCC 152 digital output write example.")
    print("Sets all digital I/O channels to outputs then gets values from")
    print("the user and updates the outputs. The value can be specified")
    print("as decimal (0 - 255,) hexadecimal (0x0 - 0xFF,)")
    print("octal (0o0 - 0o377,) or binary (0b0 - 0b11111111.)")
    print("   Methods demonstrated:")
    print("      mcc152.dio_reset")
    print("      mcc152.dio_output_write_port")
    print("      mcc152.dio_config_write_port")
    print("      mcc152.info")
    print()

    # Get an instance of the selected hat device object.
    address = select_hat_device(HatIDs.MCC_152)

    print("\nUsing address {}.\n".format(address))

    hat = mcc152(address)

    # Reset the DIO to defaults (all channels input, pull-up resistors
    # enabled).
    hat.dio_reset()

    # Set all channels as outputs.
    try:
        hat.dio_config_write_port(DIOConfigItem.DIRECTION, 0x00)
    except (HatError, ValueError):
        print("Could not configure the port as outputs.")
        sys.exit()

    run_loop = True
    error = False
    # Loop until the user terminates or we get a library error.
    while run_loop and not error:
        write_value = get_input()

        if write_value is None:
            run_loop = False
        else:
            try:
                hat.dio_output_write_port(write_value)
            except (HatError, ValueError):
                error = True

        if error:
            print("Error writing the outputs.")

    # Return the DIO to default settings
    if not error:
        hat.dio_reset()
コード例 #4
0
def main():
    """
    This function is executed automatically when the module is run directly.
    """

    print("MCC 152 digital output write example.")
    print("Sets all digital I/O channels to output then gets channel and")
    print("value input from the user and updates the output.")
    print("   Methods demonstrated:")
    print("      mcc152.dio_reset")
    print("      mcc152.dio_output_write_bit")
    print("      mcc152.dio_config_write_bit")
    print("      mcc152.info")
    print()

    # Get an instance of the selected hat device object.
    address = select_hat_device(HatIDs.MCC_152)

    print("\nUsing address {}.\n".format(address))

    hat = mcc152(address)

    # Reset the DIO to defaults (all channels input, pull-up resistors
    # enabled).
    hat.dio_reset()

    # Set all channels as outputs.
    for channel in range(mcc152.info().NUM_DIO_CHANNELS):
        try:
            hat.dio_config_write_bit(channel, DIOConfigItem.DIRECTION, 0)
        except (HatError, ValueError):
            print("Could not configure the channel as output.")
            sys.exit()

    run_loop = True
    error = False
    # Loop until the user terminates or we get a library error.
    while run_loop and not error:
        channel, value = get_input()

        if channel is None:
            run_loop = False
        else:
            try:
                hat.dio_output_write_bit(channel, value)
            except (HatError, ValueError):
                error = True

        if error:
            print("Error writing the output.")

    # Return the DIO to default settings
    if not error:
        hat.dio_reset()
コード例 #5
0
def main():
    """
    This function is executed automatically when the module is run directly.
    """

    print("MCC 152 digital input read example.")
    print("Reads the inputs individually and displays their state.")
    print("   Methods demonstrated:")
    print("      mcc152.dio_reset")
    print("      mcc152.dio_input_read_bit")
    print("      mcc152.info")
    print()

    # Get an instance of the selected hat device object.
    address = select_hat_device(HatIDs.MCC_152)

    print("\nUsing address {}.\n".format(address))

    hat = mcc152(address)

    # Reset the DIO to defaults (all channels input, pull-up resistors
    # enabled).
    hat.dio_reset()

    num_channels = hat.info().NUM_DIO_CHANNELS

    run_loop = True
    error = False
    # Loop until the user terminates or we get a library error.
    while run_loop and not error:
        # Read and display the individual channels.
        for channel in range(num_channels):
            try:
                value = hat.dio_input_read_bit(channel)
            except (HatError, ValueError):
                error = True
                break
            else:
                print("DIO{0}: {1}\t".format(channel, value), end="")

        if error:
            print("\nError reading the input.")
        else:
            # Wait for the user to enter a response
            message = "\nEnter Q to exit, anything else to read again: "
            if version_info.major > 2:
                response = input(message)
            else:
                response = raw_input(message)

            if response == "q" or response == "Q":
                # Exit the loop
                run_loop = False
コード例 #6
0
ファイル: mytest.py プロジェクト: sagamore66/PythonPiDAQ
def api_id():

    if 'id' in request.args:
        id = int(request.args['id'])
    else:
        return "Error detected"

    #get MCC152 board address
    boardAddr = select_hat_device(HatIDs.MCC_152)
    board = mcc152(boardAddr)
    bit = (0, 1, 2, 3, 4, 5, 6, 7, 8)

    board.dio_config_write_port(DIOConfigItem.DIRECTION, 0x00)

    board.dio_output_write_port(id)

    bit0 = str(board.dio_input_read_bit(0))
    bit1 = str(board.dio_input_read_bit(1))
    bit2 = str(board.dio_input_read_bit(2))
    bit3 = str(board.dio_input_read_bit(3))
    bit4 = str(board.dio_input_read_bit(4))
    bit5 = str(board.dio_input_read_bit(5))
    bit6 = str(board.dio_input_read_bit(6))
    bit7 = str(board.dio_input_read_bit(7))

    myDIO = [{
        'bit': 0,
        'value': bit0,
    }, {
        'bit': 1,
        'value': bit1,
    }, {
        'bit': 2,
        'value': bit2,
    }, {
        'bit': 3,
        'value': bit3,
    }, {
        'bit': 4,
        'value': bit4,
    }, {
        'bit': 5,
        'value': bit5,
    }, {
        'bit': 6,
        'value': bit7,
    }, {
        'bit': 7,
        'value': bit7,
    }]

    return jsonify(myDIO)
コード例 #7
0
ファイル: mcc_daq.py プロジェクト: SangkyunLee/Pybehav
 def init_daq(self):
     try:            
         address = select_hat_device(HatIDs.MCC_118)
         self.hat = mcc118(address)
         
         num_channels = len(self.ai_ch)             
         self.scan_rate = self.hat.a_in_scan_actual_rate(num_channels, self.scan_rate)        
         self.read_request_size = int(self.scan_rate*self.acq_dur)
     
         
         
     except (NameError, SyntaxError):
         pass
コード例 #8
0
ファイル: mytest.py プロジェクト: sagamore66/PythonPiDAQ
def AnaOut0():

    if 'id' in request.args:
        id = float(request.args['id'])
    else:
        return "Error detected"

    options = OptionFlags.DEFAULT
    boardAddr = select_hat_device(HatIDs.MCC_152)
    board = mcc152(boardAddr)

    board.a_out_write(channel=0, value=id, options=options)
    return "SUCCESS"
コード例 #9
0
def main():
    """
    This function is executed automatically when the module is run directly.
    """

    print("MCC 152 digital input read example.")
    print("Reads the inputs as a port and displays their state.")
    print("   Methods demonstrated:")
    print("      mcc152.dio_reset")
    print("      mcc152.dio_input_read_port")
    print()

    # Get an instance of the selected hat device object.
    address = select_hat_device(HatIDs.MCC_152)

    print("\nUsing address {}.\n".format(address))

    hat = mcc152(address)

    # Reset the DIO to defaults (all channels input, pull-up resistors
    # enabled).
    hat.dio_reset()

    run_loop = True
    error = False
    # Loop until the user terminates or we get a library error.
    while run_loop and not error:
        # Read and display the inputs
        try:
            value = hat.dio_input_read_port()
        except (HatError, ValueError):
            error = True
            break
        else:
            print("Digital Inputs: 0x{0:02X}".format(value))

        if error:
            print("Error reading the inputs.")
        else:
            print("Enter Q to exit, anything else to read again: ")

            # Wait for the user to enter a response
            if version_info.major > 2:
                response = input("")
            else:
                response = raw_input("")

            if response == "q" or response == "Q":
                # Exit the loop
                run_loop = False
コード例 #10
0
def main():
    """
    This function is executed automatically when the module is run directly.
    """
    options = OptionFlags.DEFAULT
    channel = 0
    num_channels = mcc152.info().NUM_AO_CHANNELS

    # Ensure channel is valid.
    if channel not in range(num_channels):
        error_message = ('Error: Invalid channel selection - must be '
                         '0 - {}'.format(num_channels - 1))
        raise Exception(error_message)

    print('MCC 152 single channel analog output example.')
    print('Writes the specified voltage to the analog output.')
    print("   Methods demonstrated:")
    print("      mcc152.a_out_write")
    print("      mcc152.info")
    print("   Channel: {}\n".format(channel))

    # Get an instance of the selected hat device object.
    address = select_hat_device(HatIDs.MCC_152)

    print("\nUsing address {}.\n".format(address))

    hat = mcc152(address)

    run_loop = True
    error = False
    while run_loop and not error:
        # Get the value from the user.
        try:
            value = get_input_value()
        except ValueError:
            run_loop = False
        else:
            # Write the value to the selected channel.
            try:
                hat.a_out_write(channel=channel,
                                value=value,
                                options=options)
            except (HatError, ValueError):
                error = True

    if error:
        print("Error writing analog output.")
コード例 #11
0
ファイル: mytest.py プロジェクト: sagamore66/PythonPiDAQ
def BitStatus():

    if 'id' in request.args:
        id = int(request.args['id'])
    else:
        return "error detected"

    boardAddr = select_hat_device(HatIDs.MCC_152)
    board = mcc152(boardAddr)

    bitValue = board.dio_input_read_bit(6)

    #buttonStatus = [
    #    {'bitStatus': id,
    #    'bitValue': bitValue}
    #    ]

    return str(bitValue)
コード例 #12
0
ファイル: mytest.py プロジェクト: sagamore66/PythonPiDAQ
def ButtonClear():

    options = OptionFlags.DEFAULT

    if 'id' in request.args:
        id = int(request.args['id'])
    else:
        return jsonify("Error detected clearing bit 6")

    boardAddr = select_hat_device(HatIDs.MCC_152)
    board = mcc152(boardAddr)
    board.dio_output_write_bit(6, 0)
    board.a_out_write(channel=1, value=0, options=options)

    buttonReset = [{
        'ButtonStatus': id,
        'value': board.dio_input_read_bit(6),
    }]

    return jsonify(buttonReset)
コード例 #13
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
コード例 #14
0
ファイル: mytest.py プロジェクト: sagamore66/PythonPiDAQ
def AnaIN():

    if 'id' in request.args:
        id = int(request.args['id'])
    else:
        return "Error detected"

    options = OptionFlags.DEFAULT
    boardAddr = select_hat_device(HatIDs.MCC_118)
    board = mcc118(boardAddr)

    value = board.a_in_read(id, options)
    #value = value * 2
    #value = "{:.2f}".format(value)

    myAnalogIn = [{
        'chan': id,
        'value': value,
    }]

    return jsonify(myAnalogIn)
コード例 #15
0
    def init_dev(self):
        address = select_hat_device(HatIDs.MCC_152)
        self.HAT = mcc152(address)

        # Reset the DIO to defaults (all channels input, pull-up resistors
        # enabled).
        self.HAT.dio_reset()
        # Read the initial input values so we don't trigger an interrupt when
        # we enable them.
        self.HAT.dio_input_read_port()

        # set digital ouptput channels
        for ch in self.do_ch:
            try:
                self.HAT.dio_config_write_bit(ch, DIOConfigItem.DIRECTION, 0)
                # since default output register value is 1,
                # reset to 0
                self.write_outputvalue(ch, 0)

            except (HatError, ValueError):
                logging.error(
                    'could not configure the channel{} as output'.format(ch))
                sys.exit()

        # set digital iput channels as latched input
        for ch in self.di_ch:
            try:
                self.HAT.dio_config_write_bit(ch, DIOConfigItem.DIRECTION, 1)
                # Enable latched inputs so we know that a value changed even if it changes
                # back to the original value before the interrupt callback.
                self.HAT.dio_config_write_bit(ch, DIOConfigItem.INPUT_LATCH, 1)
                # interrupt enabled
                self.HAT.dio_config_write_bit(ch, DIOConfigItem.INT_MASK, 0)

            except (HatError, ValueError):
                logging.error(
                    'could not configure the channel{} as output'.format(ch))
                sys.exit()

        self.callback = HatCallback(self.interrupt_callback)
コード例 #16
0
    def openDaq(self, DaqStreamInfo):
        self.DaqStreamInfo = DaqStreamInfo
        self.options = DaqStreamInfo.options
        self.low_chan = DaqStreamInfo.low_chan
        self.high_chan = DaqStreamInfo.high_chan
        self.input_mode = DaqStreamInfo.input_mode
        self.input_range = DaqStreamInfo.input_range

        self.mcc_128_num_channels = DaqStreamInfo.mcc_128_num_channels
        self.sample_interval = DaqStreamInfo.sample_interval
        self.guid = getGUID()
        #print(self.guid)

        try:
            # Ensure low_chan and high_chan are valid.
            if self.low_chan < 0 or self.low_chan >= self.mcc_128_num_channels:
                error_message = ('Error: Invalid low_chan selection - must be '
                                 '0 - {0:d}'.format(self.mcc_128_num_channels -
                                                    1))
                raise Exception(error_message)
            if self.high_chan < 0 or self.high_chan >= self.mcc_128_num_channels:
                error_message = (
                    'Error: Invalid high_chan selection - must be '
                    '0 - {0:d}'.format(self.mcc_128_num_channels - 1))
                raise Exception(error_message)
            if self.low_chan > self.high_chan:
                error_message = ('Error: Invalid channels - high_chan must be '
                                 'greater than or equal to low_chan')
                raise Exception(error_message)
            # Get an instance of the selected hat device object.
            address = select_hat_device(HatIDs.MCC_128)
            self.hat = mcc128(address)

            self.hat.a_in_mode_write(self.input_mode)
            self.hat.a_in_range_write(self.input_range)
            self.sensor = self.hat

        except (HatError, ValueError) as error:
            print('\n', error)
コード例 #17
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)
コード例 #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]
    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)
コード例 #19
0
delay = 3

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-------------------------------------------------'''
コード例 #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, 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)
コード例 #21
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)
コード例 #22
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)
コード例 #23
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)
コード例 #24
0
def main():
    """
    This function is executed automatically when the module is run directly.
    """

    print("MCC 152 digital input interrupt example.")
    print("Enables interrupts on the inputs and displays their state when")
    print("they change.")
    print("   Functions / Methods demonstrated:")
    print("      mcc152.dio_reset")
    print("      mcc152.dio_config_write_port")
    print("      mcc152.dio_input_read_port")
    print("      mcc152.dio_int_status_read_port")
    print("      mcc152.info")
    print("      interrupt_callback_enable")
    print("      interrupt_callback_disable")
    print()

    # Get an instance of the selected HAT device object.
    address = select_hat_device(HatIDs.MCC_152)

    print("\nUsing address {}.\n".format(address))

    global HAT  # pylint: disable=global-statement

    HAT = mcc152(address)

    # Reset the DIO to defaults (all channels input, pull-up resistors
    # enabled).
    HAT.dio_reset()

    # Read the initial input values so we don't trigger an interrupt when
    # we enable them.
    value = HAT.dio_input_read_port()

    # Enable latched inputs so we know that a value changed even if it changes
    # back to the original value before the interrupt callback.
    HAT.dio_config_write_port(DIOConfigItem.INPUT_LATCH, 0xFF)

    # Unmask (enable) interrupts on all channels.
    HAT.dio_config_write_port(DIOConfigItem.INT_MASK, 0x00)

    print("Current input values are 0x{:02X}".format(value))
    print("Waiting for changes, enter any text to exit. ")

    # Create a HAT callback object for our function
    callback = HatCallback(interrupt_callback)

    # Enable the interrupt callback function. Provide a mutable value for
    # user_data that counts the number of interrupt occurrences.

    int_count = [0]
    interrupt_callback_enable(callback, int_count)

    # Wait for the user to enter anything, then exit.
    if version_info.major > 2:
        input("")
    else:
        raw_input("")

    # Return the digital I/O to default settings.
    HAT.dio_reset()

    # Disable the interrupt callback.
    interrupt_callback_disable()
コード例 #25
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)
コード例 #26
0
def main():
    """
    This function is executed automatically when the module is run directly.
    """
    tc_type = TcTypes.TYPE_J  # change this to the desired thermocouple type
    delay_between_reads = 1  # Seconds
    channels = (0, 1, 2, 3)

    try:
        # Get an instance of the selected hat device object.
        address = select_hat_device(HatIDs.MCC_134)
        hat = mcc134(address)

        for channel in channels:
            hat.tc_type_write(channel, tc_type)

        print('\nMCC 134 single data value read example')
        print('    Function demonstrated: mcc134.t_in_read')
        print('    Channels: ' +
              ', '.join(str(channel) for channel in channels))
        print('    Thermocouple type: ' + tc_type_to_string(tc_type))
        try:
            input("\nPress 'Enter' to continue")
        except (NameError, SyntaxError):
            pass

        print('\nAcquiring data ... Press Ctrl-C to abort')

        # Display the header row for the data table.
        print('\n  Sample', end='')
        for channel in channels:
            print('     Channel', channel, end='')
        print('')

        try:
            samples_per_channel = 0
            while True:
                # Display the updated samples per channel count
                samples_per_channel += 1
                print('\r{:8d}'.format(samples_per_channel), end='')

                # Read a single value from each selected channel.
                for channel in channels:
                    value = hat.t_in_read(channel)
                    if value == mcc134.OPEN_TC_VALUE:
                        print('     Open     ', end='')
                    elif value == mcc134.OVERRANGE_TC_VALUE:
                        print('     OverRange', end='')
                    elif value == mcc134.COMMON_MODE_TC_VALUE:
                        print('   Common Mode', end='')
                    else:
                        print('{:12.2f} C'.format(value), end='')

                stdout.flush()

                # Wait the specified interval between reads.
                sleep(delay_between_reads)

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

    except (HatError, ValueError) as error:
        print('\n', error)
コード例 #27
0
def main():
    """
    This function is executed automatically when the module is run directly.
    """
    options = OptionFlags.DEFAULT
    low_chan = 0
    high_chan = 3
    mcc_118_num_channels = mcc118.info().NUM_AI_CHANNELS
    sample_interval = 0.5  # Seconds

    try:
        # Ensure low_chan and high_chan are valid.
        if low_chan < 0 or low_chan >= mcc_118_num_channels:
            error_message = ('Error: Invalid low_chan selection - must be '
                             '0 - {0:d}'.format(mcc_118_num_channels - 1))
            raise Exception(error_message)
        if high_chan < 0 or high_chan >= mcc_118_num_channels:
            error_message = ('Error: Invalid high_chan selection - must be '
                             '0 - {0:d}'.format(mcc_118_num_channels - 1))
            raise Exception(error_message)
        if low_chan > high_chan:
            error_message = ('Error: Invalid channels - high_chan must be '
                             'greater than or equal to low_chan')
            raise Exception(error_message)

        # Get an instance of the selected hat device object.
        address = select_hat_device(HatIDs.MCC_118)
        hat = mcc118(address)

        print('\nMCC 118 single data value read example')
        print('    Function demonstrated: mcc118.a_in_read')
        print('    Channels: {0:d} - {1:d}'.format(low_chan, high_chan))
        print('    Options:', enum_mask_to_string(OptionFlags, options))
        try:
            #input("\nPress 'Enter' to continue")
        #except (NameError, SyntaxError):
            #pass

        print('\nAcquiring data ... Press Ctrl-C to abort')

        # Display the header row for the data table.
        print('\n  Samples/Channel', end='')
        for chan in range(low_chan, high_chan + 1):
            print('     Channel', chan, end='')
        print('')

        try:
            samples_per_channel = 0
            while True:
                # Display the updated samples per channel count
                samples_per_channel += 1
                print('\r{:17}'.format(samples_per_channel), end='')

                # Read a single value from each selected channel.
                for chan in range(low_chan, high_chan + 1):
                    value = hat.a_in_read(chan, options)
                    print('{:12.5} V'.format(value), end='')

                stdout.flush()

                # Wait the specified interval between reads.
                sleep(sample_interval)

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

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


if __name__ == '__main__':
    # This will only be run when the module is called directly.
    main()
コード例 #28
0
ファイル: continuous_scan.py プロジェクト: weimeitzu/daqhats
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)
コード例 #29
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)
コード例 #30
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)