コード例 #1
0
    def update_input_displayed_values(self, range_):
        # Get the status from the device
        status, curr_count, curr_index = ul.get_status(self.board_num,
                                                       FunctionType.AIFUNCTION)

        # Display the status info
        self.update_input_status_labels(status, curr_count, curr_index)

        # Update period if necessary
        self.update_input_period(curr_count)

        # Display the values
        self.display_input_values(range_, curr_index, curr_count)

        # Open the directory text file
        self.textfile = open("Rawtext.txt",
                             "a+")  # textfile that the data will be written to

        # Function for the writing of the complete buffer to a text file and stopping the process
        if curr_count >= self.test_time() - 100:
            self.full_file()

        # Call this method again until the stop_input button is pressed
        if status == Status.RUNNING:
            self.after(10, self.update_input_displayed_values, range_)
        else:
            # Free the allocated memory
            ul.win_buf_free(self.input_memhandle)
            self.set_input_ui_idle_state()
コード例 #2
0
ファイル: DaqInScan03.py プロジェクト: conandewitt/lotus
    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
コード例 #3
0
ファイル: ULAI10.py プロジェクト: cullenmq/shearTest
    def scan_loop(self):
        rate = 100
        points_per_channel = 10
        low_chan = 0  # Ignored by a_in_scan when queue is enabled
        high_chan = 3  # Ignored by a_in_scan when queue is enabled
        num_channels = high_chan - low_chan + 1
        total_count = points_per_channel * num_channels

        # Ignored by a_in_scan when queue is enabled
        range_ = self.ai_props.available_ranges[0]

        # Allocate a buffer for the scan
        if self.ai_props.resolution <= 16:
            # Use the win_buf_alloc method for devices with a resolution <= 16
            memhandle = ul.win_buf_alloc(total_count)
        else:
            # Use the win_buf_alloc_32 method for devices with a resolution >
            # 16
            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")
            return

        try:
            # Run the scan
            ul.a_in_scan(self.board_num, low_chan, high_chan, total_count,
                         rate, range_, memhandle, 0)

            # Convert the memhandle to a ctypes array
            # 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.ai_props.resolution <= 16:
                # Use the memhandle_as_ctypes_array method for devices with a
                # resolution <= 16
                array = self.memhandle_as_ctypes_array(memhandle)
            else:
                # Use the memhandle_as_ctypes_array_32 method for devices with
                # a resolution > 16
                array = self.memhandle_as_ctypes_array_32(memhandle)

            # Display the values
            self.display_values(array, total_count)

            self.after(1000, self.scan_loop)
        except ULError as e:
            self.show_ul_error(e)
        finally:
            # Free the allocated memory
            ul.win_buf_free(memhandle)
コード例 #4
0
ファイル: _daq.py プロジェクト: eparsonnet93/ekpmeasure
	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
コード例 #5
0
ファイル: ULAO04.py プロジェクト: conandewitt/lotus
    def update_displayed_values(self):
        # Get the status from the device
        status, curr_count, curr_index = ul.get_status(self.board_num,
                                                       FunctionType.AOFUNCTION)

        # Display the status info
        self.update_status_labels(status, curr_count, curr_index)

        # Call this method again until the stop button is pressed
        if status == Status.RUNNING:
            self.after(100, self.update_displayed_values)
        else:
            # Free the allocated memory
            ul.win_buf_free(self.memhandle)
            self.set_ui_idle_state()
コード例 #6
0
ファイル: ULAI15.py プロジェクト: conandewitt/lotus
    def start_scan(self):
        low_chan = self.get_low_channel_num()
        high_chan = self.get_high_channel_num()

        if low_chan > high_chan:
            messagebox.showerror(
                "Error",
                "Low Channel Number must be greater than or equal to High "
                "Channel Number")
            self.start_button["state"] = tk.NORMAL
            return

        rate = 100
        points_per_channel = 10
        num_channels = high_chan - low_chan + 1
        total_count = points_per_channel * num_channels

        range_ = self.ai_props.available_ranges[0]

        # Allocate a buffer for the scan
        memhandle = ul.scaled_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

        # Convert the memhandle to a ctypes array
        # Note: the ctypes array will only be valid until win_buf_free
        # is called.
        # A copy of the buffer can be created using scaled_win_buf_to_array
        # before the memory is freed. The copy can be used at any time.
        array = self.memhandle_as_ctypes_array_scaled(memhandle)

        try:
            # Run the scan
            ul.a_in_scan(self.board_num, low_chan, high_chan, total_count,
                         rate, range_, memhandle, ScanOptions.SCALEDATA)

            # Display the values
            self.display_values(array, total_count, low_chan, high_chan)
        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
