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 118 mylist = hats.hat_list(filter_by_id=hats.HatIDs.MCC_118) if not mylist: print("No MCC 118 boards found") sys.exit() board = hats.mcc118(mylist[0].address) 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 openDevice(self, address): try: self.board = mcc118(address) except: return False else: return True
def start_stop_click(n_clicks, button_label, hat_descriptor_json_str, sample_rate_val, samples_to_display, 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 118 DAQ HAT. sample_rate_val (float): The user specified sample rate value. samples_to_display (float): The number of samples to be displayed. 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 len(active_channels) > 0 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 _hat = mcc118(hat_descriptor['address']) 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
def __init__( self ): self.queue = Queue() self.running = True self.a0 = 0 self.hat = mcc118( 0 ) self.server = SocketServer( self.queue ) self.start() self.putDataInQueue()
def open_device(self, address): """ Open the selected device """ try: self.board = mcc118(address) except HatError: return False else: return True
def run(self, channels=[0, 2, 4]): ''' Run class that will be called by Cortix Returns data in predetermined format (format undecided) ''' hatlist = hat_list() for i in hatlist: ad = i.address hat = mcc118(ad) options = OptionFlags.DEFAULT avgs = dict() mcc = self.get_port('mcc-plot') tempfile = '{}/{}.csv'.format(self.wrk_dir, self.fname) if os.path.exists(tempfile): os.remove(tempfile) check = True while True: self.timestamp = str(datetime.datetime.now())[:-7] minutes = self.timestamp[14:16] filetime = str(datetime.datetime.now())[:10] self.filename = os.path.join(self.db_dir, self.fname + filetime + '.csv') for i in channels: if str(i) not in avgs: avgs[str(i)] = [] value = hat.a_in_read(i, options) avgs[str(i)].append(value) if len(avgs[str(i)]) < 400: len(avgs[str(i)]) time.sleep(0.00005) continue for i in channels: i = str(i) avgs[i] = sum(avgs[i]) / len(avgs[i]) if not os.path.isfile(self.filename): header = 'Date and Time, ' with open(self.filename, 'w') as f: for i in channels: header += 'Chan {}, '.format(i) header += '\sn' f.write(header) dataline = self.timestamp with open(self.filename, 'a') as f: for i in channels: dataline += ', ' dataline += '{}'.format(avgs[str(i)]) dataline += '\n' f.write(dataline) if minutes == '59' and check == True: self.df = pd.read_csv(self.filename, sep=', ', engine='python', index_col=False) self.send(self.df, mcc) check == False if minutes != '59': check = True avgs = dict()
def CheckDAQBoard(): # get hat list of MCC daqhat boards board_list = hat_list(filter_by_id=HatIDs.ANY) if not board_list: print("No boards found") sys.exit() for entry in board_list: if entry.id == HatIDs.MCC_118: print("Board {}: MCC 118".format(entry.address)) board = mcc118(entry.address) return board
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
def initBoard(self): # Try to initialize the device try: self.board = mcc118(0) serial = self.board.serial() self.serial_number.set(serial) self.ready_led.set(1) self.device_open = True except: self.software_errors += 1 self.current_failures += 1
def __init__(self): ''' Detect boards and get ready to be interrupted ''' self.running = False # get hat list of MCC daqhat boards self.boards = hat_list(filter_by_id=HatIDs.MCC_118) self.boardsEntry = [] for entry in self.boards: self.boardsEntry.append(mcc118(entry.address)) if not self.boards: sys.stderr.write("No boards found\n") sys.exit()
def main(self): lis=daqhats.hat_list() for i in lis: print(i) ad=i.address hat=mcc118(ad) options = OptionFlags.DEFAULT chan=0 lis=[] while True: value = hat.a_in_read(0, options) print(value) time.sleep(0.1)
def __mcc_118(self): ''' IR 7040 "intelligent ratemeter from Mirion Tech. Inc. ''' filename = self.__wrk_dir + '/mcc_118_data.csv' fout = open(filename, 'w') fout.write('This is the header\n') hatlist = hat_list() for i in hatlist: ad = i.address hat = mcc118(ad) options = OptionFlags.DEFAULT chan = 0 while True: value = hat.a_in_read(0, options) fout.write(str(value) + '\n') time.sleep(0.1)
def main(): """ Main function """ # Find the first MCC 118 mylist = hats.hat_list(filter_by_id=hats.HatIDs.MCC_118) if not mylist: print("No MCC 118 boards found") sys.exit() board = hats.mcc118(mylist[0].address) 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(5*60)
def log(self, outfile): ''' In a loop (until interrupted) scan the inputs of all detected boards and output data to a tab delimited text file with a single header row ''' data = ["time"] for entry in self.boards: board = mcc118(entry.address) for channel in range(board.info().NUM_AI_CHANNELS): # Build channel label data.append("{}.{}".format(entry.address, channel)) # DEBUG #print(self.boards) line = "\t".join(data) outfile.write(line) outfile.write("\n") tmpCounter = 0 self.running = True while self.running: now = strftime('%Y-%m-%d %H:%M:%S', gmtime(time())) data = [now] # Read and display every channel #for entry in self.boards: for board in self.boardsEntry: if tmpCounter == 71 and entry.address == 6: print("*" * 4) print("Here it comes!") print("*" * 4) #board = mcc118(entry.address) for channel in range(board.info().NUM_AI_CHANNELS): #data.append(str(board.a_in_read(channel))) data.append("%.4f" % board.a_in_read(channel)) line = "\t".join(data) outfile.write(line) outfile.write("\n") sleep(0.5) tmpCounter += 1 print("Iteration #%d" % tmpCounter) outfile.close()
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
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)
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 = 0 options = OptionFlags.CONTINUOUS scan_rate = 1000.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(' 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('') 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 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 mcc118 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[mcc118]: A list of mcc118 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 118 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(mcc118(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(mcc118(address)) return selected_hats
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-------------------------------------------------'''
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)
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)
# The Python package is named daqhats. Use it in your code with import daqhats. # # read MCC 118 voltage inputs and display channel values (analog input values) #!/usr/bin/env python # import sys from daqhats import hat_list, HatIDs, mcc118 # get hat list of MCC daqhat boards board_list = hat_list(filter_by_id = HatIDs.ANY) if not board_list: print("No boards found") sys.exit() # Read and display every channel for entry in board_list: if entry.id == HatIDs.MCC_118: print("Board {}: MCC 118".format(entry.address)) board = mcc118(entry.address) for channel in range(board.info().NUM_AI_CHANNELS): value = board.a_in_read(channel) print("Ch {0}: {1:.3f}".format(channel, value))
from matplotlib import pyplot as plt # get hat list of MCC daqhat boards board_list = hat_list(filter_by_id=HatIDs.ANY) if not board_list: print("No boards found") sys.exit() board_num = 0 channel = 0 vlts = np.array([]) t = np.array([]) tTot = .1 dt = 0.001 nbr_smpls = int(tTot / dt) tcurr = 0 board = mcc118(board_list[board_num].address) for k in range(nbr_smpls): value = board.a_in_read(channel) vlts = np.append(vlts, value) t = np.append(t, tcurr) tcurr += dt sleep(dt) fig, ax = plt.subplots() ax.plot(t, vlts, '-o') plt.show()
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)
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)
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()
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)
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)
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)
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)