def display_values(self, curr_index, curr_count): array = self.array # If no data has been gathered, don't add data to the labels if curr_count > 1: # Convert the CH0 value to volts and display it chan_0_eng_value = ul.to_eng_units(self.board_num, self.gain_list[0], array[curr_index]) self.chan_0_label["text"] = '{:.3f}'.format( chan_0_eng_value) + " Volts" # Convert the CH1 value to volts and display it chan_1_eng_value = ul.to_eng_units(self.board_num, self.gain_list[0], array[curr_index + 1]) self.chan_1_label["text"] = '{:.3f}'.format( chan_1_eng_value) + " Volts" # Display the digital port value as hex self.digital_label["text"] = '0x' + \ '{:0<2X}'.format(array[curr_index + 2]) # Display the setpoint status as hex self.setpoint_status_label["text"] = '0x' + \ '{:0<4X}'.format(array[curr_index + 3])
def update_value(self): channel = self.get_channel_num() ai_range = self.ai_props.available_ranges[0] try: gain = self.ai_props.available_ranges[0] trig_type = self.get_trigger_type() trig_value_eng = self.get_trigger_level() trig_value = ul.from_eng_units(self.board_num, gain, trig_value_eng) # Get a value from the device value = ul.a_trig(self.board_num, channel, trig_type, trig_value, gain) # Convert the raw value to engineering units eng_units_value = ul.to_eng_units(self.board_num, ai_range, value) # Display the raw value self.value_label["text"] = str(value) # Display the engineering value self.eng_value_label["text"] = '{:.3f}'.format(eng_units_value) # Call this method again until the stop button is pressed (or an # error occurs) if self.running: self.after(100, self.update_value) except ULError as e: self.stop() self.show_ul_error(e)
def display_values(self, array, range_, total_count, low_chan, high_chan): new_data_frame = tk.Frame(self.results_group) channel_text = [] # Add the headers for chan_num in range(low_chan, high_chan + 1): channel_text.append("Channel " + str(chan_num) + "\n") chan_count = high_chan - low_chan + 1 # Add (up to) the first 10 values for each channel to the text chan_num = low_chan for data_index in range(0, min(chan_count * 10, total_count)): # Convert the value to an engineering units value. eng_value = ul.to_eng_units( self.board_num, range_, array[data_index]) channel_text[chan_num - low_chan] += '{:.3f}'.format(eng_value) + "\n" if chan_num == high_chan: chan_num = low_chan else: chan_num += 1 # Add the labels for each channel for chan_num in range(low_chan, high_chan + 1): chan_label = tk.Label(new_data_frame, justify=tk.LEFT, padx=3) chan_label["text"] = channel_text[chan_num - low_chan] chan_label.grid(row=0, column=chan_num - low_chan) self.data_frame.destroy() self.data_frame = new_data_frame self.data_frame.grid()
def update_value(self): channel = self.get_channel_num() ai_range = self.ai_props.available_ranges[0] try: # Get a value from the device if self.ai_props.resolution <= 16: # Use the a_in method for devices with a resolution <= 16 value = ul.a_in(self.board_num, channel, ai_range) # Convert the raw value to engineering units eng_units_value = ul.to_eng_units(self.board_num, ai_range, value) else: # Use the a_in_32 method for devices with a resolution > 16 # (optional parameter omitted) value = ul.a_in_32(self.board_num, channel, ai_range) # Convert the raw value to engineering units eng_units_value = ul.to_eng_units_32(self.board_num, ai_range, value) # Display the raw value self.value_label["text"] = str(value) # Display the engineering value self.eng_value_label["text"] = '{:.3f}'.format(eng_units_value) # Call this method again until the stop button is pressed (or an # error occurs) if self.running: self.after(100, self.update_value) except ULError as e: self.stop() self.show_ul_error(e)
def go(self, **kwargs): """Start the run.""" to_average = [] #stop old processes in case ul.stop_background(self.board_num, FunctionType.AOFUNCTION) ul.stop_background(self.board_num, FunctionType.AIFUNCTION) nchannels_out = self.out_channel_end - self.out_channel_start + 1 nchannels_in = self.in_channel_end - self.in_channel_start + 1 try: self.preset_loop = kwargs['preset_loop'] if self.preset_loop: self.nave = self.nave+1 except KeyError: self.preset_loop = False for i in range(self.nave): returned = apply_and_listen(self.wf_1d, self.nzeros_front, self.nzeros_back, in_channel_start=self.in_channel_start, in_channel_end=self.in_channel_end, out_channel_start=self.out_channel_start, out_channel_end=self.out_channel_end, quiet = self.quiet, **kwargs) memhandle_in, memhandle_out, data_array_in, data_array_out, count_in, time = returned try: # Free the buffer and set the data_array to None ul.win_buf_free(memhandle_out) data_array_out = None #now that it is done convert from data_array back to numpy data: out = [] for i in range(0, count_in): out.append(ul.to_eng_units(self.board_num, self.ul_range, data_array_in[i])) out = np.array(out) #clear memory ul.win_buf_free(memhandle_in) data_array_in = None #append data if self.preset_loop and i == 0: continue else: to_average.append(out) except Exception as e: #clear memory try: ul.win_buf_free(memhandle_in) ul.win_buf_free(memhandle_out) raise e except: raise e data = np.array(to_average) means = np.mean(data, axis = 0) out = waveform_1d_to_array(means, nchannels_in=nchannels_in) self.waveform_collected = out self.time = time return
def run_example(): # By default, the example detects and displays all available devices and # selects the first device listed. Use the dev_id_list variable to filter # detected devices by device ID (see UL documentation for device IDs). # If use_device_detection is set to False, the board_num variable needs to # match the desired board number configured with Instacal. use_device_detection = True dev_id_list = [] board_num = 0 try: if use_device_detection: config_first_detected_device(board_num, dev_id_list) daq_dev_info = DaqDeviceInfo(board_num) if not daq_dev_info.supports_analog_input: raise Exception('Error: The DAQ device does not support ' 'analog input') print('\nActive DAQ device: ', daq_dev_info.product_name, ' (', daq_dev_info.unique_id, ')\n', sep='') ai_info = daq_dev_info.get_ai_info() ai_range = ai_info.supported_ranges[0] channel = 0 # Get a value from the device if ai_info.resolution <= 16: # Use the a_in method for devices with a resolution <= 16 value = ul.a_in(board_num, channel, ai_range) # Convert the raw value to engineering units eng_units_value = ul.to_eng_units(board_num, ai_range, value) else: # Use the a_in_32 method for devices with a resolution > 16 # (optional parameter omitted) value = ul.a_in_32(board_num, channel, ai_range) # Convert the raw value to engineering units eng_units_value = ul.to_eng_units_32(board_num, ai_range, value) # Display the raw value print('Raw Value:', value) # Display the engineering value print('Engineering Value: {:.3f}'.format(eng_units_value)) except Exception as e: print('\n', e) finally: if use_device_detection: ul.release_daq_device(board_num)
def read_pressure(): try: # Get a value from the device value = ul.a_in(board_num, channel, ai_range) # Convert the raw value to engineering units eng_units_value = ul.to_eng_units(board_num, ai_range, value) psi = (eng_units_value - 0.5) * 500 / 3 print 'psi:', psi except ULError as e: # Display the error print("A UL error occurred. Code: " + str(e.errorcode) + " Message: " + e.message)
def display_input_values(self, range_, curr_index, curr_count): per_channel_display_count = 1 array = self.ctypes_array low_chan = self.input_low_chan high_chan = self.input_high_chan ULAIO01.channel_text = [] # Add the headers for chan_num in range(low_chan, high_chan + 1): ULAIO01.channel_text.append("Channel " + str(chan_num) + "\n") # If no data has been gathered, don't add data to the labels if curr_count > 1: chan_count = high_chan - low_chan + 1 chan_num = low_chan # curr_index points to the start_input of the last completed channel scan that # was transferred between the board and the data buffer. Based on this, # calculate the first index we want to display using subtraction. first_index = max( curr_index - ((per_channel_display_count - 1) * chan_count), 0) # Add (up to) the latest 10 values for each channel to the text for data_index in range( first_index, first_index + min(chan_count * per_channel_display_count, curr_count)): raw_value = array[data_index] if self.ai_props.resolution <= 16: ULAIO01.eng_value = ul.to_eng_units( self.board_num, range_, raw_value) else: ULAIO01.eng_value = ul.to_eng_units_32( self.board_num, range_, raw_value) ULAIO01.channel_text[chan_num - low_chan] += ( '{:.3f}'.format(ULAIO01.eng_value) + "\n") self.datasheet() # custom datahandling if chan_num == high_chan: chan_num = low_chan else: chan_num += 1 # Update the labels for each channel for chan_num in range(low_chan, high_chan + 1): ULAIO01.chan_index = chan_num - low_chan self.chan_labels[ULAIO01.chan_index][ "text"] = ULAIO01.channel_text[ULAIO01.chan_index]
def display_values(self, range_, curr_index, curr_count): per_channel_display_count = 10 array = self.ctypes_array low_chan = self.low_chan high_chan = self.high_chan channel_text = [] # Add the headers for chan_num in range(low_chan, high_chan + 1): channel_text.append("Channel " + str(chan_num) + "\n") # If no data has been gathered, don't add data to the labels if curr_count > 1: chan_count = high_chan - low_chan + 1 chan_num = low_chan # curr_index points to the start of the last completed channel # scan that was transferred between the board and the data # buffer. Based on this, calculate the first index we want to # display using subtraction. first_index = max( curr_index - ((per_channel_display_count - 1) * chan_count), 0) # Add (up to) the latest 10 values for each channel to the text for data_index in range( first_index, first_index + min(chan_count * per_channel_display_count, curr_count)): if self.ai_info.resolution <= 16: eng_value = ul.to_eng_units(self.board_num, range_, array[data_index]) else: eng_value = ul.to_eng_units_32(self.board_num, range_, array[data_index]) channel_text[chan_num - low_chan] += '{:.3f}'.format(eng_value) + "\n" if chan_num == high_chan: chan_num = low_chan else: chan_num += 1 # Update the labels for each channel for chan_num in range(low_chan, high_chan + 1): chan_index = chan_num - low_chan self.chan_labels[chan_index]["text"] = channel_text[chan_index]
def stop_input(self): self.tempo = 2 # stop turning arena self.update_arena_output() status, curr_count, curr_index = ul.get_status(self.board_num, FunctionType.AIFUNCTION) my_array = self.ctypes_array # save all the collected data ul.stop_background(self.board_num, FunctionType.AIFUNCTION) open("KHZtext.txt", "w") # clear existing file endfile = open( "KHZtext.txt", "a+") # textfile that the data will be written to (kiloherztext) millisec = 0 # the time column parameter in milliseconds ULAIO01.txt_count = 0 # for the order of the KHZtext file self.period = 1 print("count", curr_count) for i in list( range(0, curr_count) ): # curr_count should represent the length of the ctypes_array eng_value = ul.to_eng_units(self.board_num, self.ai_props.available_ranges[0], my_array[i]) eng_value_proper = ( "%f " % (eng_value) ) # thats how it is supposed to be written into the txt file, but right now it isn't unicode endfile.write( eng_value_proper.decode("unicode-escape") ) # eng_value returns float, but after (4) floats all channels are printed (also: encode to utf8 format) ULAIO01.txt_count = ULAIO01.txt_count + 1 # thats why we need the count (know when to newline) if self.period < len( self.period_switch ) and i == self.period_switch[ self.period - 1]: # when we iterated to the point where a new period was started, we need to switch the period parameter self.period = self.period + 1 print("hat funktioniert", self.period) if ULAIO01.txt_count == ( (self.input_high_chan - self.input_low_chan) + 1): endfile.write(u"%d %d\n" % (millisec, self.period)) ULAIO01.txt_count = 0 millisec = millisec + 10 # for each loop the next millisecond is measured Beep(3000, 500)
def run_example(): board_num = 0 if use_device_detection: ul.ignore_instacal() if not util.config_first_detected_device(board_num): print("Could not find device.") return channel = 0 ai_props = AnalogInputProps(board_num) if ai_props.num_ai_chans < 1: util.print_unsupported_example(board_num) return ai_range = ai_props.available_ranges[0] try: # Get a value from the device if ai_props.resolution <= 16: # Use the a_in method for devices with a resolution <= 16 value = ul.a_in(board_num, channel, ai_range) # Convert the raw value to engineering units eng_units_value = ul.to_eng_units(board_num, ai_range, value) else: # Use the a_in_32 method for devices with a resolution > 16 # (optional parameter omitted) value = ul.a_in_32(board_num, channel, ai_range) # Convert the raw value to engineering units eng_units_value = ul.to_eng_units_32(board_num, ai_range, value) # Display the raw value print("Raw Value: " + str(value)) # Display the engineering value print("Engineering Value: " + '{:.3f}'.format(eng_units_value)) except ULError as e: util.print_ul_error(e) finally: if use_device_detection: ul.release_daq_device(board_num)
def readVoltage(self, gain=0): # Based on my understanding of the universal library source code and docs # The UL.AbIN gets inupt from the card and the cbtoEngUnits reads the # input as voltage voltageReadings = list() # print self.channelNumber ai_range = ULRange.BIP10VOLTS for i in range(0, self.channelNumber+1): # if i ==1: # voltage = 0 # short = 0 # else: short = ul.a_in(self.deviceNumber, i, ai_range) voltage = float(ul.to_eng_units(self.deviceNumber, gain, short)) voltageReadings.append(voltage) print str(short) + " " + str(voltage) # print UL.cbToEngUnits(self.getDeviceNumber(), 0, UL.cbAIn( # self.getDeviceNumber(), 0, gain)) # print UL.cbToEngUnits(self.getDeviceNumber(), 1, UL.cbAIn( # self.getDeviceNumber(), 1, gain)) time.sleep(.001) return voltageReadings
def update_value(self): channel = self.get_chan_num() ai_range = self.ai_props.available_ranges[0] try: if self.ai_props.resolution <= 16: value = ul.a_in(self.board_num, channel, ai_range) eng_value = ul.to_eng_units(self.board_num, ai_range, value) else: value = ul.a_in_32(self.board_num, channel, ai_range) eng_value = ul.to_eng_units_32(self.board_num, ai_range, value) self.value_label["text"] = str(value) self.eng_value_label["text"] = '{:.3f}'.format(eng_value) if self.running: self.after(100, self.update_value) except: pass
def update_value(self): channel = self.get_channel_num() ai_range = self.ai_info.supported_ranges[0] try: gain = self.ai_info.supported_ranges[0] trig_type = self.get_trigger_type() trig_value_eng = self.get_trigger_level() trig_value = ul.from_eng_units(self.board_num, gain, trig_value_eng) # Get a value from the device value = ul.a_trig(self.board_num, channel, trig_type, trig_value, gain) # Convert the raw value to engineering units eng_units_value = ul.to_eng_units(self.board_num, ai_range, value) # Display the raw value self.value_label["text"] = str(value) # Display the engineering value self.eng_value_label["text"] = '{:.3f}'.format(eng_units_value) except ULError as e: self.stop() show_ul_error(e)
input_mode = AnalogInputMode.DIFFERENTIAL value = ul.a_in(board_num, channel, input_mode) leave_loop = False ####reading from Clarity#### import win32com.client as win32 clar = win32.gencache.EnsureDispatch('ClarityII.CloudSensorII') while not leave_loop: try: # Get a value from the device value = ul.a_in(board_num, channel, input_mode) # Convert the raw value to engineering units V = ul.to_eng_units(board_num, input_mode, value) P = V * cf + inter measurement_datetime = dt.datetime.now(utc) measurement_time = measurement_datetime.strftime("%H:%M:%S.%f") measurement_date = measurement_datetime.strftime("%Y/%m/%d") Cloud = clar.CloudCondition Tout = clar.AmbientT WSPD = clar.Wind Rain = clar.RainCondition RH = clar.HumidityPercent Light = clar.DayCondition pprint = round(P, 2) vprint = round(V, 4) print(measurement_date + "," + measurement_time + "," + str(pprint) + "," + str(vprint) + "," + str(WSPD) + "," + str(Tout) + "," +
def readInductionVoltage(self): ai_range = ULRange.BIPPT156VOLTS value = ul.a_in(0, 2, ai_range) dec_value = ul.to_eng_units(0, ai_range, value) return dec_value * 64.103
def readFotodiode(self): ai_range = ULRange.BIPPT05VOLTS value = ul.a_in(0, 3, ai_range) dec_value = ul.to_eng_units(0, ai_range, value) return dec_value * 200
def readShuntVoltage(self): ai_range = ULRange.BIP1PT67VOLTS value = ul.a_in(0, 1, ai_range) dec_value = ul.to_eng_units(0, ai_range, value) return dec_value * 5.988
def readChannel(self, ch): ai_range = ULRange.BIP5VOLTS value = ul.a_in(0, ch, ai_range) dec_value = ul.to_eng_units(0, ai_range, value) return dec_value * 2
def run_example(): # By default, the example detects and displays all available devices and # selects the first device listed. Use the dev_id_list variable to filter # detected devices by device ID (see UL documentation for device IDs). # If use_device_detection is set to False, the board_num variable needs to # match the desired board number configured with Instacal. use_device_detection = True dev_id_list = [] board_num = 0 rate = 100 points_per_channel = 10 memhandle = None try: if use_device_detection: config_first_detected_device(board_num, dev_id_list) daq_dev_info = DaqDeviceInfo(board_num) if not daq_dev_info.supports_analog_input: raise Exception('Error: The DAQ device does not support ' 'analog input') print('\nActive DAQ device: ', daq_dev_info.product_name, ' (', daq_dev_info.unique_id, ')\n', sep='') ai_info = daq_dev_info.get_ai_info() low_chan = 0 high_chan = min(3, ai_info.num_chans - 1) num_chans = high_chan - low_chan + 1 total_count = points_per_channel * num_chans ai_range = ai_info.supported_ranges[0] scan_options = ScanOptions.FOREGROUND if ScanOptions.SCALEDATA in ai_info.supported_scan_options: # If the hardware supports the SCALEDATA option, it is easiest to # use it. scan_options |= ScanOptions.SCALEDATA memhandle = ul.scaled_win_buf_alloc(total_count) # Convert the memhandle to a ctypes array. # Use the memhandle_as_ctypes_array_scaled method for scaled # buffers. ctypes_array = cast(memhandle, POINTER(c_double)) elif ai_info.resolution <= 16: # Use the win_buf_alloc method for devices with a resolution <= 16 memhandle = ul.win_buf_alloc(total_count) # Convert the memhandle to a ctypes array. # Use the memhandle_as_ctypes_array method for devices with a # resolution <= 16. ctypes_array = cast(memhandle, POINTER(c_ushort)) else: # Use the win_buf_alloc_32 method for devices with a resolution > 16 memhandle = ul.win_buf_alloc_32(total_count) # Convert the memhandle to a ctypes array. # Use the memhandle_as_ctypes_array_32 method for devices with a # resolution > 16 ctypes_array = cast(memhandle, POINTER(c_ulong)) # Note: the ctypes array will no longer be valid after win_buf_free is # called. # A copy of the buffer can be created using win_buf_to_array or # win_buf_to_array_32 before the memory is freed. The copy can be used # at any time. # Check if the buffer was successfully allocated if not memhandle: raise Exception('Error: Failed to allocate memory') # Start the scan ul.a_in_scan(board_num, low_chan, high_chan, total_count, rate, ai_range, memhandle, scan_options) print('Scan completed successfully. Data:') # Create a format string that aligns the data in columns row_format = '{:>5}' + '{:>10}' * num_chans # Print the channel name headers labels = ['Index'] for ch_num in range(low_chan, high_chan + 1): labels.append('CH' + str(ch_num)) print(row_format.format(*labels)) # Print the data data_index = 0 for index in range(points_per_channel): display_data = [index] for _ in range(num_chans): if ScanOptions.SCALEDATA in scan_options: # If the SCALEDATA ScanOption was used, the values # in the array are already in engineering units. eng_value = ctypes_array[data_index] else: # If the SCALEDATA ScanOption was NOT used, the # values in the array must be converted to # engineering units using ul.to_eng_units(). eng_value = ul.to_eng_units(board_num, ai_range, ctypes_array[data_index]) data_index += 1 display_data.append('{:.3f}'.format(eng_value)) # Print this row print(row_format.format(*display_data)) except Exception as e: print('\n', e) finally: if memhandle: # Free the buffer in a finally block to prevent a memory leak. ul.win_buf_free(memhandle) if use_device_detection: ul.release_daq_device(board_num)
def run_example(): board_num = 0 rate = 100 points_per_channel = 10 if use_device_detection: ul.ignore_instacal() if not util.config_first_detected_device(board_num): print("Could not find device.") return ai_props = AnalogInputProps(board_num) if ai_props.num_ai_chans < 1: util.print_unsupported_example(board_num) return low_chan = 0 high_chan = min(3, ai_props.num_ai_chans - 1) num_chans = high_chan - low_chan + 1 total_count = points_per_channel * num_chans ai_range = ai_props.available_ranges[0] scan_options = ScanOptions.FOREGROUND if ScanOptions.SCALEDATA in ai_props.supported_scan_options: # If the hardware supports the SCALEDATA option, it is easiest to # use it. scan_options |= ScanOptions.SCALEDATA memhandle = ul.scaled_win_buf_alloc(total_count) # Convert the memhandle to a ctypes array. # Use the memhandle_as_ctypes_array_scaled method for scaled # buffers. ctypes_array = util.memhandle_as_ctypes_array_scaled(memhandle) elif ai_props.resolution <= 16: # Use the win_buf_alloc method for devices with a resolution <= 16 memhandle = ul.win_buf_alloc(total_count) # Convert the memhandle to a ctypes array. # Use the memhandle_as_ctypes_array method for devices with a # resolution <= 16. ctypes_array = util.memhandle_as_ctypes_array(memhandle) else: # Use the win_buf_alloc_32 method for devices with a resolution > 16 memhandle = ul.win_buf_alloc_32(total_count) # Convert the memhandle to a ctypes array. # Use the memhandle_as_ctypes_array_32 method for devices with a # resolution > 16 ctypes_array = util.memhandle_as_ctypes_array_32(memhandle) # Note: the ctypes array will no longer be valid after win_buf_free is # called. # A copy of the buffer can be created using win_buf_to_array or # win_buf_to_array_32 before the memory is freed. The copy can be used # at any time. # Check if the buffer was successfully allocated if not memhandle: print("Failed to allocate memory.") return try: # Start the scan ul.a_in_scan(board_num, low_chan, high_chan, total_count, rate, ai_range, memhandle, scan_options) print("Scan completed successfully. Data:") # Create a format string that aligns the data in columns row_format = "{:>5}" + "{:>10}" * num_chans # Print the channel name headers labels = [] labels.append("Index") for ch_num in range(low_chan, high_chan + 1): labels.append("CH" + str(ch_num)) print(row_format.format(*labels)) # Print the data data_index = 0 for index in range(points_per_channel): display_data = [index] for _ in range(num_chans): if ScanOptions.SCALEDATA in scan_options: # If the SCALEDATA ScanOption was used, the values # in the array are already in engineering units. eng_value = ctypes_array[data_index] else: # If the SCALEDATA ScanOption was NOT used, the # values in the array must be converted to # engineering units using ul.to_eng_units(). eng_value = ul.to_eng_units(board_num, ai_range, ctypes_array[data_index]) data_index += 1 display_data.append('{:.3f}'.format(eng_value)) # Print this row print(row_format.format(*display_data)) except ULError as e: util.print_ul_error(e) finally: # Free the buffer in a finally block to prevent errors from causing # a memory leak. ul.win_buf_free(memhandle) if use_device_detection: ul.release_daq_device(board_num)
def run(): DaqDeviceScan(master=tk.Tk()).mainloop() board_num = 0 rate = 1000 points_per_channel = 30 if use_device_detection: ul.ignore_instacal() if not configDevice(board_num): print("Gerät konnte nicht gefunden werden!") return ai_props = aiProps(board_num) low_channel = 0 high_channel = min(7, ai_props.num_ai_chans - 1) num_channels = high_channel - low_channel + 1 total_amount = points_per_channel * num_channels ai_range = ai_props.available_ranges[0] scan_opt = ScanOptions.FOREGROUND if ScanOptions.SCALEDATA in ai_props.supported_scan_options: scan_opt |= ScanOptions.SCALEDATA memhandle = ul.scaled_win_buf_alloc(total_amount) c_array = memhandle_as_ctypes_array_scaled(memhandle) elif ai_props.resolution <= 16: memhandle = ul.win_buf_alloc(total_amount) c_array = memhandle_as_ctypes_array(memhandle) else: memhandle = ul.win_buf_alloc_32(memhandle) if not memhandle: print("Speicher konnte nicht allokiert werden") restart = False try: wr = csv.writer(open("test5.csv","w"),delimiter=";") ul.a_in_scan(board_num, low_channel, high_channel, total_amount, rate, ai_range, memhandle, scan_opt) print("Scan erfolgreich!") print("Daten: ") test = ul.a_in_32(board_num, 0, ai_range, scan_opt) test = ul.to_eng_units_32(board_num, ai_range, test) print("test value:") print(test) row_format = "{:>5}" + "{:>10}" * num_channels labels = [] labels.append("Index") for ch_num in range(low_channel, high_channel + 1): labels.append("CH" + str(ch_num)) print(row_format.format(*labels)) data_index = 0 for index in range(points_per_channel): display_data = [index] for _ in range(num_channels): if ScanOptions.SCALEDATA in scan_opt: eng_value = c_array[data_index] else: eng_value = ul.to_eng_units( board_num, ai_range, c_array[data_index]) data_index += 1 display_data.append('{:.3f}'.format(eng_value)) wr.writerow(display_data) print(row_format.format(*display_data)) except ULError as e: pass finally: ul.win_buf_free(memhandle) if use_device_detection: ul.release_daq_device(board_num)
ts = time.time() # store live values into an empty list bit_values = [] eng_units_values = [] conc_values = [] # convert from analog to digital value bit_value = ul.a_in(board_num, channel, ai_range) # append to our list bit_values.append(bit_value) # convert from digital back to analog eng_units_value = ul.to_eng_units(board_num, ai_range, bit_value) # append to its list eng_units_values.append(eng_units_value) # determine our concentration value based on the V_reference, V_fullscale, and our upper detection limit at fullscale conc_value = (eng_units_value / fullscale) * upper_limit # append these to our list conc_values.append(conc_value) # force system to sleep for a millisecond time.sleep(.001) # calculate averages for each parameter throughout the sampling window bit_avg = avg(bit_values) eng_avg = avg(eng_units_values)
def run_example(): board_num = 0 rate = 100 points_per_channel = 1000 if use_device_detection: ul.ignore_instacal() if not util.config_first_detected_device(board_num): print("Could not find device.") return ai_props = AnalogInputProps(board_num) if ai_props.num_ai_chans < 1: util.print_unsupported_example(board_num) return low_chan = 0 high_chan = min(3, ai_props.num_ai_chans - 1) num_chans = high_chan - low_chan + 1 total_count = points_per_channel * num_chans ai_range = ai_props.available_ranges[0] scan_options = ScanOptions.BACKGROUND if ScanOptions.SCALEDATA in ai_props.supported_scan_options: # If the hardware supports the SCALEDATA option, it is easiest to # use it. scan_options |= ScanOptions.SCALEDATA memhandle = ul.scaled_win_buf_alloc(total_count) # Convert the memhandle to a ctypes array. # Use the memhandle_as_ctypes_array_scaled method for scaled # buffers. ctypes_array = util.memhandle_as_ctypes_array_scaled(memhandle) elif ai_props.resolution <= 16: # Use the win_buf_alloc method for devices with a resolution <= 16 memhandle = ul.win_buf_alloc(total_count) # Convert the memhandle to a ctypes array. # Use the memhandle_as_ctypes_array method for devices with a # resolution <= 16. ctypes_array = util.memhandle_as_ctypes_array(memhandle) else: # Use the win_buf_alloc_32 method for devices with a resolution > 16 memhandle = ul.win_buf_alloc_32(total_count) # Convert the memhandle to a ctypes array. # Use the memhandle_as_ctypes_array_32 method for devices with a # resolution > 16 ctypes_array = util.memhandle_as_ctypes_array_32(memhandle) # Note: the ctypes array will no longer be valid after win_buf_free is # called. # A copy of the buffer can be created using win_buf_to_array or # win_buf_to_array_32 before the memory is freed. The copy can be used # at any time. # Check if the buffer was successfully allocated if not memhandle: print("Failed to allocate memory.") return try: # Start the scan ul.a_in_scan(board_num, low_chan, high_chan, total_count, rate, ai_range, memhandle, scan_options) # Create a format string that aligns the data in columns row_format = "{:>12}" * num_chans # Print the channel name headers labels = [] for ch_num in range(low_chan, high_chan + 1): labels.append("CH" + str(ch_num)) print(row_format.format(*labels)) # Start updating the displayed values status, curr_count, curr_index = ul.get_status(board_num, FunctionType.AIFUNCTION) while status != Status.IDLE: # Make sure a data point is available for display. if curr_count > 0: # curr_index points to the start of the last completed # channel scan that was transferred between the board and # the data buffer. Display the latest value for each # channel. display_data = [] for data_index in range(curr_index, curr_index + num_chans): if ScanOptions.SCALEDATA in scan_options: # If the SCALEDATA ScanOption was used, the values # in the array are already in engineering units. eng_value = ctypes_array[data_index] else: # If the SCALEDATA ScanOption was NOT used, the # values in the array must be converted to # engineering units using ul.to_eng_units(). eng_value = ul.to_eng_units(board_num, ai_range, ctypes_array[data_index]) display_data.append('{:.3f}'.format(eng_value)) print(row_format.format(*display_data)) # Wait a while before adding more values to the display. time.sleep(0.5) status, curr_count, curr_index = ul.get_status( board_num, FunctionType.AIFUNCTION) # Stop the background operation (this is required even if the # scan completes successfully) ul.stop_background(board_num, FunctionType.AIFUNCTION) print("Scan completed successfully.") except ULError as e: util.print_ul_error(e) finally: # Free the buffer in a finally block to prevent errors from causing # a memory leak. ul.win_buf_free(memhandle) if use_device_detection: ul.release_daq_device(board_num)