コード例 #7
0
ファイル: DaqSetTrigger01.py プロジェクト: conandewitt/lotus
    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()
コード例 #8
0
    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()
コード例 #9
0
    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
コード例 #10
0
ファイル: CInScan03.py プロジェクト: cullenmq/shearTest
    def start_scan(self):
        rate = 100
        total_count = 10

        # Allocate a buffer for the scan
        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:
            mode = CounterMode.ENCODER + CounterMode.ENCODER_MODE_X1 \
                + CounterMode.ENCODER_MODE_CLEAR_ON_Z_ON
            debounce_time = CounterDebounceTime.DEBOUNCE_NONE
            debounce_mode = 0
            edge_detection = CounterEdgeDetection.RISING_EDGE
            tick_size = CounterTickSize.TICK20PT83ns
            mapped_channel = 2

            # Configure the first counter channel for Encoder mode
            ul.c_config_scan(self.board_num, self.chan_num, mode,
                             debounce_time, debounce_mode, edge_detection,
                             tick_size, mapped_channel)

            # Run the scan
            ul.c_in_scan(self.board_num, self.chan_num, self.chan_num,
                         total_count, rate, memhandle, 0)

            # Convert the memhandle to a ctypes array
            # 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_32
            # before the memory is freed. The copy can be used at any time.
            array = self.memhandle_as_ctypes_array_32(memhandle)

            # Display the values
            self.display_values(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
コード例 #11
0
ファイル: CInScan01.py プロジェクト: jdechevr/mcculw
    def start_scan(self):
        low_chan = self.get_low_channel_num()
        high_chan = self.get_high_channel_num()

        if low_chan > high_chan:
            messagebox.showerror(
                "Error", "Low Channel Number must be greater than or equal "
                "to High Channel Number")
            self.start_button["state"] = tk.NORMAL
            return

        rate = 100
        points_per_channel = 10
        num_channels = high_chan - low_chan + 1
        total_count = points_per_channel * num_channels

        # Allocate a buffer for the scan
        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.c_in_scan(self.board_num, low_chan, high_chan, total_count,
                         rate, memhandle, 0)

            # Convert the memhandle to a ctypes array
            # 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_32
            # before the memory is freed. The copy can be used at any time.
            array = cast(memhandle, POINTER(c_ulong))

            # Display the values
            self.display_values(array, total_count, low_chan, high_chan)
        except ULError as e:
            show_ul_error(e)
        finally:
            # Free the allocated memory
            ul.win_buf_free(memhandle)
            self.start_button["state"] = tk.NORMAL
コード例 #12
0
ファイル: DaqSetSetpoints01.py プロジェクト: jdechevr/mcculw
    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()
コード例 #13
0
ファイル: CInScan02.py プロジェクト: jdechevr/mcculw
    def start_scan(self):
        rate = 390
        total_count = 100

        # Allocate a buffer for the scan
        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:
            # Configure the counter
            ul.c_config_scan(
                self.board_num, self.chan_num, CounterMode.DECREMENT_ON,
                CounterDebounceTime.DEBOUNCE_NONE, 0,
                CounterEdgeDetection.FALLING_EDGE,
                CounterTickSize.TICK20PT83ns, 1)

            # Run the scan
            ul.c_in_scan(
                self.board_num, self.chan_num, self.chan_num, total_count,
                rate, memhandle, 0)

            # Convert the memhandle to a ctypes array
            # 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_32
            # before the memory is freed. The copy can be used at any time.
            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
コード例 #14
0
    def update_displayed_values(self):
        # Get the status from the device
        status, curr_count, curr_index = ul.get_status(self.board_num,
                                                       FunctionType.AIFUNCTION)

        # Display the status info
        self.update_status_labels(status, curr_count, curr_index)

        # Display the values
        self.display_values(curr_index, curr_count)

        # Call this method again until the stop button is pressed
        if status == Status.RUNNING:
            self.after(100, self.update_displayed_values)
        else:
            # Free the allocated memory
            ul.win_buf_free(self.memhandle)
            # Stop the background operation (this is required even if the
            # scan completes successfully)
            ul.stop_background(self.board_num, FunctionType.AIFUNCTION)
            self.set_ui_idle_state()
コード例 #15
0
    def send_data(self):
        # Build the data array
        num_chans = min(self.ao_info.num_chans, 4)
        num_points = num_chans
        ao_range = self.ao_info.supported_ranges[0]

        memhandle = ul.win_buf_alloc(num_points)

        # Check if the buffer was successfully allocated
        if not memhandle:
            messagebox.showerror("Error", "Failed to allocate memory")
            self.send_data["state"] = tk.NORMAL
            return

        try:
            data_array = cast(memhandle, POINTER(c_ushort))

            full_scale_count = (2**self.ao_info.resolution) - 1
            value_step = full_scale_count / (num_chans + 1)
            for point_num in range(0, num_points):
                raw_value = int(value_step * (point_num + 1))
                data_array[point_num] = raw_value

                self.raw_data_labels[point_num]["text"] = str(raw_value)
                # ul.to_eng_units cannot be used here, as it uses the analog
                # input resolution. Instead, do the conversion on our own.
                volts = self.ao_to_eng_units(raw_value, ao_range,
                                             self.ao_info.resolution)
                self.volts_labels[point_num]["text"] = ('{:.3f}'.format(volts))

            ul.a_out_scan(self.board_num, 0, num_chans - 1, num_points, 100,
                          ao_range, memhandle, 0)
        except ULError as e:
            show_ul_error(e)
        finally:
            ul.win_buf_free(memhandle)
コード例 #16
0
ファイル: progresstest.py プロジェクト: DerPoddy/Poddy
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)
コード例 #17
0
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)
コード例 #18
0
ファイル: ULAI14.py プロジェクト: conandewitt/lotus
    def start_scan(self):
        low_chan = self.get_low_channel_num()
        high_chan = self.get_high_channel_num()

        if low_chan > high_chan:
            messagebox.showerror(
                "Error", "Low Channel Number must be greater than or equal to "
                "High Channel Number")
            self.start_button["state"] = tk.NORMAL
            return

        rate = 1000
        points_per_channel = 10
        num_channels = high_chan - low_chan + 1
        total_count = points_per_channel * num_channels
        range_ = self.ai_props.available_ranges[0]

        trig_type = TrigType.TRIG_ABOVE
        low_threshold_volts = 0.1
        high_threshold_volts = 1.53

        # Allocate a buffer for the scan
        if self.ai_props.resolution <= 16:
            # Use the win_buf_alloc method for devices with a resolution <= 16
            memhandle = ul.win_buf_alloc(total_count)
        else:
            # Use the win_buf_alloc_32 method for devices with a resolution >
            # 16
            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:
            low_threshold, high_threshold = self.get_threshold_counts(
                range_, low_threshold_volts, high_threshold_volts)

            ul.set_trigger(self.board_num, trig_type, low_threshold,
                           high_threshold)

            # Run the scan
            ul.a_in_scan(self.board_num, low_chan, high_chan, total_count,
                         rate, range_, memhandle, ScanOptions.EXTTRIGGER)

            # Convert the memhandle to a ctypes array
            # 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.ai_props.resolution <= 16:
                # Use the memhandle_as_ctypes_array method for devices with a
                # resolution <= 16
                array = self.memhandle_as_ctypes_array(memhandle)
            else:
                # Use the memhandle_as_ctypes_array_32 method for devices with
                # a resolution > 16
                array = self.memhandle_as_ctypes_array_32(memhandle)

            # Display the values
            self.display_values(array, range_, total_count, low_chan,
                                high_chan)
        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
