def main(): """ Main function """ log_period = 5*60 if KEY == "<my_key>": print("The default key must be changed to the user's personal IFTTT " "Webhooks key before using this example.") sys.exit() # Find the first MCC 128 mylist = hats.hat_list(filter_by_id=hats.HatIDs.MCC_128) if not mylist: print("No MCC 128 boards found") sys.exit() board = hats.mcc128(mylist[0].address) board.a_in_mode_write(hats.AnalogInputMode.SE) board.a_in_range_write(hats.AnalogInputRange.BIP_10V) while True: # read the voltages value_0 = board.a_in_read(0) value_1 = board.a_in_read(1) send_trigger(EVENT_NAME, "{:.3f}".format(value_0), "{:.3f}".format(value_1)) print("Sent data {0:.3f}, {1:.3f}.".format(value_0, value_1)) time.sleep(log_period)
def __init__(self, conn, ip, port): Thread.__init__(self) self._stop_event = Event() self.ip = ip self.port = port self.conn = conn self.hat = mcc128(ADDRESS) self.temp = None print "[+] New thread started for "+ip+":"+str(port)
def open_device(self, address): """ Open the selected device """ try: self.board = mcc128(address) # get the mode and range self.input_mode = self.board.a_in_mode_read() self.input_range = self.board.a_in_range_read() self.input_mode_var.set(self.input_modes_reversed[self.input_mode]) self.input_range_var.set( self.input_ranges_reversed[self.input_range]) except HatError: return False else: return True
def initBoard(self): # Try to initialize the device try: self.board = mcc128(0) serial = self.board.serial() self.serial_number.set(serial) # set mode and range self.board.a_in_mode_write(TEST_MODE) self.board.a_in_range_write(TEST_RANGE) self.board.trigger_mode(TriggerModes.RISING_EDGE) self.ready_led.set(1) self.device_open = True except: self.software_errors += 1 self.current_failures += 1
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)
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)
def main(): """ This function is executed automatically when the module is run directly. """ options = OptionFlags.DEFAULT low_chan = 0 high_chan = 3 input_mode = AnalogInputMode.SE input_range = AnalogInputRange.BIP_10V mcc_128_num_channels = mcc128.info().NUM_AI_CHANNELS[input_mode] sample_interval = 0.5 # Seconds try: # Ensure low_chan and high_chan are valid. if low_chan < 0 or low_chan >= mcc_128_num_channels: error_message = ('Error: Invalid low_chan selection - must be ' '0 - {0:d}'.format(mcc_128_num_channels - 1)) raise Exception(error_message) if high_chan < 0 or high_chan >= mcc_128_num_channels: error_message = ('Error: Invalid high_chan selection - must be ' '0 - {0:d}'.format(mcc_128_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_128) hat = mcc128(address) hat.a_in_mode_write(input_mode) hat.a_in_range_write(input_range) print('\nMCC 128 single data value read example') print(' Functions demonstrated:') print(' mcc128.a_in_read') 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: {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)
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 = 10000 scan_rate = 1000.0 options = OptionFlags.EXTTRIGGER trigger_mode = TriggerModes.RISING_EDGE 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.trigger_mode') print(' mcc128.a_in_scan_status') 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(' 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') hat.a_in_scan_stop() hat.a_in_scan_cleanup() except (HatError, ValueError) as err: print('\n', err)
def select_hat_devices(filter_by_id, number_of_devices): """ This function performs a query of available DAQ HAT devices and determines the addresses of the DAQ HAT devices to be used in the example. If the number of HAT devices present matches the requested number of devices, a list of all mcc128 objects is returned in order of address, otherwise the user is prompted to select addresses from a list of displayed devices. Args: filter_by_id (int): If this is :py:const:`HatIDs.ANY` return all DAQ HATs found. Otherwise, return only DAQ HATs with ID matching this value. number_of_devices (int): The number of devices to be selected. Returns: list[mcc128]: A list of mcc128 objects for the selected devices (Note: The object at index 0 will be used as the master). Raises: HatError: Not enough HAT devices are present. """ selected_hats = [] # Get descriptors for all of the available HAT devices. hats = hat_list(filter_by_id=filter_by_id) number_of_hats = len(hats) # Verify at least one HAT device is detected. if number_of_hats < number_of_devices: error_string = ('Error: This example requires {0} MCC 128 HATs - ' 'found {1}'.format(number_of_devices, number_of_hats)) raise HatError(0, error_string) elif number_of_hats == number_of_devices: for i in range(number_of_devices): selected_hats.append(mcc128(hats[i].address)) else: # Display available HAT devices for selection. for hat in hats: print('Address ', hat.address, ': ', hat.product_name, sep='') print('') for device in range(number_of_devices): valid = False while not valid: input_str = 'Enter address for HAT device {}: '.format(device) address = int(input(input_str)) # Verify the selected address exists. if any(hat.address == address for hat in hats): valid = True else: print('Invalid address - try again') # Verify the address was not previously selected if any(hat.address() == address for hat in selected_hats): print('Address already selected - try again') valid = False if valid: selected_hats.append(mcc128(address)) return selected_hats
def start_stop_click(n_clicks, button_label, hat_descriptor_json_str, sample_rate_val, samples_to_display, input_range, active_channels): """ A callback function to change the application status when the Configure, Start or Stop button is clicked. Args: n_clicks (int): Number of button clicks - triggers the callback. button_label (str): The current label on the button. hat_descriptor_json_str (str): A string representation of a JSON object containing the descriptor for the selected MCC 128 DAQ HAT. sample_rate_val (float): The user specified sample rate value. samples_to_display (float): The number of samples to be displayed. input_range (int): The analog input voltage range. active_channels ([int]): A list of integers corresponding to the user selected Active channel checkboxes. Returns: str: The new application status - "idle", "configured", "running" or "error" """ output = 'idle' if n_clicks is not None and n_clicks > 0: if button_label == 'Configure': if (1 < samples_to_display <= 1000 and active_channels and sample_rate_val <= (100000 / len(active_channels))): # If configuring, create the hat object. if hat_descriptor_json_str: hat_descriptor = json.loads(hat_descriptor_json_str) # The hat object is retained as a global for use in # other callbacks. global _HAT # pylint: disable=global-statement _HAT = mcc128(hat_descriptor['address']) # Change to AnalogInputMode.DIFF for differential inputs. _HAT.a_in_mode_write(AnalogInputMode.SE) _HAT.a_in_range_write(input_range) output = 'configured' else: output = 'error' elif button_label == 'Start': # If starting, call the a_in_scan_start function. sample_rate = float(sample_rate_val) channel_mask = 0x0 for channel in active_channels: channel_mask |= 1 << channel hat = globals()['_HAT'] # Buffer 5 seconds of data samples_to_buffer = int(5 * sample_rate) hat.a_in_scan_start(channel_mask, samples_to_buffer, sample_rate, OptionFlags.CONTINUOUS) sleep(0.5) output = 'running' elif button_label == 'Stop': # If stopping, call the a_in_scan_stop and a_in_scan_cleanup # functions. hat = globals()['_HAT'] hat.a_in_scan_stop() hat.a_in_scan_cleanup() output = 'idle' return output
if low_chan < 0 or low_chan >= mcc_128_num_channels: error_message = ('Error: Invalid low_chan selection - must be ' '0 - {0:d}'.format(mcc_128_num_channels - 1)) raise Exception(error_message) if high_chan < 0 or high_chan >= mcc_128_num_channels: error_message = ('Error: Invalid high_chan selection - must be ' '0 - {0:d}'.format(mcc_128_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_128) hat = mcc128(address) hat.a_in_mode_write(input_mode) hat.a_in_range_write(input_range) except (HatError, ValueError) as error: print('\n', error) #MCC128 END class GroveGSRSensor: def __init__(self, channel): self.channel = channel self.adc = ADC() @property def GSR(self):