def start_scan(self): rate = 100 points_per_channel = 10 total_count = points_per_channel * self.num_chans # Allocate a buffer for the scan memhandle = ul.win_buf_alloc(total_count) # Check if the buffer was successfully allocated if not memhandle: messagebox.showerror("Error", "Failed to allocate memory") self.start_button["state"] = tk.NORMAL return try: # Configure the digital port for input ul.d_config_port(self.board_num, DigitalPortType.FIRSTPORTA, DigitalIODirection.IN) # Configure the counter channel ul.c_config_scan(self.board_num, 0, CounterMode.STOP_AT_MAX, CounterDebounceTime.DEBOUNCE_NONE, 0, CounterEdgeDetection.RISING_EDGE, CounterTickSize.TICK20PT83ns, 0) # Run the scan ul.daq_in_scan(self.board_num, self.chan_list, self.chan_type_list, self.gain_list, self.num_chans, rate, 0, total_count, memhandle, 0) # Convert the TC values (optional parameter omitted) err, temp_data_array = ul.get_tc_values(self.board_num, self.chan_list, self.chan_type_list, self.num_chans, memhandle, 0, points_per_channel, TempScale.CELSIUS) if err == ErrorCode.OUTOFRANGE: messagebox.showwarning("Warning", "Temperature data is out of range") # Cast the memhandle to a ctypes pointer # Note: the ctypes array will only be valid until win_buf_free # is called. array = self.memhandle_as_ctypes_array(memhandle) # Display the values self.display_values(array, temp_data_array, total_count) except ULError as e: self.show_ul_error(e) finally: # Free the allocated memory ul.win_buf_free(memhandle) self.start_button["state"] = tk.NORMAL
def start_scan(self): rate = 100 points_per_channel = 100 total_count = points_per_channel * self.num_chans scan_options = (ScanOptions.BACKGROUND | ScanOptions.CONTINUOUS | ScanOptions.EXTTRIGGER) # Allocate a buffer for the scan self.memhandle = ul.win_buf_alloc(total_count) # Check if the buffer was successfully allocated if not self.memhandle: messagebox.showerror("Error", "Failed to allocate memory") self.start_button["state"] = tk.NORMAL return try: # Set the start trigger settings ul.daq_set_trigger(self.board_num, TriggerSource.ANALOG_SW, TriggerSensitivity.RISING_EDGE, self.chan_list[0], self.chan_type_list[0], self.gain_list[0], 2, 0, TriggerEvent.START) # Set the stop trigger settings ul.daq_set_trigger(self.board_num, TriggerSource.COUNTER, TriggerSensitivity.ABOVE_LEVEL, self.chan_list[2], self.chan_type_list[2], self.gain_list[2], 2, 0, TriggerEvent.START) # Run the scan ul.daq_in_scan(self.board_num, self.chan_list, self.chan_type_list, self.gain_list, self.num_chans, rate, 0, total_count, self.memhandle, scan_options) # Cast the memhandle to a ctypes pointer # Note: the ctypes array will only be valid until win_buf_free # is called. # A copy of the buffer can be created using win_buf_to_array # before the memory is freed. The copy can be used at any time. self.array = self.memhandle_as_ctypes_array(self.memhandle) except ULError as e: # Free the allocated memory ul.win_buf_free(self.memhandle) self.show_ul_error(e) return # Start updating the displayed values self.update_displayed_values()
def start_scan(self): rate = 100 points_per_channel = 100 total_count = points_per_channel * self.num_chans scan_options = ScanOptions.BACKGROUND | ScanOptions.CONTINUOUS # Allocate a buffer for the scan if self.resolution <= 16: self.memhandle = ul.win_buf_alloc(total_count) else: self.memhandle = ul.win_buf_alloc_32(total_count) # Check if the buffer was successfully allocated if not self.memhandle: messagebox.showerror("Error", "Failed to allocate memory") self.start_button["state"] = tk.NORMAL return try: # Run the scan ul.daq_in_scan( self.board_num, self.chan_list, self.chan_type_list, self.gain_list, self.num_chans, rate, 0, total_count, self.memhandle, scan_options) # Cast the memhandle to a ctypes pointer # Note: the ctypes array will only be valid until 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. if self.resolution <= 16: # Use the memhandle_as_ctypes_array method for devices with a # resolution <= 16 self.array = self.memhandle_as_ctypes_array(self.memhandle) else: # Use the memhandle_as_ctypes_array_32 method for devices with a # resolution > 16 self.array = self.memhandle_as_ctypes_array_32(self.memhandle) except ULError as e: # Free the allocated memory ul.win_buf_free(self.memhandle) self.show_ul_error(e) return # Start updating the displayed values self.update_displayed_values()
def start_scan(self): rate = 100 points_per_channel = 10 total_count = points_per_channel * self.num_chans # Allocate a buffer for the scan if self.resolution <= 16: memhandle = ul.win_buf_alloc(total_count) else: memhandle = ul.win_buf_alloc_32(total_count) # Check if the buffer was successfully allocated if not memhandle: messagebox.showerror("Error", "Failed to allocate memory") self.start_button["state"] = tk.NORMAL return try: # Run the scan ul.daq_in_scan(self.board_num, self.chan_list, self.chan_type_list, self.gain_list, self.num_chans, rate, 0, total_count, memhandle, 0) # Cast the memhandle to a ctypes pointer # Note: the ctypes array will only be valid until 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. if self.resolution <= 16: # Use the memhandle_as_ctypes_array method for devices with a # resolution <= 16 array = cast(memhandle, POINTER(c_ushort)) else: # Use the memhandle_as_ctypes_array_32 method for devices with # a resolution > 16 array = cast(memhandle, POINTER(c_ulong)) # Display the values self.display_values(array, total_count) except ULError as e: show_ul_error(e) finally: # Free the allocated memory ul.win_buf_free(memhandle) self.start_button["state"] = tk.NORMAL
def start_scan(self): rate = 100 points_per_channel = 100 total_count = points_per_channel * self.num_chans scan_options = ScanOptions.BACKGROUND | ScanOptions.CONTINUOUS # Allocate a buffer for the scan self.memhandle = ul.win_buf_alloc(total_count) # Check if the buffer was successfully allocated if not self.memhandle: messagebox.showerror("Error", "Failed to allocate memory") self.start_button["state"] = tk.NORMAL return try: # Configure the setpoints ul.daq_set_setpoints(self.board_num, self.limit_a_list, self.limit_b_list, self.setpoint_flags_list, self.setpoint_output_list, self.output_1_list, self.output_2_list, self.output_mask_1_list, self.output_mask_2_list, self.setpoint_count) # Run the scan ul.daq_in_scan(self.board_num, self.chan_list, self.chan_type_list, self.gain_list, self.num_chans, rate, 0, total_count, self.memhandle, scan_options) # Cast the memhandle to a ctypes pointer # Note: the ctypes array will only be valid until win_buf_free # is called. # A copy of the buffer can be created using win_buf_to_array # before the memory is freed. The copy can be used at any time. self.array = cast(self.memhandle, POINTER(c_ushort)) except ULError as e: # Free the allocated memory ul.win_buf_free(self.memhandle) show_ul_error(e) return # Start updating the displayed values self.update_displayed_values()
def run_example(): board_num = 0 rate = 100 points_per_channel = 100 if use_device_detection: ul.ignore_instacal() if not util.config_first_detected_device_of_type( board_num, supported_pids): print("Could not find a supported device.") return scan_options = ScanOptions.FOREGROUND | ScanOptions.SCALEDATA # Create the daq_in_scan channel configuration lists chan_list = [] chan_type_list = [] gain_list = [] # Analog channels must be first in the list chan_list.append(1) chan_type_list.append(ChannelType.ANALOG_SE) gain_list.append(ULRange.BIP10VOLTS) chan_list.append(2) chan_type_list.append(ChannelType.ANALOG_DIFF) gain_list.append(ULRange.BIP10VOLTS) chan_list.append(DigitalPortType.AUXPORT) chan_type_list.append(ChannelType.DIGITAL) gain_list.append(ULRange.NOTUSED) chan_list.append(0) chan_type_list.append(ChannelType.CTR) gain_list.append(ULRange.NOTUSED) num_chans = len(chan_list) total_count = num_chans * points_per_channel # Allocate memory for the scan and cast it to a ctypes array pointer memhandle = ul.scaled_win_buf_alloc(total_count) ctypes_array = util.memhandle_as_ctypes_array_scaled(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.daq_in_scan(board_num, chan_list, chan_type_list, gain_list, num_chans, rate, 0, total_count, 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_index in range(num_chans): channel_label = { ChannelType.ANALOG: lambda: "AI" + str(chan_list[ch_index]), ChannelType.ANALOG_DIFF: lambda: "AI" + str(chan_list[ch_index]), ChannelType.ANALOG_SE: lambda: "AI" + str(chan_list[ch_index]), ChannelType.DIGITAL: lambda: chan_list[ch_index].name, ChannelType.CTR: lambda: "CI" + str(chan_list[ch_index]), }[chan_type_list[ch_index]]() labels.append(channel_label) print(row_format.format(*labels)) # Print the data data_index = 0 for index in range(points_per_channel): display_data = [index] for ch_index in range(num_chans): data_label = { ChannelType.ANALOG: lambda: '{:.3f}'.format(ctypes_array[data_index]), ChannelType.ANALOG_DIFF: lambda: '{:.3f}'.format(ctypes_array[data_index]), ChannelType.ANALOG_SE: lambda: '{:.3f}'.format(ctypes_array[data_index]), ChannelType.DIGITAL: lambda: '{:d}'.format(int(ctypes_array[data_index])), ChannelType.CTR: lambda: '{:d}'.format(int(ctypes_array[data_index])), }[chan_type_list[ch_index]]() display_data.append(data_label) data_index += 1 # 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 _readBG(self, file_name): # file_name = 'C:\\Users\\PVGroup\\Desktop\\frgmapper\\Data\\20190913\\test.data' # totalCount = len(self.channels['Number']) * self.__countsPerChannel # memhandle = ul.win_buf_alloc_64(totalCount) # ctypesArray = ctypes.cast(memhandle, ctypes.POINTER(ctypes.c_ulonglong)) # The size of the UL buffer to create, in seconds buffer_size_seconds = 2 # The number of buffers to write. After this number of UL buffers are # written to file, the example will be stopped. num_buffers_to_write = 2 low_chan = 0 high_chan = 1 num_chans = high_chan - low_chan + 1 # Create a circular buffer that can hold buffer_size_seconds worth of # data, or at least 10 points (this may need to be adjusted to prevent # a buffer overrun) points_per_channel = max(self.__rate * buffer_size_seconds, 10) # Some hardware requires that the total_count is an integer multiple # of the packet size. For this case, calculate a points_per_channel # that is equal to or just above the points_per_channel selected # which matches that requirement. # if ai_props.continuous_requires_packet_size_multiple: # packet_size = ai_props.packet_size # remainder = points_per_channel % packet_size # if remainder != 0: # points_per_channel += packet_size - remainder ul_buffer_count = points_per_channel * num_chans # Write the UL buffer to the file num_buffers_to_write times. points_to_write = ul_buffer_count * num_buffers_to_write # When handling the buffer, we will read 1/10 of the buffer at a time write_chunk_size = int(ul_buffer_count / 100) if self.useExtClock: scan_options = ScanOptions.BACKGROUND | ScanOptions.CONTINUOUS | ScanOptions.SCALEDATA | ScanOptions.EXTCLOCK else: scan_options = ScanOptions.BACKGROUND | ScanOptions.CONTINUOUS | ScanOptions.SCALEDATA memhandle = ul.scaled_win_buf_alloc(ul_buffer_count) # Allocate an array of doubles temporary storage of the data write_chunk_array = (c_double * write_chunk_size)() # Check if the buffer was successfully allocated if not memhandle: print("Failed to allocate memory.") return try: # Start the scan ul.daq_in_scan(board_num=self.board_num, chan_list=self.channels['Number'], chan_type_list=self.channels['Type'], gain_list=self.channels['Gain'], chan_count=len(self.channels['Number']), rate=self.__rate, pretrig_count=0, total_count=ul_buffer_count, memhandle=memhandle, options=scan_options) status = Status.IDLE # Wait for the scan to start fully while (status == Status.IDLE): status, _, _ = ul.get_status(board_num, FunctionType.DAQIFUNCTION) # Create a file for storing the data with open(file_name, 'w') as f: # print('Writing data to ' + file_name, end='') # Write a header to the file # for chan_num in range(low_chan, high_chan + 1): # f.write('Channel ' + str(chan_num) + ',') # f.write(u'\n') # Start the write loop prev_count = 0 prev_index = 0 write_ch_num = low_chan keepReading = True while status != Status.IDLE and keepReading: # Get the latest counts status, curr_count, _ = ul.get_status( board_num, FunctionType.DAQIFUNCTION) new_data_count = curr_count - prev_count # Check for a buffer overrun before copying the data, so # that no attempts are made to copy more than a full buffer # of data if new_data_count > ul_buffer_count: # Print an error and stop writing ul.stop_background(board_num, FunctionType.DAQIFUNCTION) print("A buffer overrun occurred") break # Check if a chunk is available if new_data_count > write_chunk_size: wrote_chunk = True # Copy the current data to a new array # Check if the data wraps around the end of the UL # buffer. Multiple copy operations will be required. if prev_index + write_chunk_size > ul_buffer_count - 1: first_chunk_size = ul_buffer_count - prev_index second_chunk_size = (write_chunk_size - first_chunk_size) # Copy the first chunk of data to the # write_chunk_array ul.scaled_win_buf_to_array(memhandle, write_chunk_array, prev_index, first_chunk_size) # Create a pointer to the location in # write_chunk_array where we want to copy the # remaining data second_chunk_pointer = cast( addressof(write_chunk_array) + first_chunk_size * sizeof(c_double), POINTER(c_double)) # Copy the second chunk of data to the # write_chunk_array ul.scaled_win_buf_to_array(memhandle, second_chunk_pointer, 0, second_chunk_size) else: # Copy the data to the write_chunk_array ul.scaled_win_buf_to_array(memhandle, write_chunk_array, prev_index, write_chunk_size) # Check for a buffer overrun just after copying the data # from the UL buffer. This will ensure that the data was # not overwritten in the UL buffer before the copy was # completed. This should be done before writing to the # file, so that corrupt data does not end up in it. status, curr_count, _ = ul.get_status( board_num, FunctionType.DAQIFUNCTION) if curr_count - prev_count > ul_buffer_count: # Print an error and stop writing ul.stop_background(board_num, FunctionType.DAQIFUNCTION) print("A buffer overrun occurred") break for i in range(write_chunk_size): f.write(str(write_chunk_array[i])) write_ch_num += 1 if write_ch_num == high_chan + 1: write_ch_num = low_chan f.write(u'\n') else: f.write(',') else: wrote_chunk = False if wrote_chunk: # Increment prev_count by the chunk size prev_count += write_chunk_size # Increment prev_index by the chunk size prev_index += write_chunk_size # Wrap prev_index to the size of the UL buffer prev_index %= ul_buffer_count if not self.acquiringBG: #make sure to wait until after writing to check if we should stop to avoid truncation keepReading = False # if prev_count >= points_to_write: # break # f.write('-----\n') # print('.', end='') else: # Wait a short amount of time for more data to be # acquired. time.sleep(0.01) ul.stop_background(board_num, FunctionType.DAQIFUNCTION) except ULError as e: pass finally: # print('Done') # Free the buffer in a finally block to prevent errors from causing # a memory leak. ul.win_buf_free(memhandle)
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 = [317, 318] # USB-1808 = 317, USB-1808X = 318 board_num = 0 # Supported PIDs for the USB-1808 Series rate = 100 points_per_channel = 100 memhandle = None try: if use_device_detection: config_first_detected_device(board_num, dev_id_list) daq_dev_info = DaqDeviceInfo(board_num) print('\nActive DAQ device: ', daq_dev_info.product_name, ' (', daq_dev_info.unique_id, ')\n', sep='') scan_options = ScanOptions.FOREGROUND | ScanOptions.SCALEDATA # Create the daq_in_scan channel configuration lists chan_list = [] chan_type_list = [] gain_list = [] # Analog channels must be first in the list chan_list.append(1) chan_type_list.append(ChannelType.ANALOG_SE) gain_list.append(ULRange.BIP10VOLTS) chan_list.append(2) chan_type_list.append(ChannelType.ANALOG_DIFF) gain_list.append(ULRange.BIP10VOLTS) chan_list.append(DigitalPortType.AUXPORT) chan_type_list.append(ChannelType.DIGITAL) gain_list.append(ULRange.NOTUSED) chan_list.append(0) chan_type_list.append(ChannelType.CTR) gain_list.append(ULRange.NOTUSED) num_chans = len(chan_list) total_count = num_chans * points_per_channel # Allocate memory for the scan and cast it to a ctypes array pointer memhandle = ul.scaled_win_buf_alloc(total_count) ctypes_array = cast(memhandle, POINTER(c_double)) # 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.daq_in_scan( board_num, chan_list, chan_type_list, gain_list, num_chans, rate, 0, total_count, 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_index in range(num_chans): channel_label = { ChannelType.ANALOG: lambda: 'AI' + str(chan_list[ch_index]), ChannelType.ANALOG_DIFF: lambda: 'AI' + str(chan_list[ch_index]), ChannelType.ANALOG_SE: lambda: 'AI' + str(chan_list[ch_index]), ChannelType.DIGITAL: lambda: chan_list[ch_index].name, ChannelType.CTR: lambda: 'CI' + str(chan_list[ch_index]), }[chan_type_list[ch_index]]() labels.append(channel_label) print(row_format.format(*labels)) # Print the data data_index = 0 for index in range(points_per_channel): display_data = [index] for ch_index in range(num_chans): data_label = { ChannelType.ANALOG: lambda: '{:.3f}'.format(ctypes_array[data_index]), ChannelType.ANALOG_DIFF: lambda: '{:.3f}'.format(ctypes_array[data_index]), ChannelType.ANALOG_SE: lambda: '{:.3f}'.format(ctypes_array[data_index]), ChannelType.DIGITAL: lambda: '{:d}'.format(int(ctypes_array[data_index])), ChannelType.CTR: lambda: '{:d}'.format(int(ctypes_array[data_index])), }[chan_type_list[ch_index]]() display_data.append(data_label) data_index += 1 # 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)