コード例 #19
0
    def start_scan(self):
        low_chan = self.get_low_channel_num()
        high_chan = self.get_high_channel_num()

        if low_chan > high_chan:
            messagebox.showerror(
                "Error",
                "Low Channel Number must be greater than or equal to High "
                "Channel Number")
            self.start_button["state"] = tk.NORMAL
            return

        rate = 100
        points_per_channel = 10
        num_channels = high_chan - low_chan + 1
        total_count = points_per_channel * num_channels

        ai_range = self.ai_info.supported_ranges[0]

        # Allocate a buffer for the scan
        if self.ai_info.resolution <= 16:
            # Use the win_buf_alloc method for devices with a resolution
            # <= 16
            memhandle = ul.win_buf_alloc(total_count)
        else:
            # Use the win_buf_alloc_32 method for devices with a resolution
            # > 16
            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.a_in_scan(self.board_num, low_chan, high_chan, total_count,
                         rate, ai_range, 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.ai_info.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, ai_range, total_count, low_chan,
                                high_chan)
        except ULError as e:
            show_ul_error(e)
        finally:
            # Free the allocated memory
            ul.win_buf_free(memhandle)
            self.start_button["state"] = tk.NORMAL
コード例 #20
0
    def start_scan(self):
        # Set filename
        self.file_name = window.rec_settings.FolderLabel.text() + '/' + window.rec_settings.NamePrefixLabel.text() + \
            datetime.datetime.now().strftime("_%Y_%m_%d_%H%M%S") + \
            '.wav'

        try:
            # Start the scan
            ul.a_in_scan(
                self.board_num, self.low_chan, self.high_chan, self.ul_buffer_count,
                self.rate, self.ai_range, self.memhandle, self.scan_options)

            self.status = Status.IDLE
            # Wait for the scan to start fully
            while(self.status == Status.IDLE):
                self.status, _, _ = ul.get_status(
                    self.board_num, FunctionType.AIFUNCTION)

            # Create a file for storing the data
            # PYSOUNDFILE MODULE
            temp_file = SoundFile(self.file_name, 'w+', self.rate, 1, 'PCM_16')
            # with SoundFile(self.file_name, 'w', self.rate, 1, 'PCM_16') as f:
            #     print('abro', self.file_name)
            # WAVE MODULE
            # with wave.open('wavemod' + self.file_name, 'w') as f:
            #     f.setnchannels(1)
            #     f.setsampwidth(2)
            #     f.setframerate(self.rate)

            # Start the write loop
            prev_count = 0
            prev_index = 0
            write_ch_num = self.low_chan

            while self.status != Status.IDLE:
                # Get the latest counts
                self.status, curr_count, _ = ul.get_status(
                    self.board_num, FunctionType.AIFUNCTION)

                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 > self.ul_buffer_count:
                    # Print an error and stop writing
                    # QtGui.QMessageBox.information(self, "Error", "A buffer overrun occurred")
                    ul.stop_background(self.board_num, FunctionType.AIFUNCTION)
                    print("A buffer overrun occurred")  # cambiar por critical message
                    break  # VER COMO REEMPLAZAR

                # Check if a chunk is available
                if new_data_count > self.write_chunk_size:
                    self.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 + self.write_chunk_size > self.ul_buffer_count - 1:
                        first_chunk_size = self.ul_buffer_count - prev_index
                        second_chunk_size = (
                            self.write_chunk_size - first_chunk_size)

                        # Copy the first chunk of data to the write_chunk_array
                        ul.win_buf_to_array(
                            self.memhandle, self.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(self.write_chunk_array) + first_chunk_size
                            * sizeof(c_ushort), POINTER(c_ushort))

                        # Copy the second chunk of data to the
                        # write_chunk_array
                        ul.win_buf_to_array(
                            self.memhandle, second_chunk_pointer,
                            0, second_chunk_size)
                    else:
                        # Copy the data to the write_chunk_array
                        ul.win_buf_to_array(
                            self.memhandle, self.write_chunk_array, prev_index,
                            self.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.
                    self.status, curr_count, _ = ul.get_status(
                        self.board_num, FunctionType.AIFUNCTION)
                    # Opcion 1: original ( valores altos )
                    if curr_count - prev_count > self.ul_buffer_count:
                        # Print an error and stop writing
                        ul.stop_background(self.board_num, FunctionType.AIFUNCTION)
                        print("BUFFER OVERRUN")
                        QtGui.QMessageBox.critical(self, "Warning", "A buffer overrun occurred")
                        break
                        # VER COMO HACER PARA EVITAR QUE CIERRE EL PROGRAMA:

                    for i in range(self.write_chunk_size):

                        # opcion 1
                        self.chunk_ls.append(self.write_chunk_array[i]-32768)

                    # opcion 4
                    self.chunk_np = np.asarray(self.chunk_ls, dtype=np.int16)
                    # resampled_chunk = samplerate.resample(self.chunk_np, 44100. /
                    #                                       float(self.rate), 'sinc_best')
                    # resampled_chunk = resampy.resample(self.chunk_np, self.rate, 44100)

                    temp_file.write(self.chunk_np)
                    # self.chunk_signal.emit(self.chunk_ls)
                    # self.file_ls.extend(self.chunk_ls)
                    self.chunk_ls = []


                else:
                    self.wrote_chunk = False

                if self.wrote_chunk:
                    self.chunk_signal.emit(self.chunk_np)
                    # Increment prev_count by the chunk size
                    prev_count += self.write_chunk_size
                    # Increment prev_index by the chunk size
                    prev_index += self.write_chunk_size
                    # Wrap prev_index to the size of the UL buffer
                    prev_index %= self.ul_buffer_count

                    if prev_count % self.points_to_write == 0:
                        # self.file_signal.emit(self.file_np)
                        # self.write_wav_file(self.file_ls
                        temp_file.close()
                        self.file_name = window.rec_settings.FolderLabel.text() + '/' + window.rec_settings.NamePrefixLabel.text() + \
                            datetime.datetime.now().strftime("_%Y_%m_%d_%H%M%S") + \
                            '.wav'
                        temp_file = SoundFile(self.file_name, 'w', self.rate, 1, 'PCM_16')
                else:
                    # Wait a short amount of time for more data to be
                    # acquired.
                    time.sleep(0.1)
        except ULError as e:
            print('except')
            # QtGui.QMessageBox.critical(window, 'Error', 'Please restart program')
            self.print_ul_error(e)  # VER FUNCION Y ADAPATAR A PYQT
        finally:
            # Free the buffer in a finally block to prevent errors from causing
            # a memory leak.
            temp_file.close()
            ul.stop_background(self.board_num, FunctionType.AIFUNCTION)
            ul.win_buf_free(self.memhandle)
            self.finished_signal.emit()
コード例 #21
0
    def read(self, processPulseTrain=False):

        if self.useExtClock:
            # scan_options = ScanOptions.FOREGROUND | ScanOptions.SCALEDATA | ScanOptions.EXTCLOCK
            scan_options = ScanOptions.FOREGROUND | ScanOptions.SCALEDATA | ScanOptions.EXTTRIGGER  # | ScanOptions.RETRIGMODE
        else:
            scan_options = ScanOptions.FOREGROUND | ScanOptions.SCALEDATA
            ul.set_config(
                info_type=InfoType.BOARDINFO,
                board_num=self.board_num,
                dev_num=0,  #value here is ignored
                config_item=BoardInfo.ADTRIGCOUNT,
                config_val=
                0  #number of samples to take per trigger. 0 = continuous triggering
            )

        channelList = []
        channelNumbers = []
        low_chan = min(self.channels['Number'])
        high_chan = max(self.channels['Number'])
        for cnum in range(low_chan, high_chan + 1):
            if cnum in self.channels['Number']:
                cidx = self.channels['Number'].index(cnum)
                cname = self.channels['Label'][cidx]
            else:
                cname = 'Dummy'
            channelList.append(cname)
        num_chans = len(channelList)

        totalCount = num_chans * self.__countsPerChannel
        memhandle = ul.scaled_win_buf_alloc(totalCount)
        ctypesArray = ctypes.cast(memhandle, ctypes.POINTER(ctypes.c_double))

        ul.a_in_scan(board_num=self.board_num,
                     low_chan=low_chan,
                     high_chan=high_chan,
                     num_points=totalCount,
                     rate=self.__rate,
                     ul_range=ULRange.BIP5VOLTS,
                     memhandle=memhandle,
                     options=scan_options)

        data = {}
        for ch in channelList:
            data[ch] = {'Raw': [], 'Mean': None, 'Std': None}

        dataIndex = 0
        for each in range(self.__countsPerChannel):
            for ch in channelList:
                data[ch]['Raw'].append(ctypesArray[dataIndex])
                dataIndex += 1
        data.pop('Dummy')  #toss dummy data from middle channels

        for ch in data.keys():
            data[ch]['Mean'] = np.mean(data[ch]['Raw'])
            data[ch]['Std'] = np.std(data[ch]['Raw'])

        # data['Reference']['Mean'] = np.ones(data['Reference']['Mean'].shape)	#set reference detector readings to 1
        ul.win_buf_free(memhandle)

        if self.useFilter:
            data = self.filterSignal(data)

        if processPulseTrain:
            data = self.processPulseTrain(data)

        return data
コード例 #22
0
    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)
