def init_dev(nchan, tc_types): interface = InterfaceType.USB tscale = TempScale.CELSIUS daq_list = get_daq_device_inventory(interface) ndev = len(daq_list) input_mode = AiInputMode.SINGLE_ENDED tc_dev = None ps_dev = None # Listing devices and finding USB-TC if ndev == 0: print('** No devices connected : terminating **') exit() else: str = '\nThe following USB devices are conected :-\n\n' for daq in daq_list: str += '%s' % (daq.product_name) str += '\t (%s)\n' % (daq.unique_id) if daq.product_name == 'USB-TC': tc_dev = DaqDevice(daq) elif daq.product_name == 'USB-201': ps_dev = DaqDevice(daq) print(str) if tc_dev == None: print('\n**USB-TC failed to connect**\n') exit(0) if ps_dev == None: print('\n**USB-201 failed to connect**\n') exit(0) # Connect TC device and get current info / configuration at_dev = tc_dev.get_ai_device() at_inf = at_dev.get_info() tc_dev.connect() at_cnf = at_dev.get_config() for c in range(nchan): at_cnf.set_chan_tc_type(c, tc_types[c]) tc_typ = at_cnf.get_chan_tc_type(c) print('Channel %d is of TC type : %s' % (c, tc_typ.name)) # Connect pressure sensor DAQ ap_dev = ps_dev.get_ai_device() ap_inf = ap_dev.get_info() ps_dev.connect() ap_cnf = ap_dev.get_config() ap_rng = ap_inf.get_ranges(input_mode)[0] ans = raw_input('\nPress RETURN to continue and Ctrl-C to stop\n') return tc_dev, at_dev, ps_dev, ap_dev, ap_rng
def initialize(self): # Check there is a DAQ connected to the computer # ---------------------------------------------- devices = get_daq_device_inventory(self.interface_type) number_of_devices = len(devices) if number_of_devices == 0: raise Exception('Error: No DAQ devices found') # Look for the device with the proper ID # -------------------------------------- for device in devices: id = device.unique_id if id == self.DAQ_id: daq_device = DaqDevice(device) daq_device.connect() self.daq_device = daq_device print('\nThe device with ID={} was found and connected'.format( self.DAQ_id)) else: self.daq_device = None print("\nThe device with ID={} was not found".format( self.DAQ_id))
def __init__(self): devices = get_daq_device_inventory(InterfaceType.USB) number_of_devices = len(devices) if number_of_devices == 0: raise Exception('Error: No DAQ devices found') print('Found', number_of_devices, 'DAQ device(s):') for i in range(number_of_devices): print(' ', devices[i].product_name, ' (', devices[i].unique_id, ')', sep='') # Create the DAQ device object associated with the specified descriptor index. daq_device = DaqDevice( devices[0] ) #if more than one device, change this to the one you want self.daq_device = daq_device # Get the DioDevice object and verify that it is valid. dio_device = daq_device.get_dio_device() self.dio_device = dio_device if dio_device is None: raise Exception( 'Error: The device does not support digital output') self.connect()
def DaqConnect(self): #connect DAQ devices try: devices = get_daq_device_inventory(InterfaceType.USB) number_of_devices = len(devices) daq_device = DaqDevice(devices[0]) daq_device.connect() for i in range(number_of_devices): print(devices[i].product_name, 'is connected.') except: print("No DAQ device")
def get_radiacion(self): # Get a list of available DAQ devices devices = get_daq_device_inventory(InterfaceType.USB) # Create a DaqDevice Object and connect to the device daq_device = DaqDevice(devices[0]) daq_device.connect() # Get AiDevice and AiInfo objects for the analog input subsystem ai_device = daq_device.get_ai_device() ai_info = ai_device.get_info() data = ai_device.a_in(1, AiInputMode.SINGLE_ENDED, Range.BIP10VOLTS, AInFlag.DEFAULT) r = data / (80.86 * pow(10, -6)) daq_device.disconnect() daq_device.release() return round(r, 2)
def get_temperatura(self): # Get a list of available DAQ devices devices = get_daq_device_inventory(InterfaceType.USB) # Create a DaqDevice Object and connect to the device daq_device = DaqDevice(devices[0]) daq_device.connect() # Get AiDevice and AiInfo objects for the analog input subsystem ai_device = daq_device.get_ai_device() ai_info = ai_device.get_info() data = ai_device.a_in(0, AiInputMode.SINGLE_ENDED, Range.BIP10VOLTS, AInFlag.DEFAULT) temp = data * -10 #print'Temperatura ', round(temp, 2), "C" daq_device.disconnect() daq_device.release() return round(temp, 2)
def initialize(self): connected_devices = get_daq_device_inventory(InterfaceType.USB) number_of_devices = len(connected_devices) if number_of_devices == 0: raise Exception( 'OLYMPUS: RUNTIME ERROR - DAQ DEVICE NOT CONNECTED') for daqs in connected_devices: if daqs.unique_id == self.serial: self.daq_device = DaqDevice(daqs) self.ai_device = self.daq_device.get_ai_device() self.daq_device.connect() self.daq_data = create_float_buffer(self.channel_count, self.samples_per_channel) self.scan_event_parameters_daq = self.ScanParams( self.daq_data, self.high_channel, self.low_channel) return True
def main(): daq_device = None ctr_device = None status = ScanStatus.IDLE descriptor_index = 0 interface_type = InterfaceType.USB low_encoder = 0 encoder_count = 2 sample_rate = 1000.0 # Hz samples_per_channel = 10000 scan_options = ScanOption.CONTINUOUS scan_flags = CInScanFlag.DEFAULT encoder_type = CounterMeasurementType.ENCODER encoder_mode = CounterMeasurementMode.ENCODER_X1 | CounterMeasurementMode.ENCODER_CLEAR_ON_Z edge_detection = CounterEdgeDetection.RISING_EDGE tick_size = CounterTickSize.TICK_20ns debounce_mode = CounterDebounceMode.NONE debounce_time = CounterDebounceTime.DEBOUNCE_0ns config_flags = CConfigScanFlag.DEFAULT try: # Get descriptors for all of the available DAQ devices. devices = get_daq_device_inventory(interface_type) number_of_devices = len(devices) if number_of_devices == 0: raise Exception('Error: No DAQ devices found') print('Found', number_of_devices, 'DAQ device(s):') for i in range(number_of_devices): print(' ', devices[i].product_name, ' (', devices[i].unique_id, ')', sep='') # Create the DAQ device object associated with the specified descriptor index. daq_device = DaqDevice(devices[descriptor_index]) # Get the CtrDevice object and verify that it is valid. ctr_device = daq_device.get_ctr_device() if ctr_device is None: raise Exception('Error: The DAQ device does not support counters') # Verify that the specified device supports hardware pacing for counters. ctr_info = ctr_device.get_info() if not ctr_info.has_pacer(): raise Exception( '\nError: The specified DAQ device does not support hardware paced counter input' ) # Establish a connection to the DAQ device. descriptor = daq_device.get_descriptor() print('\nConnecting to', descriptor.dev_string, '- please wait...') daq_device.connect() # Get the encoder counter channels. encoder_counters = get_supported_encoder_counters(ctr_info) if len(encoder_counters) == 0: raise Exception( '\nError: The specified DAQ device does not support encoder channels' ) # Verify that the low_encoder number is valid. first_encoder = encoder_counters[0] if low_encoder < first_encoder: low_encoder = first_encoder if low_encoder > first_encoder + len(encoder_counters) - 1: low_encoder = first_encoder # Verify that the encoder count is valid. if encoder_count > len(encoder_counters): encoder_count = len(encoder_counters) # Set the high_encoder channel. high_encoder = low_encoder + encoder_count - 1 if high_encoder > first_encoder + len(encoder_counters) - 1: high_encoder = first_encoder + len(encoder_counters) - 1 # update the actual number of encoders being used encoder_count = high_encoder - low_encoder + 1 # Clear the counter, and configure the counter as an encoder. for encoder in range(low_encoder, high_encoder + 1): ctr_device.c_config_scan(encoder, encoder_type, encoder_mode, edge_detection, tick_size, debounce_mode, debounce_time, config_flags) # Allocate a buffer to receive the data. data = create_int_buffer(encoder_count, samples_per_channel) print('\n', descriptor.dev_string, ' ready', sep='') print(' Function demonstrated: ctr_device.c_config_scan()') print(' Counter(s):', low_encoder, '-', high_encoder) print(' Sample rate:', sample_rate, 'Hz') print(' Scan options:', display_scan_options(scan_options)) try: input('\nHit ENTER to continue\n') except (NameError, SyntaxError): pass # Start the scan ctr_device.c_in_scan(low_encoder, high_encoder, samples_per_channel, sample_rate, scan_options, scan_flags, data) system('clear') try: while True: try: status, transfer_status = ctr_device.get_scan_status() reset_cursor() print('Please enter CTRL + C to terminate the process\n') print('Active DAQ device: ', descriptor.dev_string, ' (', descriptor.unique_id, ')\n', sep='') print('actual scan rate = ', '{:.6f}'.format(sample_rate), 'Hz\n') index = transfer_status.current_index print('currentScanCount = ', transfer_status.current_scan_count) print('currentTotalCount = ', transfer_status.current_total_count) print('currentIndex = ', index, '\n') for encoder_index in range(encoder_count): print('chan =', (encoder_index + low_encoder), ': ', '{:.6f}'.format(data[index + encoder_index])) sleep(0.1) if status != ScanStatus.RUNNING: break except (ValueError, NameError, SyntaxError): break except KeyboardInterrupt: pass except Exception as e: print('\n', e) finally: if daq_device: if status == ScanStatus.RUNNING: ctr_device.scan_stop() if daq_device.is_connected(): daq_device.disconnect() daq_device.release()
def main(data_write_mode = ''): daq_device = None ai_device = None status = ScanStatus.IDLE descriptor_index = 0 range_index = 0 interface_type = InterfaceType.USB low_channel = 0 high_channel = 0 rate = 100000 # Samples/second/channel buffer_length = 200000 f_transmit = 36000 # fundamental frequency of transmitter channel_num = high_channel-low_channel+1 samples_per_channel = int(float(buffer_length)/float(channel_num)) file_length = 2 # Seconds rows_of_data = (float(file_length)/((float(buffer_length)/2)/(float(rate)*float(channel_num))))*((float(buffer_length)/2)/float(channel_num)) scan_options = ScanOption.CONTINUOUS flags = AInScanFlag.DEFAULT #CONTROL ALGORITHM PARAMETERS: velocity = 1 #tune speed beta = 0.01 #tune turning heading = 0 past_freq = f_transmit dH = -1.0001 try: # Get descriptors for all of the available DAQ devices. devices = get_daq_device_inventory(interface_type) number_of_devices = len(devices) if number_of_devices == 0: raise Exception('Error: No DAQ devices found') print('Found', number_of_devices, 'DAQ device(s):') for i in range(number_of_devices): print(' ', devices[i].product_name, ' (', devices[i].unique_id, ')', sep='') # Create the DAQ device object associated with the specified descriptor index. daq_device = DaqDevice(devices[descriptor_index]) # Get the AiDevice object and verify that it is valid. ai_device = daq_device.get_ai_device() if ai_device is None: raise Exception('Error: The DAQ device does not support analog input') # Verify that the specified device supports hardware pacing for analog input. ai_info = ai_device.get_info() if not ai_info.has_pacer(): raise Exception('\nError: The specified DAQ device does not support hardware paced analog input') # Establish a connection to the DAQ device. descriptor = daq_device.get_descriptor() print('\nConnecting to', descriptor.dev_string, '- please wait...') daq_device.connect() # The default input mode is SINGLE_ENDED. input_mode = AiInputMode.SINGLE_ENDED # If SINGLE_ENDED input mode is not supported, set to DIFFERENTIAL. if ai_info.get_num_chans_by_mode(AiInputMode.SINGLE_ENDED) <= 0: input_mode = AiInputMode.DIFFERENTIAL # Get the number of channels and validate the high channel number. number_of_channels = ai_info.get_num_chans_by_mode(input_mode) if high_channel >= number_of_channels: high_channel = number_of_channels - 1 channel_count = high_channel - low_channel + 1 # Get a list of supported ranges and validate the range index. ranges = ai_info.get_ranges(input_mode) if range_index >= len(ranges): range_index = len(ranges) - 1 # Allocate a buffer to receive the data. data = create_float_buffer(channel_count, samples_per_channel) print('\n', descriptor.dev_string, ' ready', sep='') print(' Function demonstrated: ai_device.a_in_scan()') print(' Channels: ', low_channel, '-', high_channel) print(' Input mode: ', input_mode.name) print(' Range: ', ranges[range_index].name) print(' Samples per channel: ', samples_per_channel) print(' Rate: ', rate, 'Hz') print(' Scan options:', display_scan_options(scan_options)) print(" Output File Rows:" +str(rows_of_data)) try: input('\nHit ENTER to continue\n') except (NameError, SyntaxError): pass system('clear') print('\nHit ^C to exit\n') #Set up threshold for where the dumps should occur in the buffer #Currently configured for dumping half of the buffer threshold = (float(len(data))/2) - (float(len(data))/2)%channel_count data_range = [range(int(threshold)),range(int(threshold),len(data))] #Setting up whether or not to write in binary mode write_mode = 'w'+data_write_mode # Start the acquisition. rate = ai_device.a_in_scan(low_channel, high_channel, input_mode, ranges[range_index], samples_per_channel, rate, scan_options, flags, data) #open first text file start=time.time() f=open('./data/'+'{:.6f}'.format(start)+".txt",write_mode) try: past_index = -1 #Initiated at -1 to because index is -1 until buffer is written to while True: #Get the status of the background operation status, transfer_status = ai_device.get_scan_status() #Make new file after fixed amount of time set by 'file_length' if time.time()-start>=file_length: f.close start=time.time() f=open('./data/'+'{:.6f}'.format(start)+".txt",write_mode) #get current index in filling the buffer to know when to clear it index = transfer_status.current_index #write half buffer to txt file, find max freq, and update heading if buffer fills past halfway point if past_index<=threshold and index>threshold: #dumps data data_fft, data_dump = dump_data(f, data, data_range[0], channel_count) #find fundamental frequency within 500Hz of f_transmit freq = fourier_analysis(data_fft,rate,f_transmit,500) #new heading past_freq, heading, dH = heading_adjust(freq, past_freq, beta, heading, dH) print('HEADING: %s FREQ: %d dH: %d' %(str(heading), past_freq,dH)) nav_solution(dH,heading) #write half buffer to txt file, find max freq, and update heading if buffer filled to end and is overwriting first half if past_index>index: #dumps data data_fft, data_dump = dump_data(f, data, data_range[1], channel_count) #find fundamental frequency within 500Hz of f_transmit freq = fourier_analysis(data_fft,rate,f_transmit,500) #new heading past_freq, heading, dH = heading_adjust(freq, past_freq, beta, heading, dH) print('HEADING: %s FREQ: %d dH: %d' %(str(heading), past_freq,dH)) nav_solution(dH,heading) past_index = index except KeyboardInterrupt: pass except Exception as e: print('\n', e) finally: if daq_device: # Stop the acquisition if it is still running. if status == ScanStatus.RUNNING: ai_device.scan_stop() if daq_device.is_connected(): daq_device.disconnect() daq_device.release()
def stream(low_channel, high_channel, sample_rate, data_file): """Analog input scan example.""" daq_device = None ai_device = None status = ScanStatus.IDLE device_number = 0 dt = 0.1 # how often save a chunk of data range_index = 0 buffer_margin = 20 interface_type = InterfaceType.ANY samples_per_channel = int(buffer_margin * dt * sample_rate) scan_options = ScanOption.CONTINUOUS flags = AInScanFlag.DEFAULT try: # Get descriptors for all of the available DAQ devices. devices = get_daq_device_inventory(interface_type) number_of_devices = len(devices) if number_of_devices == 0: raise RuntimeError('Error: No DAQ devices found') print('Found', number_of_devices, 'DAQ device(s):') print('using device', device_number) descriptor_index = device_number if descriptor_index not in range(number_of_devices): raise RuntimeError('Error: Invalid descriptor index') # Create the DAQ device from the descriptor at the specified index. daq_device = DaqDevice(devices[descriptor_index]) # Get the AiDevice object and verify that it is valid. ai_device = daq_device.get_ai_device() if ai_device is None: raise RuntimeError('Error: The DAQ device does not support analog ' 'input') # Verify the specified device supports hardware pacing for analog input. ai_info = ai_device.get_info() if not ai_info.has_pacer(): raise RuntimeError('\nError: The specified DAQ device does not ' 'support hardware paced analog input') # Establish a connection to the DAQ device. descriptor = daq_device.get_descriptor() print('\nConnecting to', descriptor.dev_string, '- please wait...') # For Ethernet devices using a connection_code other than the default # value of zero, change the line below to enter the desired code. try: daq_device.connect(connection_code=0) except TypeError: daq_device.connect() # The default input mode is SINGLE_ENDED. input_mode = AiInputMode.SINGLE_ENDED # If SINGLE_ENDED input mode is not supported, set to DIFFERENTIAL. if ai_info.get_num_chans_by_mode(AiInputMode.SINGLE_ENDED) <= 0: input_mode = AiInputMode.DIFFERENTIAL # Get the number of channels and validate the high channel number. number_of_channels = ai_info.get_num_chans_by_mode(input_mode) if high_channel >= number_of_channels: high_channel = number_of_channels - 1 channel_count = high_channel - low_channel + 1 # Get a list of supported ranges and validate the range index. ranges = ai_info.get_ranges(input_mode) if range_index >= len(ranges): range_index = len(ranges) - 1 # Allocate a buffer to receive the data.0 data = create_float_buffer(channel_count, samples_per_channel) print('\n', descriptor.dev_string, ' ready', sep='') print(' Function demonstsample_rated: ai_device.a_in_scan()') print(' Channels: ', low_channel, '-', high_channel) print(' Input mode: ', input_mode.name) print(' Range: ', ranges[range_index].name) print(' Samples per channel: ', samples_per_channel) print(' Rate: ', sample_rate, 'Hz') print(' Scan options:', display_scan_options(scan_options)) # Start the acquisition. sample_rate = ai_device.a_in_scan(low_channel, high_channel, input_mode, ranges[range_index], samples_per_channel, sample_rate, scan_options, flags, data) print() print('acquiring data ..', end='') stdout.flush() with open(data_file, 'w') as f: save_count = 0 last_save_index = 0 buffer_size = samples_per_channel * channel_count while not done: # Get the status of the background operation status, transfer_status = ai_device.get_scan_status() current_index = transfer_status.current_index if current_index < 0: continue num_to_save = (current_index - last_save_index) % buffer_size + channel_count # Write data to file for i in range(num_to_save): if i % channel_count == 0: f.write('{} '.format(save_count)) save_count += 1 save_index = (last_save_index + i) % buffer_size f.write('{}'.format(data[save_index])) if i % channel_count == (channel_count - 1): f.write('\n') else: f.write(' ') last_save_index = (current_index + channel_count) % buffer_size sleep(dt) print('done') except RuntimeError as error: print('\n', error) finally: if daq_device: # Stop the acquisition if it is still running. if status == ScanStatus.RUNNING: ai_device.scan_stop() if daq_device.is_connected(): daq_device.disconnect() daq_device.release()
async def run(self, parsed_args, output): aq_device = None ctr_device = None descriptor_index = 0 interface_type = InterfaceType.USB low_encoder = 0 encoder_count = 5 sample_rate = 1000.0 # 1000 # Hz samples_per_channel = 10000 # 10000 scan_options = ScanOption.CONTINUOUS scan_flags = CInScanFlag.DEFAULT encoder_type = CounterMeasurementType.ENCODER encoder_mode = CounterMeasurementMode.ENCODER_X4 edge_detection = CounterEdgeDetection.RISING_EDGE tick_size = CounterTickSize.TICK_20ns debounce_mode = CounterDebounceMode.TRIGGER_AFTER_STABLE debounce_time = CounterDebounceTime.DEBOUNCE_7500ns config_flags = CConfigScanFlag.DEFAULT daq_device = None try: # Get descriptors for all of the available DAQ devices. devices = get_daq_device_inventory(interface_type) number_of_devices = len(devices) if number_of_devices == 0: raise ValueError('Error: No DAQ devices found') # Create the DAQ device object associated with the specified descriptor index. daq_device = DaqDevice(devices[descriptor_index]) # Get the CtrDevice object and verify that it is valid. ctr_device = daq_device.get_ctr_device() if ctr_device is None: raise ValueError( 'Error: The DAQ device does not support counters') # Verify that the specified device supports hardware pacing for counters. ctr_info = ctr_device.get_info() if not ctr_info.has_pacer(): raise ValueError( 'Error: The specified DAQ device does not support hardware paced counter input' ) # Establish a connection to the DAQ device. descriptor = daq_device.get_descriptor() daq_device.connect() # Get the encoder counter channels. encoder_counters = get_supported_encoder_counters(ctr_info) if len(encoder_counters) == 0: raise ValueError( 'Error: The specified DAQ device does not support encoder channels' ) # Verify that the low_encoder number is valid. first_encoder = encoder_counters[0] if low_encoder < first_encoder: low_encoder = first_encoder if low_encoder > first_encoder + len(encoder_counters) - 1: low_encoder = first_encoder # Verify that the encoder count is valid. if encoder_count > len(encoder_counters): encoder_count = len(encoder_counters) # Set the high_encoder channel. high_encoder = low_encoder + encoder_count - 1 if high_encoder > first_encoder + len(encoder_counters) - 1: high_encoder = first_encoder + len(encoder_counters) - 1 # update the actual number of encoders being used encoder_count = high_encoder - low_encoder + 1 # Clear the counter, and configure the counter as an encoder. for encoder in range(low_encoder, high_encoder + 1): ctr_device.c_config_scan(encoder, encoder_type, encoder_mode, edge_detection, tick_size, debounce_mode, debounce_time, config_flags) # Allocate a buffer to receive the data. data = create_int_buffer(encoder_count, samples_per_channel) # Start the scan ctr_device.c_in_scan(low_encoder, high_encoder, samples_per_channel, sample_rate, scan_options, scan_flags, data) # prev_samples_per_channel = 0 # cur_samples_per_channel = 0 prev_index = 0 XVect = [] YVect = [] ZVect = [] EVect = [] AllVect = [] startX = 0.0 startY = 0.0 startZ = 0.0 startE = 0.0 # newZ = [] prev_index = 0 start_time = time_now() cur_time = start_time + 1 while not self.stop_requested: status, transfer_status = ctr_device.get_scan_status() # not sure if can await the above line index = transfer_status.current_index # print(index) # edge starting condition if index == -1: AllVect = [0.0, 0.0, 0.0, 0.0, 0.0] # normal condition else: # has not looped around if prev_index < index: AllVect = data[prev_index:index] # has wrapped around else: AllVect = data[prev_index:] + data[0:index] prev_index = index # print(AllVect) XVect = AllVect[3::5] YVect = AllVect[1::5] Z1Vect = AllVect[0::5] Z2Vect = AllVect[2::5] EVect = AllVect[4::5] end_time = cur_time + (len(XVect) - 1) * 1e3 # cur_time is in us [XVect, startX] = processX(XVect, startX) [YVect, startY] = processY(YVect, startY) [EVect, startE] = processE(EVect, startE) [ZVect, startZ] = processZ(Z1Vect, Z2Vect, startZ, cur_time, end_time) Xarray = np.array(XVect) Yarray = np.array(YVect) Zarray = np.array(ZVect) Earray = np.array(EVect) * -1 #invert for positive extrusion Xarray = np.vstack(Xarray) Yarray = np.vstack(Yarray) Zarray = np.vstack(Zarray) Earray = np.vstack(Earray) time_array = np.linspace(cur_time, end_time, len(XVect)) time_array = np.vstack(time_array) # print("before all output") All_Output = np.hstack( (time_array, Xarray, Yarray, Zarray, Earray)) # print("after all output") # print(All_Output) await output.write(np.array(All_Output)) # print("after writing") # print(len(YVect)) # for i in range(len(YVect)): # print(str(YVect[i])+ "\t"+str(newY[i])) await asyncio.sleep(1) cur_time = end_time + 1e3 if status != ScanStatus.RUNNING: break # except (ValueError, NameError, SyntaxError): # break # print("next while loop cycle") except ValueError as e: print(str(e)) except Exception as e: raise e finally: if daq_device: if ctr_device: ctr_device.scan_stop() if daq_device.is_connected(): daq_device.disconnect() daq_device.release()
def main(): daq_device = None dio_device = None port_to_write = None port_info = None interface_type = InterfaceType.USB descriptor_index = 0 port_types_index = 0 try: # Get descriptors for all of the available DAQ devices. devices = get_daq_device_inventory(interface_type) number_of_devices = len(devices) if number_of_devices == 0: raise Exception('Error: No DAQ devices found') print('Found', number_of_devices, 'DAQ device(s):') for i in range(number_of_devices): print(' ', devices[i].product_name, ' (', devices[i].unique_id, ')', sep='') # Create the DAQ device object associated with the specified descriptor index. daq_device = DaqDevice(devices[descriptor_index]) # Get the DioDevice object and verify that it is valid. dio_device = daq_device.get_dio_device() if dio_device is None: raise Exception( 'Error: The device does not support digital output') # Establish a connection to the DAQ device. descriptor = daq_device.get_descriptor() print('\nConnecting to', descriptor.dev_string, '- please wait...') daq_device.connect() # Get the port types for the device(AUXPORT, FIRSTPORTA, ...) dio_info = dio_device.get_info() port_types = dio_info.get_port_types() if port_types_index >= len(port_types): port_types_index = len(port_types) - 1 port_to_write = port_types[port_types_index] # Get the port I/O type and the number of bits for the first port. port_info = dio_info.get_port_info(port_to_write) # Configure the port for output. if (port_info.port_io_type == DigitalPortIoType.IO or port_info.port_io_type == DigitalPortIoType.BITIO): dio_device.d_config_port(port_to_write, DigitalDirection.OUTPUT) print('\n', descriptor.dev_string, ' ready', sep='') print(' Function demonstrated: dio_device.d_out()') print(' Port: ', port_types[port_types_index].name) try: input('\nHit ENTER to continue\n') except (NameError, SyntaxError): pass system('clear') max_port_value = int(pow(2.0, port_info.number_of_bits) - 1) reset_cursor() print('Active DAQ device: ', descriptor.dev_string, ' (', descriptor.unique_id, ')\n', sep='') try: while True: try: data = input('Enter a value between 0 and ' + '{:.0f}'.format(max_port_value) + ' (or non-numeric character to exit): ') # write the first port dio_device.d_out(port_to_write, int(data)) sleep(0.1) cursor_up() clear_eol() except (ValueError, NameError, SyntaxError): break except KeyboardInterrupt: pass except Exception as e: print('\n', e) finally: if daq_device: if dio_device and port_to_write and port_info: # before disconnecting, set the port back to input if (port_info.port_io_type == DigitalPortIoType.IO or port_info.port_io_type == DigitalPortIoType.BITIO): dio_device.d_config_port(port_to_write, DigitalDirection.INPUT) if daq_device.is_connected(): daq_device.disconnect() daq_device.release()
def daq_setup(rate=500000, samples_per_channel=500000 * 10, resistor=0.1): """Analog input scan example.""" global bench_over bench_over = False # beginning of a new cycle daq_device = None status = ScanStatus.IDLE # samples_per_channel (int): the number of A/D samples to collect from each channel in the scan. # rate (float): A/D sample rate in samples per channel per second. range_index = 0 interface_type = InterfaceType.ANY low_channel = 0 high_channel = 0 scan_options = ScanOption.CONTINUOUS flags = AInScanFlag.DEFAULT # Get descriptors for all of the available DAQ devices. devices = get_daq_device_inventory(interface_type) number_of_devices = len(devices) if number_of_devices == 0: raise RuntimeError('Error: No DAQ devices found') print('Found', number_of_devices, 'DAQ device(s):') for i in range(number_of_devices): print(' [', i, '] ', devices[i].product_name, ' (', devices[i].unique_id, ')', sep='') descriptor_index = 0 if descriptor_index not in range(number_of_devices): raise RuntimeError('Error: Invalid descriptor index') # Create the DAQ device from the descriptor at the specified index. daq_device = DaqDevice(devices[descriptor_index]) # Get the AiDevice object and verify that it is valid. ai_device = daq_device.get_ai_device() if ai_device is None: raise RuntimeError('Error: The DAQ device does not support analog ' 'input') # Verify the specified device supports hardware pacing for analog input. ai_info = ai_device.get_info() if not ai_info.has_pacer(): raise RuntimeError('\nError: The specified DAQ device does not ' 'support hardware paced analog input') # Establish a connection to the DAQ device. descriptor = daq_device.get_descriptor() print('\nConnecting to', descriptor.dev_string, '- please wait...') # For Ethernet devices using a connection_code other than the default # value of zero, change the line below to enter the desired code. daq_device.connect(connection_code=0) # The default input mode is DIFFERENTIAL. input_mode = AiInputMode.DIFFERENTIAL # Get the number of channels and validate the high channel number. number_of_channels = ai_info.get_num_chans_by_mode(input_mode) if high_channel >= number_of_channels: high_channel = number_of_channels - 1 channel_count = high_channel - low_channel + 1 # Get a list of supported ranges and validate the range index. ranges = ai_info.get_ranges(input_mode) if range_index >= len(ranges): range_index = len(ranges) - 1 meas_range = ranges[1] data_dir = "data_dir" if not os.path.isdir(data_dir): os.mkdir(data_dir) # define name of a datafile and delete if it exists in the data directory data_fname = "test_data" #if os.path.isfile(os.path.join(data_dir, data_fname)): #os.remove(os.path.join(data_dir, data_fname)) # Allocate a buffer to receive the data. data = create_float_buffer(channel_count, samples_per_channel) # ranges[1] = Range.BIP5VOLTS return daq_device, low_channel, high_channel, input_mode, meas_range, samples_per_channel, rate, scan_options, flags, data, data_dir, data_fname
def main(): # Parameters for AoDevice.a_out_scan low_channel = 0 high_channel = 0 voltage_range_index = 0 # Use the first supported range samples_per_channel = 2000 # Two second buffer (sample_rate * 2) sample_rate = 1000 # Hz scan_options = ScanOption.CONTINUOUS scan_flags = AOutScanFlag.DEFAULT interface_type = InterfaceType.USB daq_device = None ao_device = None scan_status = ScanStatus.IDLE try: # Get descriptors for all of the available DAQ devices. devices = get_daq_device_inventory(interface_type) number_of_devices = len(devices) # Verify at least one DAQ device is detected. if number_of_devices == 0: raise Exception('Error: No DAQ devices found') print('Found', number_of_devices, 'DAQ device(s):') for i in range(number_of_devices): print(' ', devices[i].product_name, ' (', devices[i].unique_id, ')', sep='') # Create a DaqDevice object from the first descriptor. daq_device = DaqDevice(devices[0]) ao_device = daq_device.get_ao_device() # Verify the specified DAQ device supports analog output. if ao_device is None: raise Exception( 'Error: The DAQ device does not support analog output') # Verify the specified DAQ device supports hardware pacing for analog output. ao_info = ao_device.get_info() if not ao_info.has_pacer(): raise Exception( 'Error: The DAQ device does not support paced analog output') descriptor = daq_device.get_descriptor() print('\nConnecting to', descriptor.dev_string, '- please wait...') # Establish a connection to the device. daq_device.connect() chan_string = str(low_channel) num_channels = high_channel - low_channel + 1 if num_channels > 1: chan_string = ' '.join((chan_string, '-', str(high_channel))) # Select the voltage range voltage_ranges = ao_info.get_ranges() if voltage_range_index < 0: voltage_range_index = 0 elif voltage_range_index >= len(voltage_ranges): voltage_range_index = len(voltage_ranges) - 1 voltage_range = ao_info.get_ranges()[voltage_range_index] # Create a buffer for output data. out_buffer = create_float_buffer(num_channels, samples_per_channel) # Fill the output buffer with data. amplitude = 1.0 # Volts offset = amplitude if voltage_range > 1000 else 0.0 # Set an offset if the range is unipolar samples_per_cycle = int(sample_rate / 10.0) # 10 Hz sine wave create_output_data(num_channels, samples_per_channel, samples_per_cycle, amplitude, offset, out_buffer) print('\n', descriptor.dev_string, 'ready') print(' Function demonstrated: AoDevice.a_out_scan') print(' Channel(s):', chan_string) print(' Range:', voltage_range.name) print(' Samples per channel:', samples_per_channel) print(' Sample Rate:', sample_rate, 'Hz') print(' Scan options:', display_scan_options(scan_options)) try: input('\nHit ENTER to continue') except (NameError, SyntaxError): pass # Start the output scan. sample_rate = ao_device.a_out_scan(low_channel, high_channel, voltage_range, samples_per_channel, sample_rate, scan_options, scan_flags, out_buffer) system('clear') print('Please enter CTRL + C to terminate the process\n') print('Active DAQ device: ', descriptor.dev_string, ' (', descriptor.unique_id, ')\n', sep='') print(' Actual scan rate: ', sample_rate, 'Hz') try: while True: # Get and display the scan status. scan_status, transfer_status = ao_device.get_scan_status() if scan_status != ScanStatus.RUNNING: break print(' Current scan count: ', transfer_status.current_scan_count) print(' Current total count:', transfer_status.current_total_count) print(' Current index: ', transfer_status.current_index) stdout.flush() sleep(0.1) # Clear the previous status before displaying the next status. for line in range(3): stdout.write(CURSOR_UP + ERASE_LINE) except KeyboardInterrupt: pass except Exception as e: print('\n', e) finally: if daq_device: # Stop the scan. if scan_status == ScanStatus.RUNNING: ao_device.scan_stop() # Disconnect from the DAQ device. if daq_device.is_connected(): daq_device.disconnect() # Release the DAQ device resource. daq_device.release()
def main(): global rate daq_device = None ai_device = None ai_info = None descriptor_index = 0 range_index = 0 interface_type = InterfaceType.USB low_channel = 0 high_channel = 3 samples_per_channel = 10000 rate = 100 flags = AInScanFlag.DEFAULT event_types = (DaqEventType.ON_DATA_AVAILABLE | DaqEventType.ON_END_OF_INPUT_SCAN | DaqEventType.ON_INPUT_SCAN_ERROR) ScanParams = namedtuple('ScanParams', 'buffer high_chan low_chan descriptor status') # set the scan options for a FINITE scan ... to set the scan options for # a continuous scan, uncomment the line that or's the SO_CONTINUOUS option # into to the scanOptions variable scan_options = ScanOption.DEFAULTIO # scan_options |= ScanOption.CONTINUOUS try: # Get descriptors for all of the available DAQ devices. devices = get_daq_device_inventory(interface_type) number_of_devices = len(devices) if number_of_devices == 0: raise Exception('Error: No DAQ devices found') print('Found', number_of_devices, 'DAQ device(s):') for i in range(number_of_devices): print(' ', devices[i].product_name, ' (', devices[i].unique_id, ')', sep='') # Create the DAQ device object from the specified descriptor index. daq_device = DaqDevice(devices[descriptor_index]) # Get the AiDevice object and verify that it is valid. ai_device = daq_device.get_ai_device() if ai_device is None: raise Exception('Error: The DAQ device does not support analog ' 'input') # Verify the device supports hardware pacing for analog input. ai_info = ai_device.get_info() if not ai_info.has_pacer(): raise Exception( '\nError: The specified DAQ device does not support' ' hardware paced analog input') # Establish a connection to the DAQ device. descriptor = daq_device.get_descriptor() print('\nConnecting to', descriptor.dev_string, '- please wait...') daq_device.connect() # The default input mode is SINGLE_ENDED. input_mode = AiInputMode.SINGLE_ENDED # If SINGLE_ENDED input mode is not supported, set to DIFFERENTIAL. if ai_info.get_num_chans_by_mode(AiInputMode.SINGLE_ENDED) <= 0: input_mode = AiInputMode.DIFFERENTIAL # Get the number of channels and validate the high channel number. number_of_channels = ai_info.get_num_chans_by_mode(input_mode) if high_channel >= number_of_channels: high_channel = number_of_channels - 1 channel_count = high_channel - low_channel + 1 # Get a list of supported ranges and validate the range index. ranges = ai_info.get_ranges(input_mode) if range_index >= len(ranges): range_index = len(ranges) - 1 # Allocate a buffer to receive the data. data = create_float_buffer(channel_count, samples_per_channel) # Store the user data for use in the callback function. scan_status = {'complete': False, 'error': False} user_data = ScanParams(data, high_channel, low_channel, descriptor, scan_status) # Enable the event to be notified every time 100 samples are available. available_sample_count = 100 daq_device.enable_event(event_types, available_sample_count, event_callback_function, user_data) print('\n', descriptor.dev_string, 'ready', sep='') print(' Function demonstrated: daq_device.enable_event()') print(' Channels: ', low_channel, '-', high_channel) print(' Input mode: ', input_mode.name) print(' Range: ', ranges[range_index].name) print(' Samples per channel: ', samples_per_channel) print(' Rate: ', rate, 'Hz') print(' Scan options:', display_scan_options(scan_options)) try: input('\nHit ENTER to continue\n') except (NameError, SyntaxError): pass system('clear') # Start the finite acquisition. rate = ai_device.a_in_scan(low_channel, high_channel, input_mode, ranges[range_index], samples_per_channel, rate, scan_options, flags, data) # Wait here until the scan is done ... events will be handled in the # event handler (eventCallbackFunction). # The scan_status values are set in the event handler callback. while not scan_status['complete'] and not scan_status['error']: sleep(0.1) except KeyboardInterrupt: pass except (ValueError, NameError, SyntaxError): pass except Exception as e: print('\n', e) finally: if daq_device: if daq_device.is_connected(): # Stop the acquisition if it is still running. if ai_device and ai_info and ai_info.has_pacer(): ai_device.scan_stop() daq_device.disable_event(event_types) daq_device.disconnect() daq_device.release()
devices = get_daq_device_inventory(interface_type) number_of_devices = len(devices) if number_of_devices == 0: raise Exception('Error: No DAQ devices found') print('\nFound', number_of_devices, 'DAQ device(s):') for i in range(number_of_devices): print(' ', devices[i].product_name, ' (', devices[i].unique_id, ')', sep='') # Create the DAQ device object associated with the specified descriptor index. daq_device["daq_device_" + str(i)] = DaqDevice(devices[i]) # Get the AiDevice object and verify that it is valid. ai_device["ai_device_" + str(i)] = daq_device["daq_device_" + str(i)].get_ai_device() # Establish a connection to the DAQ device. descriptor["descriptor_" + str(i)] = daq_device["daq_device_" + str(i)].get_descriptor() print('\n') for i in range(number_of_devices): print('Connecting to', descriptor["descriptor_" + str(i)].dev_string, '- please wait...') daq_device["daq_device_" + str(i)].connect()
def main(): daq_device = None descriptor_index = 0 range_index = 0 interface_type = InterfaceType.USB low_channel = 0 high_channel = 3 try: # Get descriptors for all of the available DAQ devices. devices = get_daq_device_inventory(interface_type) number_of_devices = len(devices) if number_of_devices == 0: raise Exception('Error: No DAQ devices found') print('Found', number_of_devices, 'DAQ device(s):') for i in range(number_of_devices): print(' ', devices[i].product_name, ' (', devices[i].unique_id, ')', sep='') # Create the DAQ device object associated with the specified descriptor index. daq_device = DaqDevice(devices[descriptor_index]) # Get the AiDevice object and verify that it is valid. ai_device = daq_device.get_ai_device() if ai_device is None: raise Exception('Error: The DAQ device does not support analog input') # Establish a connection to the DAQ device. descriptor = daq_device.get_descriptor() print('\nConnecting to', descriptor.dev_string, '- please wait...') daq_device.connect() ai_info = ai_device.get_info() # The default input mode is SINGLE_ENDED. input_mode = AiInputMode.SINGLE_ENDED # If SINGLE_ENDED input mode is not supported, set to DIFFERENTIAL. if ai_info.get_num_chans_by_mode(AiInputMode.SINGLE_ENDED) <= 0: input_mode = AiInputMode.DIFFERENTIAL # Get the number of channels and validate the high channel number. number_of_channels = ai_info.get_num_chans_by_mode(input_mode) if high_channel >= number_of_channels: high_channel = number_of_channels - 1 # Get a list of supported ranges and validate the range index. ranges = ai_info.get_ranges(input_mode) if range_index >= len(ranges): range_index = len(ranges) - 1 print('\n', descriptor.dev_string, ' ready', sep='') print(' Function demonstrated: ai_device.a_in()') print(' Channels: ', low_channel, '-', high_channel) print(' Input mode: ', input_mode.name) print(' Range: ', ranges[range_index].name) try: input('\nHit ENTER to continue\n') except (NameError, SyntaxError): pass system('clear') try: while True: try: reset_cursor() print('Please enter CTRL + C to terminate the process\n') print('Active DAQ device: ', descriptor.dev_string, ' (', descriptor.unique_id, ')\n', sep='') # Display data for the specified analog input channels. for channel in range(low_channel, high_channel + 1): data = ai_device.a_in(channel, input_mode, ranges[range_index], AInFlag.DEFAULT) print('Channel(', channel, ') Data: ', '{:.6f}'.format(data), sep='') sleep(0.1) except (ValueError, NameError, SyntaxError): break except KeyboardInterrupt: pass except Exception as e: print('\n', e) finally: if daq_device: if daq_device.is_connected(): daq_device.disconnect() daq_device.release()
def main(): daq_device = None descriptor_index = 0 interface_type = InterfaceType.USB low_channel = 0 high_channel = 3 scale = TempScale.CELSIUS try: # Get descriptors for all of the available DAQ devices. devices = get_daq_device_inventory(interface_type) number_of_devices = len(devices) if number_of_devices == 0: raise Exception('Error: No DAQ devices found') print('Found', number_of_devices, 'DAQ device(s):') for i in range(number_of_devices): print(' ', devices[i].product_name, ' (', devices[i].unique_id, ')', sep='') # Create the DAQ device object for the specified descriptor index. daq_device = DaqDevice(devices[descriptor_index]) # Get the AiDevice object and verify that it is valid. ai_device = daq_device.get_ai_device() if ai_device is None: raise Exception( 'Error: The DAQ device does not support analog input') # Verify that the DAQ device has temperature channels. ai_info = ai_device.get_info() chan_types = ai_info.get_chan_types() if (AiChanType.TC not in chan_types and AiChanType.RTD not in chan_types and AiChanType.SEMICONDUCTOR not in chan_types and AiChanType.THERMISTOR not in chan_types): raise Exception( 'Error: The DAQ device does not support temperature channels') # Verify the DAQ device has the specified number of channels number_of_channels = ai_info.get_num_chans() if high_channel >= number_of_channels: high_channel = number_of_channels - 1 # Establish a connection to the DAQ device. descriptor = daq_device.get_descriptor() print('\nConnecting to', descriptor.dev_string, '- please wait...') daq_device.connect() print('\n', descriptor.dev_string, ' ready', sep='') print(' Function demonstrated: ai_device.t_in()') print(' Channels: ', low_channel, '-', high_channel) # Display channel configuration information. ai_config = ai_device.get_config() for chan in range(low_channel, high_channel + 1): # Set the specified analog channels to TC type if the specified # DAQ device is a USB-2408 or USB-2416 device if (descriptor.product_id == USB_2416_ID or descriptor.product_id == USB_2416_4AO_ID or descriptor.product_id == USB_2408_ID or descriptor.product_id == USB_2408_2AO_ID): ai_config.set_chan_type(chan, AiChanType.TC) chan_type = -1 chan_type_str = 'N/A' try: chan_type = ai_config.get_chan_type(chan) chan_type_str = chan_type.name except ULException as ul_error: if ul_error.error_code != ULError.CONFIG_NOT_SUPPORTED: raise ul_error if chan_type == AiChanType.TC: tc_type = ai_config.get_chan_tc_type(chan) chan_type_str += ' Type ' + tc_type.name elif (chan_type == AiChanType.RTD or chan_type == AiChanType.THERMISTOR): connect_type = ai_config.get_chan_sensor_connection_type(chan) chan_type_str += ' ' + connect_type.name print(' Channel', chan, 'type:', chan_type_str) print(' Temperature scaling:', scale.name) try: input('\nHit ENTER to continue\n') except (NameError, SyntaxError): pass system('clear') try: while True: try: display_strings = [] # Read data for the specified analog input channels. for channel in range(low_channel, high_channel + 1): try: data = ai_device.t_in(channel, scale) display_strings.append('Channel(' + str(channel) + ') Data: ' + '{:10.6f}'.format(data)) except ULException as ul_error: if ul_error.error_code == ULError.OPEN_CONNECTION: display_strings.append('Channel(' + str(channel) + ') Data: ' + 'Open Connection') else: raise ul_error reset_cursor() print('Please enter CTRL + C to terminate the process\n') print('Active DAQ device: ', descriptor.dev_string, ' (', descriptor.unique_id, ')\n', sep='') # Display data for the specified analog input channels. for display_string in display_strings: clear_eol() print(display_string) sleep(0.3) except (ValueError, NameError, SyntaxError): break except KeyboardInterrupt: pass except Exception as e: print('\n', e) finally: if daq_device: if daq_device.is_connected(): daq_device.disconnect() daq_device.release()
def main(): counter_number = 0 interface_type = InterfaceType.USB daq_device = None try: # Get descriptors for all of the available DAQ devices. devices = get_daq_device_inventory(interface_type) number_of_devices = len(devices) # Verify at least one DAQ device is detected. if number_of_devices == 0: raise Exception('Error: No DAQ devices found') print('Found', number_of_devices, 'DAQ device(s):') for i in range(number_of_devices): print(' ', devices[i].product_name, ' (', devices[i].unique_id, ')', sep='') # Create a DaqDevice object from the first descriptor. daq_device = DaqDevice(devices[0]) ctr_device = daq_device.get_ctr_device() # Verify the specified DAQ device supports counters. if ctr_device is None: raise Exception('Error: The DAQ device does not support counters') descriptor = daq_device.get_descriptor() print('\nConnecting to', descriptor.dev_string, '- please wait...') # Establish a connection to the device. daq_device.connect() ctr_info = ctr_device.get_info() dev_num_counters = ctr_info.get_num_ctrs() if counter_number >= dev_num_counters: counter_number = dev_num_counters - 1 print('\n', descriptor.dev_string, 'ready') print(' Function demonstrated: CtrDevice.c_in') print(' Counter:', counter_number) try: input('\nHit ENTER to continue') except (NameError, SyntaxError): pass system('clear') ctr_device.c_clear(counter_number) try: while True: try: # Read and display the data. counter_value = ctr_device.c_in(counter_number) reset_cursor() print('Please enter CTRL + C to terminate the process\n') print('Active DAQ device: ', descriptor.dev_string, ' (', descriptor.unique_id, ')\n', sep='') print(' Counter ', counter_number, ':', str(counter_value).rjust(12), sep='') stdout.flush() sleep(0.1) except (ValueError, NameError, SyntaxError): break except KeyboardInterrupt: pass except Exception as e: print('\n', e) finally: if daq_device: # Disconnect from the DAQ device. if daq_device.is_connected(): daq_device.disconnect() # Release the DAQ device resource. daq_device.release()
def main(): interface_type = InterfaceType.USB output_channel = 0 daq_device = None try: # Get descriptors for all of the available DAQ devices. devices = get_daq_device_inventory(interface_type) number_of_devices = len(devices) # Verify at least one DAQ device is detected. if number_of_devices == 0: raise Exception('Error: No DAQ device is detected') print('Found', number_of_devices, 'DAQ device(s):') for i in range(number_of_devices): print(' ', devices[i].product_name, ' (', devices[i].unique_id, ')', sep='') # Create a DaqDevice object from the first descriptor. daq_device = DaqDevice(devices[0]) ao_device = daq_device.get_ao_device() # Verify the specified DAQ device supports analog output. if ao_device is None: raise Exception( 'Error: The DAQ device does not support analog output') descriptor = daq_device.get_descriptor() print('\nConnecting to', descriptor.dev_string, '- please wait...') # Establish a connection to the device. daq_device.connect() ao_info = ao_device.get_info() output_range = ao_info.get_ranges()[ 0] # Select the first supported range. print('\n', descriptor.dev_string, 'ready') print(' Function demonstrated: AoDevice.a_out') print(' Channel:', output_channel) print(' Range:', output_range.name) try: input('\nHit ENTER to continue') except (NameError, SyntaxError): pass system('clear') print('Active DAQ device: ', descriptor.dev_string, ' (', descriptor.unique_id, ')\n', sep='') print('*Enter non-numeric value to exit') try: while True: try: # Get and set a user specified output value. out_val = input(' Enter output value (V): ') ao_device.a_out(output_channel, output_range, AOutFlag.DEFAULT, float(out_val)) # Clear the previous input request before the next input request. stdout.write(CURSOR_UP + ERASE_LINE) except (ValueError, NameError, SyntaxError): break except KeyboardInterrupt: pass except Exception as e: print('\n', e) finally: if daq_device: # Disconnect from the DAQ device. if daq_device.is_connected(): daq_device.disconnect() # Release the DAQ device resource. daq_device.release()
sys.path.append(lib_path) sys.path.append(config_path) sys.path.append(local_path) import config # import usb_driver # print('Reading from USB torque sensor:') # print(usb_driver.read('usb_torque')) from uldaq import (get_daq_device_inventory, DaqDevice, InterfaceType, AiInputMode, Range, AInFlag) try: # Get a list of available devices devices = get_daq_device_inventory(InterfaceType.USB) # Create a DaqDevice Object and connect to the device with DaqDevice(devices[0]) as daq_device: # Get AiDevice and AiInfo objects for the analog input subsystem ai_device = daq_device.get_ai_device() ai_info = ai_device.get_info() # Read and display voltage values for all analog input channels for channel in range(ai_info.get_num_chans()): data = ai_device.a_in(channel, AiInputMode.SINGLE_ENDED, Range.BIP10VOLTS, AInFlag.DEFAULT) print('Channel', channel, 'Data:', data) except: #ULException as e: print('\nERROR') #, e) # Display any error messages
def main(): timer_number = 0 frequency = 1000.0 # Hz duty_cycle = 0.5 # 50 percent pulse_count = 0 # Continuous initial_delay = 0.0 idle_state = TmrIdleState.LOW options = PulseOutOption.DEFAULT interface_type = InterfaceType.USB daq_device = None tmr_device = None try: # Get descriptors for all of the available DAQ devices. devices = get_daq_device_inventory(interface_type) number_of_devices = len(devices) # Verify at least one DAQ device is detected. if number_of_devices == 0: raise Exception('Error: No DAQ devices found') print('Found', number_of_devices, 'DAQ device(s):') for i in range(number_of_devices): print(' ', devices[i].product_name, ' (', devices[i].unique_id, ')', sep='') # Create a DaqDevice object from the first descriptor. daq_device = DaqDevice(devices[0]) tmr_device = daq_device.get_tmr_device() # Verify the specified DAQ device supports timers. if tmr_device is None: raise Exception('Error: The DAQ device does not support timers') descriptor = daq_device.get_descriptor() print('\nConnecting to', descriptor.dev_string, '- please wait...') # Establish a connection to the device. daq_device.connect() print('\n', descriptor.dev_string, 'ready') print(' Function demonstrated: TmrDevice.pulse_out_start') print(' Timer:', timer_number) print(' Frequency:', frequency, 'Hz') print(' Duty cycle:', duty_cycle) print(' Initial delay:', initial_delay) try: input('\nHit ENTER to continue') except (NameError, SyntaxError): pass # Start the timer pulse output. frequency, duty_cycle, initial_delay = tmr_device.pulse_out_start( timer_number, frequency, duty_cycle, pulse_count, initial_delay, idle_state, options) system('clear') print('Please enter CTRL + C to terminate the process\n') print('Active DAQ device: ', descriptor.dev_string, ' (', descriptor.unique_id, ')\n', sep='') print(' Actual frequency:', frequency, 'Hz') print(' Actual duty cycle:', duty_cycle, 'Hz') print(' Actual initial delay:', initial_delay, 'Hz') try: print( '\n Outputting {0:.6f} Hz pulse with duty cycle {1:.3f} for timer {2:d}' .format(frequency, duty_cycle, timer_number)) status = tmr_device.get_pulse_out_status(timer_number) count = 0 if status == TmrStatus.RUNNING: # If the status is RUNNING, then this timer does support the get_pulse_out_status() # function so the status is checked to determine if the pulse output is stopped # due to an error. while status == TmrStatus.RUNNING: status = tmr_device.get_pulse_out_status(timer_number) print_status_dots(count) count += 1 else: # If the status is IDLE, then this timer does not support the get_pulse_out_status() # function so we will wait for user input to stop the pulse output. while True: print_status_dots(count) count += 1 except KeyboardInterrupt: pass except Exception as e: print('\n', e) finally: if daq_device: # Stop the scan. if tmr_device: tmr_device.pulse_out_stop(timer_number) stdout.write(ERASE_LINE) print('\r Status:', TmrStatus.IDLE) # Disconnect from the DAQ device. if daq_device.is_connected(): daq_device.disconnect() # Release the DAQ device resource. daq_device.release()
def main(): daq_device = None ai_device = None status = ScanStatus.IDLE descriptor_index = 0 range_index = 0 interface_type = InterfaceType.USB low_channel = 0 high_channel = 3 samples_per_channel = 10000 rate = 100 scan_options = ScanOption.DEFAULTIO | ScanOption.CONTINUOUS flags = AInScanFlag.DEFAULT try: # Get descriptors for all of the available DAQ devices. devices = get_daq_device_inventory(interface_type) number_of_devices = len(devices) if number_of_devices == 0: raise Exception('Error: No DAQ devices found') print('Found', number_of_devices, 'DAQ device(s):') for i in range(number_of_devices): print(' ', devices[i].product_name, ' (', devices[i].unique_id, ')', sep='') # Create the DAQ device object associated with the specified descriptor index. daq_device = DaqDevice(devices[descriptor_index]) # Get the AiDevice object and verify that it is valid. ai_device = daq_device.get_ai_device() if ai_device is None: raise Exception( 'Error: The DAQ device does not support analog input') # Verify that the specified device supports hardware pacing for analog input. ai_info = ai_device.get_info() if not ai_info.has_pacer(): raise Exception( '\nError: The specified DAQ device does not support hardware paced analog input' ) # Establish a connection to the DAQ device. descriptor = daq_device.get_descriptor() print('\nConnecting to', descriptor.dev_string, '- please wait...') daq_device.connect() # The default input mode is SINGLE_ENDED. input_mode = AiInputMode.SINGLE_ENDED # If SINGLE_ENDED input mode is not supported, set to DIFFERENTIAL. if ai_info.get_num_chans_by_mode(AiInputMode.SINGLE_ENDED) <= 0: input_mode = AiInputMode.DIFFERENTIAL # Get the number of channels and validate the high channel number. number_of_channels = ai_info.get_num_chans_by_mode(input_mode) if high_channel >= number_of_channels: high_channel = number_of_channels - 1 channel_count = high_channel - low_channel + 1 # Get a list of supported ranges and validate the range index. ranges = ai_info.get_ranges(input_mode) if range_index >= len(ranges): range_index = len(ranges) - 1 # Get a list of supported queue types. queue_types = ai_info.get_queue_types() if len(queue_types) == 0: raise Exception('Error: The device does not support a gain queue') # Assign each channel in the queue an input mode (SE/DIFF) and a range. If multiple # ranges are supported, we will cycle through them and repeat ranges if the number # of channels exceeds the number of ranges. # # This block of code could be used to set other queue elements such as the input mode # and channel list. queue_list = [] for i in range(channel_count): queue_element = AiQueueElement() queue_element.channel = i queue_element.input_mode = input_mode queue_element.range = ranges[range_index] queue_list.append(queue_element) range_index += 1 if range_index >= len(ranges): range_index = 0 # Load the queue. ai_device.a_in_load_queue(queue_list) data = create_float_buffer(channel_count, samples_per_channel) print('\n', descriptor.dev_string, ' ready', sep='') print(' Function demonstrated: ai_device.a_in_load_queue()') print(' Channels: ', low_channel, '-', high_channel) for i in range(channel_count): print(' Channel:', queue_list[i].channel, ', Input mode:', AiInputMode(queue_list[i].input_mode).name, ', Range:', Range(queue_list[i].range).name) print(' Samples per channel: ', samples_per_channel) print(' Rate: ', rate, 'Hz') print(' Scan options:', display_scan_options(scan_options)) try: input('\nHit ENTER to continue\n') except (NameError, SyntaxError): pass # Start the acquisition. # # When using the queue, the low_channel, high_channel, input_mode, and range # parameters are ignored since they are specified in queue_array. rate = ai_device.a_in_scan(low_channel, high_channel, input_mode, ranges[range_index], samples_per_channel, rate, scan_options, flags, data) system('clear') try: while True: try: # Get the status of the background operation status, transfer_status = ai_device.get_scan_status() reset_cursor() print('Please enter CTRL + C to terminate the process\n') print('Active DAQ device: ', descriptor.dev_string, ' (', descriptor.unique_id, ')\n', sep='') print('actual scan rate = ', '{:.6f}'.format(rate), 'Hz\n') index = transfer_status.current_index print('currentTotalCount = ', transfer_status.current_total_count) print('currentScanCount = ', transfer_status.current_scan_count) print('currentIndex = ', index, '\n') # Display the data. for i in range(channel_count): print('chan =', i + low_channel, ': ', '{:.6f}'.format(data[index + i])) sleep(0.1) except (ValueError, NameError, SyntaxError): break except KeyboardInterrupt: pass except Exception as e: print('\n', e) finally: if daq_device: # Stop the acquisition if it is still running. if status == ScanStatus.RUNNING: ai_device.scan_stop() if daq_device.is_connected(): daq_device.disconnect() daq_device.release()
def main(): daq_device = None dio_device = None status = ScanStatus.IDLE samples_per_channel = 10000 rate = 1000 scan_options = ScanOption.CONTINUOUS flags = DInScanFlag.DEFAULT interface_type = InterfaceType.USB descriptor_index = 0 port_types_index = 0 try: # Get descriptors for all of the available DAQ devices. devices = get_daq_device_inventory(interface_type) number_of_devices = len(devices) if number_of_devices == 0: raise Exception('Error: No DAQ devices found') print('Found', number_of_devices, 'DAQ device(s):') for i in range(number_of_devices): print(' ', devices[i].product_name, ' (', devices[i].unique_id, ')', sep='') # Create the DAQ device object associated with the specified descriptor index. daq_device = DaqDevice(devices[descriptor_index]) # Get the DioDevice object and verify that it is valid. dio_device = daq_device.get_dio_device() if dio_device is None: raise Exception( 'Error: The DAQ device does not support digital input') # Verify that the specified device supports hardware pacing for digital input. dio_info = dio_device.get_info() if not dio_info.has_pacer(DigitalDirection.INPUT): raise Exception( 'Error: The specified DAQ device does not support hardware paced digital input' ) # Establish a connection to the DAQ device. descriptor = daq_device.get_descriptor() print('\nConnecting to', descriptor.dev_string, '- please wait...') daq_device.connect() # Get the port types for the device(AUXPORT, FIRSTPORTA, ...) port_types = dio_info.get_port_types() if port_types_index >= len(port_types): port_types_index = len(port_types) - 1 port_to_read = port_types[port_types_index] # Configure the port for input. port_info = dio_info.get_port_info(port_to_read) if (port_info.port_io_type == DigitalPortIoType.IO or port_info.port_io_type == DigitalPortIoType.BITIO): dio_device.d_config_port(port_to_read, DigitalDirection.INPUT) low_port = port_to_read hi_port = port_to_read number_of_ports = hi_port - low_port + 1 # Allocate a buffer to receive the data. data = create_int_buffer(number_of_ports, samples_per_channel) print('\n', descriptor.dev_string, ' ready', sep='') print(' Function demonstrated: dio_device.d_in_scan()') print(' Device name: ', descriptor.dev_string) print(' Port: ', low_port.name) print(' Samples per channel: ', samples_per_channel) print(' Rate: ', rate, ' Hz') print(' Scan options:', display_scan_options(scan_options)) try: input('\nHit ENTER to continue\n') except (NameError, SyntaxError): pass system("clear") # Start the acquisition. dio_device.d_in_scan(low_port, hi_port, samples_per_channel, rate, scan_options, flags, data) try: while True: try: status, transfer_status = dio_device.d_in_get_scan_status() reset_cursor() print('Please enter CTRL + C to terminate the process\n') print('Active DAQ device: ', descriptor.dev_string, ' (', descriptor.unique_id, ')\n', sep='') print('actual scan rate = ', '{:.6f}'.format(rate), 'Hz\n') index = transfer_status.current_index print('currentTotalCount = ', transfer_status.current_total_count) print('currentScanCount = ', transfer_status.current_scan_count) print('currentIndex = ', index, '\n') for i in range(number_of_ports): clear_eol() print('port =', port_types[i].name, ': ', '{:d}'.format(data[index + i])) sleep(0.1) except (ValueError, NameError, SyntaxError): break except KeyboardInterrupt: pass except Exception as e: print('\n', e) finally: if daq_device: # Stop the acquisition if it is still running. if status == ScanStatus.RUNNING: dio_device.d_in_scan_stop() if daq_device.is_connected(): daq_device.disconnect() daq_device.release()
def main(): daq_device = None daqi_device = None status = ScanStatus.IDLE samples_per_channel = 10000 rate = 1000.0 options = ScanOption.DEFAULTIO | ScanOption.CONTINUOUS flags = DaqInScanFlag.DEFAULT interface_type = InterfaceType.USB descriptor_index = 0 try: # Get descriptors for all of the available DAQ devices. devices = get_daq_device_inventory(interface_type) number_of_devices = len(devices) if number_of_devices == 0: raise Exception('Error: No DAQ devices found') print('Found', number_of_devices, 'DAQ device(s):') for i in range(number_of_devices): print(' ', devices[i].product_name, ' (', devices[i].unique_id, ')', sep='') # Create the DAQ device object associated with the specified descriptor index. daq_device = DaqDevice(devices[descriptor_index]) # Get the DaqiDevice object and verify that it is valid. daqi_device = daq_device.get_daqi_device() if daqi_device is None: raise Exception( 'Error: The device does not support daq input subsystem') # Establish a connection to the DAQ device. descriptor = daq_device.get_descriptor() print('\nConnecting to', descriptor.dev_string, '- please wait...') daq_device.connect() # Get the channel types supported by the DAQI subsystem daqi_info = daqi_device.get_info() chan_types_list = daqi_info.get_channel_types() # Configure the analog input channels. channel_descriptors = [] if DaqInChanType.ANALOG_SE in chan_types_list: configure_analog_input_channels(daq_device, channel_descriptors) # Configure the digital input channels. if DaqInChanType.DIGITAL in chan_types_list: configure_digital_input_channels(daq_device, channel_descriptors) # Configure the counter input channels. if DaqInChanType.CTR32 in chan_types_list: configure_counter_input_channels(daq_device, channel_descriptors) number_of_scan_channels = len(channel_descriptors) # Allocate a buffer to receive the data data = create_float_buffer(number_of_scan_channels, samples_per_channel) print('\n', descriptor.dev_string, ' ready', sep='') print(' Function demonstrated: daqi_device.daq_in_scan()') print(' Number of scan channels: ', number_of_scan_channels) for i in range(number_of_scan_channels): if channel_descriptors[i].type == AiInputMode.SINGLE_ENDED or \ channel_descriptors[i].type == AiInputMode.DIFFERENTIAL: print(' ScanChannel ', i, ': type = ', DaqInChanType(channel_descriptors[i].type).name, ', channel = ', channel_descriptors[i].channel, ', range = ', Range(channel_descriptors[i].range).name) else: print(' ScanChannel ', i, ': type = ', DaqInChanType(channel_descriptors[i].type).name, ', channel = ', channel_descriptors[i].channel) print(' Samples per channel: ', samples_per_channel) print(' Rate: ', rate, ' Hz') print(' Scan options:', display_scan_options(options)) try: input('\nHit ENTER to continue\n') except (NameError, SyntaxError): pass system('clear') # Start the acquisition. rate = daqi_device.daq_in_scan(channel_descriptors, samples_per_channel, rate, options, flags, data) try: while True: try: # Get the status of the background operation status, transfer_status = daqi_device.get_scan_status() reset_cursor() print('Please enter CTRL + C to terminate the process\n') print('Active DAQ device: ', descriptor.dev_string, ' (', descriptor.unique_id, ')\n', sep='') print('actual scan rate = ', '{:.6f}'.format(rate), 'Hz\n') index = transfer_status.current_index print('currentScanCount = ', transfer_status.current_scan_count) print('currentTotalCount = ', transfer_status.current_total_count) print('currentIndex = ', index, '\n') for i in range(number_of_scan_channels): if channel_descriptors[i].type == DaqInChanType.ANALOG_SE \ or channel_descriptors[i].type == DaqInChanType.ANALOG_DIFF: clear_eol() print('(Ai', channel_descriptors[i].channel, '): ', '{:.6f}'.format(data[index + i])) elif channel_descriptors[ i].type == DaqInChanType.DIGITAL: clear_eol() print('(Di', channel_descriptors[i].channel, '): ', '{:d}'.format(int(data[index + i]))) else: clear_eol() print('(Ci', channel_descriptors[i].channel, '): ', '{:d}'.format(int(data[index + i]))) sleep(0.1) except (ValueError, NameError, SyntaxError): break except KeyboardInterrupt: pass except Exception as e: print('\n', e) finally: if daq_device: # Stop the scan if it is still running. if status == ScanStatus.RUNNING: daqi_device.scan_stop() if daq_device.is_connected(): daq_device.disconnect() daq_device.release()
def main(): low_counter = 0 high_counter = 1 samples_per_channel = 2000 # Two second buffer (sample_rate * 2) sample_rate = 1000.0 # Hz scan_options = ScanOption.CONTINUOUS scan_flags = CInScanFlag.DEFAULT interface_type = InterfaceType.USB daq_device = None ctr_device = None scan_status = ScanStatus.IDLE try: # Get descriptors for all of the available DAQ devices. devices = get_daq_device_inventory(interface_type) number_of_devices = len(devices) # Verify at least one DAQ device is detected. if number_of_devices == 0: raise Exception('Error: No DAQ devices found') print('Found', number_of_devices, 'DAQ device(s):') for i in range(number_of_devices): print(' ', devices[i].product_name, ' (', devices[i].unique_id, ')', sep='') # Create a DaqDevice object from the first descriptor. daq_device = DaqDevice(devices[0]) ctr_device = daq_device.get_ctr_device() # Verify the specified DAQ device supports counters. if ctr_device is None: raise Exception('Error: The DAQ device does not support counters') # Verify the specified DAQ device supports hardware pacing for counters. ctr_info = ctr_device.get_info() if not ctr_info.has_pacer(): raise Exception( 'Error: The DAQ device does not support paced counter inputs') # Verify that the selected counters support event counting. verify_counters_support_events(ctr_info, low_counter, high_counter) number_of_counters = high_counter - low_counter + 1 descriptor = daq_device.get_descriptor() print('\nConnecting to', descriptor.dev_string, '- please wait...') # Establish a connection to the device. daq_device.connect() print('\n', descriptor.dev_string, 'ready') print(' Function demonstrated: CtrDevice.c_in_scan') print(' Counter(s):', low_counter, '-', high_counter) print(' Samples per channel:', samples_per_channel) print(' Sample rate:', sample_rate, 'Hz') print(' Scan options:', display_scan_options(scan_options)) try: input('\nHit ENTER to continue') except (NameError, SyntaxError): pass # Create a buffer for input data. data = create_int_buffer(number_of_counters, samples_per_channel) # Start the input scan. sample_rate = ctr_device.c_in_scan(low_counter, high_counter, samples_per_channel, sample_rate, scan_options, scan_flags, data) system('clear') print('Please enter CTRL + C to terminate the process\n') print('Active DAQ device: ', descriptor.dev_string, ' (', descriptor.unique_id, ')\n', sep='') print(' Actual scan rate: ', sample_rate, 'Hz') try: while True: try: # Read and display the current scan status. scan_status, transfer_status = ctr_device.get_scan_status() if scan_status != ScanStatus.RUNNING: break print(' Current scan count: ', transfer_status.current_scan_count) print(' Current total count:', transfer_status.current_total_count) print(' Current index: ', transfer_status.current_index) print('') # Read and display the data for each counter. for counter_index in range(number_of_counters): counter_value = data[transfer_status.current_index - counter_index] print(' Counter ', (counter_index + low_counter), ':', str(counter_value).rjust(12), sep='') stdout.flush() sleep(0.1) # Clear the previous status before displaying the next status. for line in range(4 + number_of_counters): stdout.write(CURSOR_UP + ERASE_LINE) except (ValueError, NameError, SyntaxError): break except KeyboardInterrupt: pass except Exception as e: print('\n', e) finally: if daq_device: # Stop the scan. if scan_status == ScanStatus.RUNNING: ctr_device.scan_stop() # Disconnect from the DAQ device. if daq_device.is_connected(): daq_device.disconnect() # Release the DAQ device resource. daq_device.release() return
def signal_processing(channel_total, srate, stime): low_channel = min(channel_total) high_channel = max(channel_total) num_scan_channels = high_channel - low_channel + 1 srate = srate samples_per_channel = srate * stime data_buffer = create_float_buffer(num_scan_channels, samples_per_channel) range_index = 0 descriptor_index = 0 interface_type = InterfaceType.USB flags = AInScanFlag.DEFAULT input_mode = AiInputMode.SINGLE_ENDED scan_options = ScanOption.DEFAULTIO daq_device = None ai_device = None status = ScanStatus.IDLE try: # Get descriptors for all of the available DAQ devices. devices = get_daq_device_inventory(interface_type) number_of_devices = len(devices) if number_of_devices == 0: raise Exception('Error: No DAQ devices found') # Create the DAQ device object associated with the specified descriptor index. daq_device = DaqDevice(devices[descriptor_index]) # Get the AiDevice object and verify that it is valid. ai_device = daq_device.get_ai_device() if ai_device is None: raise Exception( 'Error: The DAQ device does not support analog input') # Verify that the specified device supports hardware pacing for analog input. ai_info = ai_device.get_info() if not ai_info.has_pacer(): raise Exception( '\nError: The specified DAQ device does not support hardware paced analog input' ) # Establish a connection to the DAQ device. descriptor = daq_device.get_descriptor() print('\nConnecting to', descriptor.dev_string, '- please wait...') daq_device.connect() ranges = ai_info.get_ranges(input_mode) if range_index >= len(ranges): range_index = len(ranges) - 1 try: print('Start sampling...') rate = ai_device.a_in_scan(low_channel, high_channel, input_mode, Range.BIP5VOLTS, samples_per_channel, rate, scan_options, flags, data_buffer) print("mem = ", daq_device.get_info().get_mem_info()) print('data scanning') datas = [] ai_device.scan_wait(WaitType.WAIT_UNTIL_DONE, -1) for channel_number in channel_total: datas.append(data_buffer[channel_number::num_scan_channels]) except (ValueError, NameError, SyntaxError): pass except Exception as e: print('\n', e) finally: # Stop the acquisition if it is still running. ai_device.scan_stop() daq_device.disconnect() daq_device.release() return datas print("get data finished")
def main(): daq_device = None ai_device = None status = ScanStatus.IDLE descriptor_index = 0 range_index = 0 iepe_mode = IepeMode.ENABLED coupling = CouplingMode.AC sensor_sensitivity = 1.0 # volts per unit interface_type = InterfaceType.USB low_channel = 0 high_channel = 3 samples_per_channel = 10000 rate = 100 scan_options = ScanOption.CONTINUOUS flags = AInScanFlag.DEFAULT try: # Get descriptors for all of the available DAQ devices. devices = get_daq_device_inventory(interface_type) number_of_devices = len(devices) # Verify at least one DAQ device is detected. if number_of_devices == 0: raise Exception('Error: No DAQ devices found') print('Found', number_of_devices, 'DAQ device(s):') for i in range(number_of_devices): print(' ', devices[i].product_name, ' (', devices[i].unique_id, ')', sep='') # Create a DaqDevice object from the first descriptor. daq_device = DaqDevice(devices[descriptor_index]) # Get the AiDevice object and verify that it is valid. ai_device = daq_device.get_ai_device() if ai_device is None: raise Exception( 'Error: The DAQ device does not support analog input') # Verify the device supports hardware pacing for analog input. ai_info = ai_device.get_info() if not ai_info.has_pacer(): raise Exception('Error: The DAQ device does not support hardware ', 'paced analog input') # Verify the device supports IEPE if not ai_info.supports_iepe(): raise Exception('Error: The DAQ device does not support IEPE') # Establish a connection to the DAQ device. descriptor = daq_device.get_descriptor() print('\nConnecting to', descriptor.dev_string, '- please wait...') daq_device.connect() # The default input mode is SINGLE_ENDED. input_mode = AiInputMode.SINGLE_ENDED # If SINGLE_ENDED input mode is not supported, set to DIFFERENTIAL. if ai_info.get_num_chans_by_mode(AiInputMode.SINGLE_ENDED) <= 0: input_mode = AiInputMode.DIFFERENTIAL # Get the number of channels and validate the high channel number. number_of_channels = ai_info.get_num_chans_by_mode(input_mode) if high_channel >= number_of_channels: high_channel = number_of_channels - 1 channel_count = high_channel - low_channel + 1 # Get a list of supported ranges and validate the range index. ranges = ai_info.get_ranges(input_mode) if range_index >= len(ranges): range_index = len(ranges) - 1 # Set IEPE mode, AC coupling and sensor sensitivity for each channel ai_config = ai_device.get_config() for chan in range(low_channel, high_channel + 1): ai_config.set_chan_iepe_mode(chan, iepe_mode) ai_config.set_chan_coupling_mode(chan, coupling) ai_config.set_chan_sensor_sensitivity(chan, sensor_sensitivity) data = create_float_buffer(channel_count, samples_per_channel) print('\n', descriptor.dev_string, ' ready', sep='') print(' Function demonstrated: ai_device.a_in_scan()') print(' Channels: ', low_channel, '-', high_channel) print(' Input mode: ', input_mode.name) print(' Range: ', ranges[range_index].name) print(' Samples per channel: ', samples_per_channel) print(' Rate: ', rate, 'Hz') print(' Scan options:', display_scan_options(scan_options)) print(' Sensor Sensitivity: {:.6f}'.format(sensor_sensitivity), '(V/unit)') try: input('\nHit ENTER to continue\n') except (NameError, SyntaxError): pass system('clear') rate = ai_device.a_in_scan(low_channel, high_channel, input_mode, ranges[range_index], samples_per_channel, rate, scan_options, flags, data) try: while True: try: status, transfer_status = ai_device.get_scan_status() index = transfer_status.current_index if index >= 0: system('clear') print('Please enter CTRL + C to terminate the process', '\n') print('Active DAQ device: ', descriptor.dev_string, ' (', descriptor.unique_id, ')\n', sep='') print('Actual scan rate = {:.6f}\n'.format(rate)) print('currentTotalCount = ', transfer_status.current_total_count) print('currentScanCount = ', transfer_status.current_scan_count) print('currentIndex = ', index, '\n') for i in range(channel_count): print('chan ', i + low_channel, ' = ', '{:.6f}'.format(data[index + i])) sleep(0.1) except (ValueError, NameError, SyntaxError): break except KeyboardInterrupt: pass except Exception as e: print('\n', e) finally: if daq_device: # Stop the acquisition if it is still running. if status == ScanStatus.RUNNING: ai_device.scan_stop() if daq_device.is_connected(): daq_device.disconnect() daq_device.release()
from uldaq import (get_daq_device_inventory, DaqDevice, InterfaceType, DigitalDirection, DigitalPortIoType) daq_device = None interface_type = InterfaceType.USB devices = get_daq_device_inventory(interface_type) number_of_devices = len(devices) if number_of_devices == 0: raise Exception('Error: No DAQ devices found') print('Found', number_of_devices, 'DAQ device(s):') daq_device = DaqDevice(devices[0]) descriptor = daq_device.get_descriptor() print('\nConnecting to', descriptor.dev_string, '- please wait...') daq_device.connect() if daq_device: if daq_device.is_connected(): daq_device.disconnect() daq_device.release()
def main(): daq_device = None interface_type = InterfaceType.USB descriptor_index = 0 port_types_index = 0 try: # Get descriptors for all of the available DAQ devices. devices = get_daq_device_inventory(interface_type) number_of_devices = len(devices) if number_of_devices == 0: raise Exception('Error: No DAQ devices found') print('Found', number_of_devices, 'DAQ device(s):') for i in range(number_of_devices): print(' ', devices[i].product_name, ' (', devices[i].unique_id, ')', sep='') # Create the DAQ device object associated with the specified descriptor index. daq_device = DaqDevice(devices[descriptor_index]) # Get the DioDevice object and verify that it is valid. dio_device = daq_device.get_dio_device() if dio_device is None: raise Exception( 'Error: The DAQ device does not support digital input') # Establish a connection to the DAQ device. descriptor = daq_device.get_descriptor() print('\nConnecting to', descriptor.dev_string, '- please wait...') daq_device.connect() # Get the port types for the device(AUXPORT, FIRSTPORTA, ...) dio_info = dio_device.get_info() port_types = dio_info.get_port_types() if port_types_index >= len(port_types): port_types_index = len(port_types) - 1 port_to_read = port_types[port_types_index] # Configure the port for input. port_info = dio_info.get_port_info(port_to_read) if (port_info.port_io_type == DigitalPortIoType.IO or port_info.port_io_type == DigitalPortIoType.BITIO): dio_device.d_config_port(port_to_read, DigitalDirection.INPUT) print('\n', descriptor.dev_string, ' ready', sep='') print(' Function demonstrated: dio_device.d_in()') print(' Port: ', port_to_read.name) try: input('\nHit ENTER to continue\n') except (NameError, SyntaxError): pass system('clear') try: while True: try: reset_cursor() print('Please enter CTRL + C to terminate the process\n') print('Active DAQ device: ', descriptor.dev_string, ' (', descriptor.unique_id, ')\n', sep='') # Read the first port. data = dio_device.d_in(port_to_read) clear_eol() print('Port(', port_to_read.name, ') Data: ', data) sleep(0.1) except (ValueError, NameError, SyntaxError): break except KeyboardInterrupt: pass except Exception as e: print('\n', e) finally: if daq_device: if daq_device.is_connected(): daq_device.disconnect() daq_device.release()