コード例 #23
0
ファイル: a_in_scan_file.py プロジェクト: cullenmq/shearTest
def run_example():
    board_num = 0
    rate = 100
    file_name = 'scan_data.csv'

    # 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 = 5

    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 or
            not ScanOptions.SCALEDATA in ai_props.supported_scan_options):
        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

    # 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(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 / 10)

    ai_range = ai_props.available_ranges[0]

    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.a_in_scan(
            board_num, low_chan, high_chan, ul_buffer_count,
            rate, ai_range, memhandle, scan_options)

        status = Status.IDLE
        # Wait for the scan to start fully
        while(status == Status.IDLE):
            status, _, _ = ul.get_status(
                board_num, FunctionType.AIFUNCTION)

        # 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
            while status != Status.IDLE:
                # Get the latest counts
                status, curr_count, _ = ul.get_status(
                    board_num, FunctionType.AIFUNCTION)

                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.AIFUNCTION)
                    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.AIFUNCTION)
                    if curr_count - prev_count > ul_buffer_count:
                        # Print an error and stop writing
                        ul.stop_background(board_num, FunctionType.AIFUNCTION)
                        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:
                    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 prev_count >= points_to_write:
                        break
                    print('.', end='')
                else:
                    # Wait a short amount of time for more data to be
                    # acquired.
                    time.sleep(0.1)

        ul.stop_background(board_num, FunctionType.AIFUNCTION)
    except ULError as e:
        util.print_ul_error(e)
    finally:
        print('Done')

        # 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)
コード例 #24
0
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)
コード例 #25
0
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)
コード例 #26
0
    def start_scan(self):
        range_ = self.ai_props.available_ranges[0]

        low_chan = self.get_low_channel_num()
        high_chan = self.get_high_channel_num()
        trig_type = self.get_trigger_type()
        trig_value_eng = self.get_trigger_level()
        trig_value = ul.from_eng_units(
            self.board_num, range_, trig_value_eng)

        if low_chan > high_chan:
            messagebox.showerror(
                "Error",
                "Low Channel Number must be greater than or equal to High "
                "Channel Number")
            self.start_button["state"] = tk.NORMAL
            return

        rate = 100
        points_per_channel = 10
        num_channels = high_chan - low_chan + 1
        total_count = points_per_channel * num_channels
        pretrig_points_per_channel = 5
        total_pretrig_count = pretrig_points_per_channel * num_channels

        # Allocate a buffer for the scan
        if self.ai_props.resolution <= 16:
            # Use the win_buf_alloc method for devices with a resolution <=
            # 16
            memhandle = ul.win_buf_alloc(total_count)
        else:
            messagebox.showerror(
                "Error",
                "This example can only be used with boards with a "
                "resolution less than or equal to 16.")
            self.start_button["state"] = tk.NORMAL
            return

        # 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:
            # Set the trigger settings (the level will be used for
            # both thresholds, since the irrelevant threshold is ignored
            # for TRIG_ABOVE and TRIG_BELOW
            ul.set_trigger(
                self.board_num, trig_type, trig_value, trig_value)

            # Run the scan
            ul.a_pretrig(
                self.board_num, low_chan, high_chan, total_pretrig_count,
                total_count, rate, range_, memhandle, 0)

            # Convert the memhandle to a ctypes array
            # 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.
            array = self.memhandle_as_ctypes_array(memhandle)

            # Display the values
            self.display_values(array, range_, total_count,
                                low_chan, high_chan)
        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
コード例 #27
0
ファイル: usb_2408_2416.py プロジェクト: conandewitt/lotus
def run_example():
    board_num = 0
    low_chan = 0
    high_chan = 3
    num_chans = high_chan - low_chan + 1

    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

    rate = 10
    points_per_channel = 10
    total_count = points_per_channel * num_chans

    scan_options = ScanOptions.FOREGROUND | 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)
    # 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:
        # Set channel settings
        set_channel_settings(board_num)

        # Start the scan
        ul.a_in_scan(
            board_num, low_chan, high_chan, total_count,
            rate, ULRange.BIP10VOLTS, 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):
                display_data.append(
                    '{:.3f}'.format(ctypes_array[data_index]))
                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)
コード例 #28
0
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

    ao_props = AnalogOutputProps(board_num)
    if ao_props.num_chans < 1:
        util.print_unsupported_example(board_num)
        return

    low_chan = 0
    high_chan = min(3, ao_props.num_chans - 1)
    num_chans = high_chan - low_chan + 1

    rate = 100
    points_per_channel = 1000
    total_count = points_per_channel * num_chans

    ao_range = ao_props.available_ranges[0]

    # Allocate a buffer for the scan
    memhandle = ul.win_buf_alloc(total_count)
    # Convert the memhandle to a ctypes array
    # 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
    # before the memory is freed. The copy can be used at any time.
    ctypes_array = util.memhandle_as_ctypes_array(memhandle)

    # Check if the buffer was successfully allocated
    if not memhandle:
        print("Failed to allocate memory.")
        return

    frequencies = add_example_data(board_num, ctypes_array, ao_range,
                                   num_chans, rate, points_per_channel)

    for ch_num in range(low_chan, high_chan + 1):
        print("Channel " + str(ch_num) + " Output Signal Frequency: " +
              str(frequencies[ch_num - low_chan]))

    try:
        # Start the scan
        ul.a_out_scan(board_num, low_chan, high_chan, total_count, rate,
                      ao_range, memhandle, ScanOptions.BACKGROUND)

        # Wait for the scan to complete
        print("Waiting for output scan to complete...", end="")
        status = Status.RUNNING
        while status != Status.IDLE:
            print(".", end="")

            # Slow down the status check so as not to flood the CPU
            time.sleep(0.5)

            status, _, _ = ul.get_status(board_num, FunctionType.AOFUNCTION)
        print("")

        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)
コード例 #29
0
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)
コード例 #30
0
ファイル: a_in_scan_file.py プロジェクト: jdechevr/mcculw
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
    file_name = 'scan_data.csv'
    memhandle = None

    # 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 = 5

    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

        # 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(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_info.packet_size != 1:
            packet_size = ai_info.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 / 10)

        ai_range = ai_info.supported_ranges[0]

        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:
            raise Exception('Failed to allocate memory')

        # Start the scan
        ul.a_in_scan(
            board_num, low_chan, high_chan, ul_buffer_count,
            rate, ai_range, memhandle, scan_options)

        status = Status.IDLE
        # Wait for the scan to start fully
        while status == Status.IDLE:
            status, _, _ = ul.get_status(board_num, FunctionType.AIFUNCTION)

        # 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
            while status != Status.IDLE:
                # Get the latest counts
                status, curr_count, _ = ul.get_status(board_num,
                                                      FunctionType.AIFUNCTION)

                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.AIFUNCTION)
                    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.AIFUNCTION)
                    if curr_count - prev_count > ul_buffer_count:
                        # Print an error and stop writing
                        ul.stop_background(board_num, FunctionType.AIFUNCTION)
                        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:
                    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 prev_count >= points_to_write:
                        break
                    print('.', end='')
                else:
                    # Wait a short amount of time for more data to be
                    # acquired.
                    sleep(0.1)

        ul.stop_background(board_num, FunctionType.AIFUNCTION)
    except Exception as e:
        print('\n', e)
    finally:
        print('Done')
        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)