def configureThermocoupleRegisters(self, configurations, names): ''' Set extended features for the analog inputs :configuration: - configuration type for the specified channel, string of configuration type will be converted to index number :names: - channel to set configration ''' # ljm.eWriteName(self.controller,EF_name,index) for (name, configuration) in zip(names, configurations): self.EventLog.debug( 'Configuring analog input %s for Thermocouple.' % name) index = self.extendedFeaturesIndex[configuration] EF_name = name + '_EF_INDEX' CONFIG_A_Name = name + '_EF_CONFIG_A' CONFIG_B_Name = name + '_EF_CONFIG_B' CONFIG_D_Name = name + '_EF_CONFIG_D' CONFIG_E_Name = name + '_EF_CONFIG_E' setting_names = [ EF_name, CONFIG_A_Name, CONFIG_B_Name, CONFIG_D_Name, CONFIG_E_Name ] setting_values = [index, 1, 0, 55.56, 255.37] numFrames = len(setting_values) ljm.eWriteNames(self.controller, numFrames, setting_names, setting_values)
def open(self): self.handle = ljm.openS(self.device,self.connection,self.identifier) # ==== Writing initial config ==== reg,types,values = [],[],[] for c in self.in_chan_list+self.out_chan_list: # Turn (name,val) tuples to (addr,type,val) for i,t in enumerate(c.get('write_at_open',[])): if len(t) == 2: c['write_at_open'][i] = ljm.nameToAddress(t[0])+(t[1],) # Write everything we need for r,t,v in c.get('write_at_open',[]): reg.append(r) types.append(t) values.append(v) if reg: ljm.eWriteAddresses(self.handle,len(reg),reg,types,values) # ==== Recap of the addresses to read/write ==== self.read_addresses = [c['to_read'] for c in self.in_chan_list] self.read_types = [c['dtype'] for c in self.in_chan_list] self.write_addresses = [c['to_write'] for c in self.out_chan_list] self.write_types = [c['dtype'] for c in self.out_chan_list] self.last_values = [None]*len(self.write_addresses) # ==== Measuring zero to add to the offset (if asked to) ==== if any([c.get("make_zero",False) for c in self.in_chan_list]): print("[Labjack] Please wait during offset evaluation...") off = self.eval_offset() names,values = [],[] for i,c in enumerate(self.in_chan_list): if 'make_zero' in c and c['make_zero']: names.append(c['name']+'_EF_CONFIG_E') values.append(c['offset']+off[i]) ljm.eWriteNames(self.handle,len(names),names,values)
def open_single(self): to_write = [ ("_RANGE", self.chan_range), ("_RESOLUTION_INDEX", self.resolution), ("_EF_INDEX", 1), # for applying a slope and offset ("_EF_CONFIG_D", self.gain), # index to set the gain ("_EF_CONFIG_E", self.offset), # index to set the offset ("_SETTLING_US", [0] * self.nb_channels) ] a_names = [] a_values = [] for i,chan in enumerate(self.channels): names,values = zip(*to_write) names = [chan+n for n in names] values = [v[i] if isinstance(v,list) else v for v in values] a_names.extend(names) a_values.extend(values) ljm.eWriteNames(self.handle, len(a_names), a_names, a_values) if any(self.make_zero): off = self.eval_offset() a_names = [] a_values = [] for i,make_zero in enumerate(self.make_zero): if make_zero: self.offset[i] += off[i] a_names.append(self.channels[i]+"_EF_CONFIG_E") a_values.append(self.offset[i]) ljm.eWriteNames(self.handle,len(a_names), a_names, a_values)
def open(self): self.handle = ljm.openS(self.device, self.connection, self.identifier) # ==== Writing initial config ==== reg, types, values = [], [], [] for c in self.in_chan_list + self.out_chan_list: # Turn (name,val) tuples to (addr,type,val) for i, t in enumerate(c.get('write_at_open', [])): if len(t) == 2: c['write_at_open'][i] = ljm.nameToAddress(t[0]) + (t[1], ) # Write everything we need for r, t, v in c.get('write_at_open', []): reg.append(r) types.append(t) values.append(v) if reg: ljm.eWriteAddresses(self.handle, len(reg), reg, types, values) # ==== Recap of the addresses to read/write ==== self.read_addresses = [c['to_read'] for c in self.in_chan_list] self.read_types = [c['dtype'] for c in self.in_chan_list] self.write_addresses = [c['to_write'] for c in self.out_chan_list] self.write_types = [c['dtype'] for c in self.out_chan_list] self.last_values = [None] * len(self.write_addresses) # ==== Measuring zero to add to the offset (if asked to) ==== if any([c.get("make_zero", False) for c in self.in_chan_list]): print("[Labjack] Please wait during offset evaluation...") off = self.eval_offset() names, values = [], [] for i, c in enumerate(self.in_chan_list): if 'make_zero' in c and c['make_zero']: names.append(c['name'] + '_EF_CONFIG_E') values.append(c['offset'] + off[i]) ljm.eWriteNames(self.handle, len(names), names, values)
def TE_HIGH_ACC_RAW(handle,AIN_names): numAddresses = len(AIN_names) aScanList = ljm.namesToAddresses(numAddresses, AIN_names)[0] scanRate = 10000 scansPerRead = scanRate aNames = ["AIN_ALL_NEGATIVE_CH", "AIN_ALL_RANGE", "STREAM_SETTLING_US", "STREAM_RESOLUTION_INDEX"] aValues = [ljm.constants.GND, 10.0, 0, 0] #single-ended, +/-10V, 0 (default), #0 (default) ljm.eWriteNames(handle, len(aNames), aNames, aValues) # Configure and start stream scanRate = ljm.eStreamStart(handle, scansPerRead, numAddresses, aScanList, scanRate) ret = ljm.eStreamRead(handle) acc_high_z_val = ret[0] # acc_high_z_val=[data[i]for i in range(0,len(data),1)] # ACC_LOW_Y_value=[data[i]for i in range(1,len(data),3)] # ACC_LOW_Z_value=[data[i]for i in range(2,len(data),3)] ljm.eStreamStop(handle) return acc_high_z_val
def read_LJ_TC(handle, TC_num, TC_AIN_start): # Initiate variables ain_n = [] # Initiate vector for AIN's connected to TC's ain_idx = [] # Initiate vector for TC type ain_cnfg = [] # Initiate vector for Temperature scale ain_rd = [] # Initiate vector of variable to read temps # Create variables for thermocuple settings and measurement for i in range(TC_AIN_start, TC_AIN_start + TC_num): ain_n.append('AIN' + str(i)) # AIN numbers on Labjack ain_idx.append(ain_n[i] + '_EF_INDEX') # Thermocouple type: 22 for K ain_cnfg.append( ain_n[i] + '_EF_CONFIG_A' ) # Temperature scale configuration: 0 for K, 1 for C, 2 for F ain_rd.append(ain_n[i] + '_EF_READ_A') # Reader variable # Indentify TC settings for LabJack v_idx = 22 * np.ones((TC_num, 1), float) # Identify type K thermocouple v_cnfg = np.ones((TC_num, 1), float) # Set thermocouple to read in Celcius # Comminicate settings to LabJack ljm.eWriteNames(handle, TC_num, ain_idx, v_idx) # Tell LabJack which AINs are Type K Thermocouples ljm.eWriteNames(handle, TC_num, ain_cnfg, v_cnfg) # Tell LabJack temperature scale # Read temperature values from LabJack Temps = ljm.eReadNames(handle, TC_num, ain_rd) # Output Temperatures return Temps
def fine_field_cart(xField, yField): ''' set the large and small coils to obtain a certin field value use the small coils with the labjack in command response mode. only adust the large coil if the small DACs are out of range. ''' # should we make a powersupply like class to controll the dacs on the labjack? DAC_VOLTS_PER_AMP_GAIN = 1 / u.ufloat(250.00, 0.03) # Vin/I = 1/R where R = 250.00 +- 0.03 ohms # check units here should be good: ((V/A) / (T/A)) * (T) = (V) xVoltage = (DAC_VOLTS_PER_AMP_GAIN / xAFieldGain) * xField yVoltage = (DAC_VOLTS_PER_AMP_GAIN / yAFieldgain) * yField # now write to the labjack with eWriteNames() try: names = ['DAC0', 'DAC1'] values = [xVoltage, yVoltage] numFrames = 2 # number of values to write to the labjack ljm.eWriteNames(handle, numFrames, names, values) pass except Exception as e: raise return
def configure(self): # Setup and call eWriteNames to configure AINs on the LabJack. settling_us_all = 100 # 10^-6 sec numFrames = 30 names = ["AIN0_NEGATIVE_CH", "AIN0_RANGE", "AIN0_RESOLUTION_INDEX", "AIN0_SETTLING_US", "AIN2_NEGATIVE_CH", "AIN2_RANGE", "AIN2_RESOLUTION_INDEX", "AIN2_SETTLING_US", "AIN4_NEGATIVE_CH", "AIN4_RANGE", "AIN4_RESOLUTION_INDEX", "AIN4_SETTLING_US", "AIN6_NEGATIVE_CH", "AIN6_RANGE", "AIN6_RESOLUTION_INDEX", "AIN6_SETTLING_US", "AIN8_NEGATIVE_CH", "AIN8_RANGE", "AIN8_RESOLUTION_INDEX", "AIN8_SETTLING_US", "AIN10_NEGATIVE_CH", "AIN10_RANGE", "AIN10_RESOLUTION_INDEX", "AIN10_SETTLING_US", "AIN12_RANGE", "AIN12_RESOLUTION_INDEX", "AIN12_SETTLING_US", "AIN13_RANGE", "AIN13_RESOLUTION_INDEX", "AIN13_SETTLING_US"] aValues = [ 1, 10, 1, settling_us_all, 3, 10, 1, settling_us_all, 5, 10, 1, settling_us_all, 7, 10, 1, settling_us_all, 9, 10, 1, settling_us_all, 11, 10, 1,settling_us_all, 10, 1, settling_us_all, 10, 1, settling_us_all] ljm.eWriteNames(self.handle, numFrames, names, aValues) print("\nSet configuration:") print("!!!!!!! BE CAREFUL , YOU ARE USING ENAC CALIBRATION FILE !!!!!") for i in range(numFrames): print(" %s : %f" % (names[i], aValues[i]))
def open(self): self.handle = ljm.openS(self.device, self.connection, self.identifier) names, values = [], [] for c in self.chan_list: if "to_write" in c: for n, v in c['to_write']: names.append(c['name'] + n) values.append(v) #names.append("STREAM_NUM_ADDRESSES");values.append(len(self.channels)) names.append("STREAM_SCANRATE_HZ") values.append(self.scan_rate) names.append("STREAM_RESOLUTION_INDEX") values.append(self.resolution) ljm.eWriteNames(self.handle, len(names), names, values) scan_rate = ljm.eReadName(self.handle, "STREAM_SCANRATE_HZ") if scan_rate != self.scan_rate: print("[Labjack] Actual scan_rate:", scan_rate, "instead of", self.scan_rate) self.scan_rate = scan_rate if any([c.get("make_zero", False) for c in self.chan_list]): print("[Labjack] Please wait during offset evaluation...") off = self.eval_offset() names, values = [], [] for i, c in enumerate(self.chan_list): if 'make_zero' in c and c['make_zero']: c['offset'] += c['gain'] * off[i] self.n = 0 # Number of data points (to rebuild time)
def new(self): """Initialise the device and create the handle""" self.handle = ljm.open(ljm.constants.dtANY, ljm.constants.ctANY, "ANY") if self.mode=="streamer": #self.channels = ["AIN0", "AIN1", "AIN2", "AIN3"] #Scan list names to stream numAddresses = len(self.channels) aScanList = ljm.namesToAddresses(numAddresses, self.channels)[0] aName_prefix=["AIN_ALL_NEGATIVE_CH","STREAM_SETTLING_US","STREAM_RESOLUTION_INDEX"] suffixes = ["_RANGE"] aNames = aName_prefix+[chan+s for chan in self.channels for s in suffixes] temp_values=[[self.chan_range[chan]] for chan,a in enumerate(self.channels)] aValues = [ljm.constants.GND, 0, self.resolution]+[item for sublist in temp_values for item in sublist] #print aValues #print "----------------------" #print aNames ljm.eWriteNames(self.handle, len(aNames), aNames, aValues) # Configure and start stream scanRate = ljm.eStreamStart(self.handle, self.scansPerRead, numAddresses, aScanList, self.scanRate) elif self.mode=="single": numAddresses = len(self.channels) #suffixes = ["_EF_INDEX","_NEGATIVE_CH", "_RANGE", "_RESOLUTION_INDEX", "_EF_CONFIG_D", "_EF_CONFIG_E"] # conf for automatic gain/offset suffixes = ["_NEGATIVE_CH", "_RANGE", "_RESOLUTION_INDEX"] aNames = [chan+s for chan in self.channels for s in suffixes] #aValues = [[1,ljm.constants.GND, self.chan_range[chan],0,self.gain[chan],self.offset[chan]] for chan,a in enumerate(self.channels)] aValues = [[ljm.constants.GND, self.chan_range[chan],self.resolution] for chan,_ in enumerate(self.channels)] aValues=[item for sublist in aValues for item in sublist] #flatten #print aValues #print "----------------------" #print aNames ljm.eWriteNames(self.handle, len(aNames), aNames, aValues) else: raise Exception("Invalid mode, please select 'single' or 'streamer'")
def fine_field_cart(xField, yField, zField, handle): """ Set powersupplies to the proper current for each coil and set the DACs to the correct voltage with the labjack. """ t0 = time.time() # create the thread objects to handle the serial wait times xThread = threading.Thread(target=xCoil.setField, args=[xField]) yThread = threading.Thread(target=yCoil.setField, args=[yField]) zThread = threading.Thread(target=zCoil.setLargeCoilField, args=[zField]) # start the threads() xThread.start() yThread.start() zThread.start() # now adust the adustment coils with the labjack # Setup and call eWriteNames to write values to the LabJack. numFrames = 2 names = [xCoil.dacName, yCoil.dacName] analogValues = [xCoil.dacVoltage, yCoil.dacVoltage] # [2.5 V, 12345] ljm.eWriteNames(handle, numFrames, names, analogValues) # wait for the threads to finish before moving on # (prevent thread duplication in an additional call) xThread.join() yThread.join() zThread.join() t1 = time.time() #print('total time between = %s' % (t1-t0)) #print('total time between = {0}'.format(t1-t0)) # return
def _LJWriteValues(self, names, values): ''' :names: - list of LJ channels names to write to :values: -list of values to write to the channels ''' numFrames = len(names) ljm.eWriteNames(self.controller, numFrames, names, values)
def switch_nd(self, pol_state): if len(pol_state) != 2: self.log_msg_q.put( (log.ERROR, MODULE, "Ant {}: Invalid number of noise diode arguments".format( self.ant_num))) return (pol, state) = pol_state if state == 'off': state_val = 1 elif state == 'on': state_val = 0 else: msg = "Ant {}: Invalid noise diode state requested: {}".format( self.ant_num, state) self.log_msg_q.put((log.ERROR, MODULE, msg)) return if pol == 'ab' or pol == 'both': msg = "Ant {}: Turning both polarizations noise diode {}".format( self.ant_num, state) ljm.eWriteNames(self.lj_handle, 1, [port.ND_A, port.ND_B], [state_val, state_val]) elif pol == 'a': msg = "Ant {}: Turning polarization a noise diode {}".format( self.ant_num, state) ljm.eWriteName(self.lj_handle, port.ND_A, state_val) elif pol == 'b': msg = "Ant {}: Turning polarization b noise diode {}".format( self.ant_num, state) ljm.eWriteName(self.lj_handle, port.ND_B, state_val) else: msg = "Ant {}: Invalid noise diode state requested: {}".format( self.ant_num, pol) self.log_msg_q.put((log.ERROR, MODULE, msg))
def open_streamer(self): self.a_scan_list = \ ljm.namesToAddresses(self.nb_channels, self.channels)[0] if self.verbose: self.queue = Queue() a_names = ["AIN_ALL_RANGE", "STREAM_SETTLING_US", "STREAM_RESOLUTION_INDEX"] a_values = [int(self.chan_range[0]), 0, int(self.resolution[0])] ljm.eWriteNames(self.handle, len(a_names), a_names, a_values) self.stream_started = False
def stream_out(self, channels, data, scanRate, loop=0): ''' Streams data at a given scan rate. Args: channels (list): Output channels to stream on, e.g. ['DAC0', 'DAC1'] data (array): Data to stream out. For streaming on multiple channels, use column 0 for DAC0 and column 1 for DAC1. scanRate (float): desired output rate in scans/s loop (int): number of values from the end of the buffer to loop after finishing stream ''' try: ''' Stop streaming if currently running ''' ljm.eStreamStop(self.handle) except: pass n = np.ceil(np.log10(2 * (1 + len(data))) / np.log10(2)) buffer_size = 2**n for i in range(len(channels)): aNames = [ "STREAM_OUT%i_TARGET" % i, "STREAM_OUT%i_BUFFER_SIZE" % i, "STREAM_OUT%i_ENABLE" % i ] ch = channels[i] if ch == 'FIO_STATE': target = 2500 else: target = 1000 + 2 * ch aValues = [target, buffer_size, 1] self._write_array(aNames, aValues) if ch == 'FIO_STATE': target = ['STREAM_OUT%i_BUFFER_U16' % i] * len(data) else: target = ['STREAM_OUT%i_BUFFER_F32' % i] * len(data) try: target_array = data[:, i] except IndexError: target_array = data ljm.eWriteNames(self.handle, len(target_array), target, list(target_array)) aNames = [ "STREAM_OUT%i_LOOP_SIZE" % i, "STREAM_OUT%i_SET_LOOP" % i ] aValues = [loop * len(data), 1] self._write_array(aNames, aValues) self.aScanList.append(4800 + i) scanRate = ljm.eStreamStart(self.handle, 1, len(self.aScanList), self.aScanList, scanRate)
def open_thermocouple(self): to_write = [ ("_EF_INDEX", 22), # for thermocouple measures ("_EF_CONFIG_A", 1), # for degrees C ("_EF_CONFIG_B", 60052), # for type K ("_RESOLUTION_INDEX", self.resolution) ] a_names = [] a_values = [] for i,chan in enumerate(self.channels): names,values = zip(*to_write) names = [chan+n for n in names] values = [v[i] if isinstance(v,list) else v for v in values] a_names.extend(names) a_values.extend(values) ljm.eWriteNames(self.handle, len(a_names), a_names, a_values)
def Init(): # Open first found LabJack handle = ljm.open(ljm.constants.dtANY, ljm.constants.ctANY, "ANY") #handle = ljm.openS("ANY", "ANY", "ANY") #A2D setup info = ljm.getHandleInfo(handle) print("Opened a LabJack with Device type: %i, Connection type: %i,\n" \ "Serial number: %i, IP address: %s, Port: %i,\nMax bytes per MB: %i" % \ (info[0], info[1], info[2], ljm.numberToIP(info[3]), info[4], info[5])) # Setup and call eWriteNames to configure AINs on the LabJack. numFrames = 3 names = ["AIN_ALL_NEGATIVE_CH", "AIN_ALL_RANGE", "AIN_ALL_RESOLUTION_INDEX"] aValues = [199, 10, 1] ljm.eWriteNames(handle, numFrames, names, aValues) #return handle, Info return handle
def clear(self): # Turn off PWM output and counter aNames = ["DIO_EF_CLOCK0_ENABLE", "DIO0_EF_ENABLE", "DIO2_EF_ENABLE", "DIO3_EF_ENABLE"] aValues = [0, 0, 0, 0] numFrames = len(aNames) self.set_flap_servo(self.flap_servo_neutral) self.set_motor_servo(self.motor_servo_neutral) time.sleep(0.7) results = ljm.eWriteNames(self.handle, numFrames, aNames, aValues) ljm.close(self.handle) ##############################
def configureRTDRegisters(self, configurations, names): ''' Set the configuration registers for the rtd inputs :configurations: - type of rtds to configure :names:- names of analog inuputs that will be used ''' for (name, configuration) in zip(names, configurations): self.EventLog.debug('Configuring analog input %s for RTD.' % name) EF_name = name + '_EF_INDEX' CONFIG_A_Name = name + '_EF_CONFIG_A' #temperature display CONFIG_B_Name = name + '_EF_CONFIG_B' #excitation circuit CONFIG_D_Name = name + '_EF_CONFIG_D' #excitation Voltage CONFIG_E_Name = name + '_EF_CONFIG_E' #excitation resistance index = self.extendedFeaturesIndex[configuration] setting_names = [ EF_name, CONFIG_A_Name, CONFIG_B_Name, CONFIG_D_Name, CONFIG_E_Name ] setting_values = [index, 1, 4, 2.500, 1000] numFrames = len(setting_values) ljm.eWriteNames(self.controller, numFrames, setting_names, setting_values)
def open(self): self.handle = ljm.openS(self.device,self.connection,self.identifier) names,values = [],[] for c in self.chan_list: if "to_write" in c: for n,v in c['to_write']: names.append(c['name']+n) values.append(v) #names.append("STREAM_NUM_ADDRESSES");values.append(len(self.channels)) names.append("STREAM_SCANRATE_HZ");values.append(self.scan_rate) names.append("STREAM_RESOLUTION_INDEX");values.append(self.resolution) ljm.eWriteNames(self.handle,len(names),names,values) scan_rate = ljm.eReadName(self.handle,"STREAM_SCANRATE_HZ") if scan_rate != self.scan_rate: print("[Labjack] Actual scan_rate:",scan_rate,"instead of",self.scan_rate) self.scan_rate = scan_rate if any([c.get("make_zero",False) for c in self.chan_list]): print("[Labjack] Please wait during offset evaluation...") off = self.eval_offset() names,values = [],[] for i,c in enumerate(self.chan_list): if 'make_zero' in c and c['make_zero']: c['offset'] += c['gain']*off[i] self.n = 0 # Number of data points (to rebuild time)
clock_divisor = 64 try: # Configure the analog inputs' negative channel, range, settling time and # resolution. # Note when streaming, negative channels and ranges can be configured for # individual analog inputs, but the stream has only one settling time and # resolution. aNames = [ "AIN0_NEGATIVE_CH", "DIO_EF_CLOCK0_ENABLE", "DIO_EF_CLOCK0_DIVISOR", "DIO_EF_CLOCK0_ROLL_VALUE", "DIO_EF_CLOCK0_ENABLE" ] aValues = [ljm.constants.GND, 0, clock_divisor, 0, 1] ljm.eWriteNames(handle, len(aNames), aNames, aValues) # Configure and start stream scanRate = ljm.eStreamStart(handle, scansPerRead, numAddresses, aScanList, scanRate) print("\nStream started with a scan rate of %0.0f Hz." % scanRate) print("\nPerforming %i stream reads." % MAX_REQUESTS) start = datetime.now() totScans = 0 totSkip = 0 # Total skipped samples output_names = ['clock', 'weight'] cur_log = "dyno" + "_" + str(start.month) + "_" + str( start.day) + "_" + str(start.year) + "_" + str(start.hour) + "_" + str( start.minute) + "_" + str(start.second) + ".csv"
def configure(self): names = [ "AIN0_NEGATIVE_CH", "AIN0_RANGE", "AIN0_RESOLUTION_INDEX", "AIN1_NEGATIVE_CH", "AIN1_RANGE", "AIN1_RESOLUTION_INDEX", "AIN2_NEGATIVE_CH", "AIN2_RANGE", "AIN2_RESOLUTION_INDEX", "AIN3_NEGATIVE_CH", "AIN3_RANGE", "AIN3_RESOLUTION_INDEX", "AIN4_NEGATIVE_CH", "AIN4_RANGE", "AIN4_RESOLUTION_INDEX", "AIN5_NEGATIVE_CH", "AIN5_RANGE", "AIN5_RESOLUTION_INDEX", "AIN6_NEGATIVE_CH", "AIN6_RANGE", "AIN6_RESOLUTION_INDEX", "AIN7_NEGATIVE_CH", "AIN7_RANGE", "AIN7_RESOLUTION_INDEX", #"AIN8_NEGATIVE_CH", "AIN8_RANGE", "AIN8_RESOLUTION_INDEX", #"AIN9_NEGATIVE_CH", "AIN9_RANGE", "AIN9_RESOLUTION_INDEX", "AIN10_NEGATIVE_CH", "AIN10_RANGE", "AIN10_RESOLUTION_INDEX", "AIN11_NEGATIVE_CH", "AIN11_RANGE", "AIN11_RESOLUTION_INDEX", "AIN12_NEGATIVE_CH", "AIN12_RANGE", "AIN12_RESOLUTION_INDEX", "AIN13_NEGATIVE_CH", "AIN13_RANGE", "AIN13_RESOLUTION_INDEX" ] l_names = len(names) aValues = [ 1, 1, 12, #0 199, 1, 12, #1 3, 1, 12, #2 199, 1, 12, #3 5, 1, 12, #4 199, 1, 12, #5 7, 1, 12, #6 199, 1, 12, #7 #199, 1, 12,#8 #199, 1, 12,#9 199, 1, 12, #10 199, 1, 12, #11 199, 1, 12, #12 199, 1, 12 #13 ] ljm.eWriteNames(self.handle, l_names, names, aValues)
#handle = ljm.open(ljm.constants.dtANY, ljm.constants.ctANY, "ANY") # Any device, Any connection, Any identifier info = ljm.getHandleInfo(handle) print("Opened a LabJack with Device type: %i, Connection type: %i,\n" "Serial number: %i, IP address: %s, Port: %i,\nMax bytes per MB: %i" % (info[0], info[1], info[2], ljm.numberToIP(info[3]), info[4], info[5])) deviceType = info[0] # Configure the PWM output and counter. if deviceType == ljm.constants.dtT4: # For the T4, use FIO6 (DIO6) for the PWM output pwmDIO = 6 # Set FIO and EIO lines to digital I/O. ljm.eWriteNames(handle, 2, ["DIO_INHIBIT", "DIO_ANALOG_ENABLE"], [0xFBF, 0x000]) else: # For the T7 and other devices, use FIO0 (DIO0) for the PWM output pwmDIO = 0 aNames = [ "DIO_EF_CLOCK0_DIVISOR", "DIO_EF_CLOCK0_ROLL_VALUE", "DIO_EF_CLOCK0_ENABLE", "DIO%i_EF_ENABLE" % pwmDIO, "DIO%i_EF_INDEX" % pwmDIO, "DIO%i_EF_CONFIG_A" % pwmDIO, "DIO%i_EF_ENABLE" % pwmDIO, "DIO18_EF_ENABLE", "DIO18_EF_INDEX", "DIO18_EF_ENABLE" ] aValues = [1, 8000, 1, 0, 0, 2000, 1, 0, 7, 1] numFrames = len(aNames) results = ljm.eWriteNames(handle, numFrames, aNames, aValues)
def main(): try: openTime = datetime.utcnow() daqHandle = ljm.openS("T7", "TCP", "ANY") daqInfo = ljm.getHandleInfo(daqHandle) print( "Opened a LabJack with Device type: %i, Connection type: %i,\n" "Serial number: %i, IP address: %s, Port: %i,\nMax bytes per MB: %i" % (daqInfo[0], daqInfo[1], daqInfo[2], ljm.numberToIP( daqInfo[3]), daqInfo[4], daqInfo[5])) csvWriter, csvFile = generateCSV() timeHeader = ["TIME"] timeHeader.extend(aScanListNames) csvWriter.writerow(timeHeader) if (daqInfo[0] == ljm.constants.dtT7): # Disable triggered streaming ljm.eWriteName(daqHandle, "STREAM_TRIGGER_INDEX", 0) # Enabling internally-clocked stream. ljm.eWriteName(daqHandle, "STREAM_CLOCK_SOURCE", 0) # All negative channels are single-ended, AIN0 and AIN1 ranges are # +/-10 V, stream settling is 0 (default) and stream resolution index # is 0 (default). aNames = [ "AIN_ALL_NEGATIVE_CH", "AIN_ALL_RANGE", "STREAM_SETTLING_US", "STREAM_RESOLUTION_INDEX" ] aValues = [ljm.constants.GND, 10.0, 0, 0] ljm.eWriteNames(daqHandle, len(aNames), aNames, aValues) # Configure and start stream scanStartTime = datetime_to_float(datetime.utcnow()) lastScanStartTime = scanStartTime scanRate = ljm.eStreamStart(daqHandle, scansPerRead, numAddresses, aScanList, scanRate) print("\nStream started with a scan rate of %0.0f Hz." % scanRate) totScans = 0 totSkip = 0 # Total skipped samples aScanClockNames = ["SYSTEM_TIMER_20HZ", "CORE_TIMER"] startClocks = ljm.eReadNames(daqHandle, len(aScanClockNames), aScanClockNames) start20HzClock = startClocks[0] start40MHzClock = startClocks[1] count40MHzRollover = 0 # Stream Configuration aScanListNames = ["AIN0", "AIN1", "AIN2", "AIN3"] # Scan list names to stream aScanList = ljm.namesToAddresses(len(numAddresses), aScanListNames)[0] scanRate = 10 scansPerRead = int(scanRate / 2) # while True: try: ret = ljm.eStreamRead(daqHandle) scanStopTime = datetime_to_float(datetime.utcnow()) aData = ret[0] scans = len(aData) / numAddresses totScans += scans # Count the skipped samples which are indicated by -9999 values. Missed # samples occur after a device's stream buffer overflows and are # reported after auto-recover mode ends. curSkip = aData.count(-9999.0) totSkip += curSkip ainStr = "" for j in range(0, numAddresses): ainStr += "%s = %0.5f, " % (aScanListNames[j], aData[j]) print(" 1st scan out of %i: %s" % (scans, ainStr)) print( " Scans Skipped = %0.0f, Scan Backlogs: Device = %i, LJM = " "%i" % (curSkip / numAddresses, ret[1], ret[2])) timeData = np.linspace(scanStartTime, scanStopTime, num=scansPerRead) print timeData print aData scanData = np.array(aData) print scanData print("Rows/Cols: ", scanData.shape) print("Num address: ", numAddresses) splitScanData = np.split(scanData, scansPerRead) print splitScanData print("Rows/Cols: ", splitScanData[0].shape) csvWriter.writerows(splitScanData) verticalStackedSplitScanData = np.vstack(splitScanData) print verticalStackedSplitScanData print "Test" # csvWriter.writerows(verticalStackedSplitScanData) #use write rows once separated with numpy array except Exception as e: raise e # break except KeyboardInterrupt: # Extend to save button interrupt pass # break # Close T7 Connection try: print("\nStop Stream") ljm.eStreamStop(daqHandle) except ljm.LJMError: ljme = sys.exc_info()[1] print(ljme) except Exception: e = sys.exc_info()[1] print(e) except ljm.LJMError: ljme = sys.exc_info()[1] print(ljme) except Exception: e = sys.exc_info()[1] print(e) csvFile.close() ljm.close(daqHandle)
ljm.eWriteNames(handle, numFrames, names, aValues) #return handle, Info return handle ''' Writing analogue values (0 to 5 v) in the DAC ports ''' def DAC_Write(handle,DAC, Volt): # Volt is an integer (e.g., can be used for clossing or openning Shutter: 0=close, 5=open) # This can also be used for digital ports e.g.: DAC_Write(DAQ_handle, 'FIO0', 1) brings the port FIO0 to 3 v ljm.eWriteName(handle, DAC, Volt) #print int(round(time.time() * 1000)) return ''' Reading analogue inpute values (0 to 10 v) in the AIN ports. To change the range of input voltage or speed of conversion, below lines should be changed in the intialization: numFrames = 3 names = ["AIN0_NEGATIVE_CH", "AIN0_RANGE", "AIN0_RESOLUTION_INDEX"] aValues = [199, 2, 1] ljm.eWriteNames(handle, numFrames, names, aValues) ''' def AIN_Read(handle,AIN): return ljm.eReadNames(handle,1 , [AIN]) ''' Writing 1 or 0 in the digital ports. Digital port will 3.3v if State = 1 and 0v if State = 0. ''' def Digital_Ports_Write(handle,Port,State):
info = ljm.getHandleInfo(handle) print("Opened a LabJack with Device type: %i, Connection type: %i,\n" \ "Serial number: %i, IP address: %s, Port: %i,\nMax bytes per MB: %i" % \ (info[0], info[1], info[2], ljm.numberToIP(info[3]), info[4], info[5])) # Configure the PWM output and counter. aNames = ["DIO_EF_CLOCK0_DIVISOR", "DIO_EF_CLOCK0_ROLL_VALUE", "DIO_EF_CLOCK0_ENABLE", "DIO0_EF_INDEX", "DIO0_EF_VALUE_A", "DIO0_EF_ENABLE", "DIO18_EF_INDEX", "DIO18_EF_ENABLE"] aValues = [1, 8000, 1, 0, 2000, 1, 7, 1] numFrames = len(aNames) results = ljm.eWriteNames(handle, numFrames, aNames, aValues) # Wait 1 second. time.sleep(1.0) # Read from the counter. value = ljm.eReadName(handle, "DIO18_EF_READ_A") print("\nCounter = %f" % (value)) # Turn off PWM output and counter aNames = ["DIO_EF_CLOCK0_ENABLE", "DIO0_EF_ENABLE"] aValues = [0, 0] numFrames = len(aNames) results = ljm.eWriteNames(handle, numFrames, aNames, aValues)
pChannel = str(analog_sensors[sensor].getPositiveChannel()) nChannel = int(analog_sensors[sensor].getNegativeChannel()) aScanListNames.append("AIN" + pChannel) if (nChannel > 0): print("configuring negative channel") aWriteNames.append("AIN" + pChannel + "_NEGATIVE_CH") aWriteValues.append(nChannel) if (int(analog_sensors[sensor].getExtendedFeatures()) > 0): aWriteNames.append("AIN" + pChannel + "_EF_INDEX") aWriteValues.append(int(analog_sensors[sensor].getExtendedFeatures())) print "Scan list names", aScanListNames print "Names written", aWriteNames print "Values written", aWriteValues ljm.eWriteNames(handle, len(aWriteNames), aWriteNames, aWriteValues) results = ljm.eReadNames(handle, len(aWriteNames), aWriteNames) print("\neReadNames results: ") for i in range(len(aWriteNames)): print(" Name - %s, value : %d" % (aWriteNames[i], results[i])) aReadListNames = [] channelNames = [] # Read Configuration for sensorName, sensor in analog_sensors.items(): if sensor is not None: channelNames.append(str(sensor.getName())) if (int(sensor.getExtendedFeatures()) > 0):
#handle = ljm.open(ljm.constants.dtANY, ljm.constants.ctANY, "ANY") info = ljm.getHandleInfo(handle) print("Opened a LabJack with Device type: %i, Connection type: %i,\n" \ "Serial number: %i, IP address: %s, Port: %i,\nMax bytes per MB: %i" % \ (info[0], info[1], info[2], ljm.numberToIP(info[3]), info[4], info[5])) # Configure the PWM output and counter. aNames = [ "DIO_EF_CLOCK0_DIVISOR", "DIO_EF_CLOCK0_ROLL_VALUE", "DIO_EF_CLOCK0_ENABLE", "DIO0_EF_INDEX", "DIO0_EF_VALUE_A", "DIO0_EF_ENABLE", "DIO18_EF_INDEX", "DIO18_EF_ENABLE" ] aValues = [1, 8000, 1, 0, 2000, 1, 7, 1] numFrames = len(aNames) results = ljm.eWriteNames(handle, numFrames, aNames, aValues) # Wait 1 second. time.sleep(1.0) # Read from the counter. value = ljm.eReadName(handle, "DIO18_EF_READ_A") print("\nCounter = %f" % (value)) # Turn off PWM output and counter aNames = ["DIO_EF_CLOCK0_ENABLE", "DIO0_EF_ENABLE"] aValues = [0, 0] numFrames = len(aNames) results = ljm.eWriteNames(handle, numFrames, aNames, aValues)
def _write_array(self, registers, values): ljm.eWriteNames(self.handle, len(registers), registers, values)
scanRate = 20 scansPerRead = 60 # Add the stream out token 4800 to the end aScanList.extend([4800]) try: # Configure the analog inputs' negative channel, range, settling time and # resolution. # Note when streaming, negative channels and ranges can be configured for # individual analog inputs, but the stream has only one settling time and # resolution. aNames = ["AIN_ALL_NEGATIVE_CH", "AIN_ALL_RANGE", "STREAM_SETTLING_US", "STREAM_RESOLUTION_INDEX"] aValues = [ljm.constants.GND, 10.0, 0, 0] # single-ended, +/-10V, 0 (default), # 0 (default) ljm.eWriteNames(handle, len(aNames), aNames, aValues) # Configure and start stream print(aScanList[0:TOTAL_NUM_CHANNELS]) scanRate = ljm.eStreamStart(handle, scansPerRead, TOTAL_NUM_CHANNELS, aScanList, scanRate) print("\nStream started with a scan rate of %0.0f Hz." % scanRate) print("\nPerforming %i stream reads." % MAX_REQUESTS) start = datetime.now() totScans = 0 totSkip = 0 # Total skipped samples i = 1 while i <= MAX_REQUESTS: ret = ljm.eStreamRead(handle)
def StreamCollection(max_requests=60, scanrate=1000, bKick=True, minSum=-1.0): #time will take about max_requests/2 in seconds MAX_REQUESTS = max_requests # The number of eStreamRead calls that will be performed. FIRST_AIN_CHANNEL = 0 #AIN0 NUMBER_OF_AINS = 3 # AIN0: L-R, AIN1: Sum, AIN2: T-B rawData = [] # open the all ports and get the labjack handle handle = xyz.openPorts() info = ljm.getHandleInfo(handle) print("Opened a LabJack with Device type: %i, Connection type: %i,\n" \ "Serial number: %i, IP address: %s, Port: %i,\nMax bytes per MB: %i" % \ (info[0], info[1], info[2], ljm.numberToIP(info[3]), info[4], info[5])) # Stream Configuration aScanListNames = [ "AIN%i" % i for i in range(FIRST_AIN_CHANNEL, FIRST_AIN_CHANNEL + NUMBER_OF_AINS) ] #Scan list names print("\nScan List = " + " ".join(aScanListNames)) numAddresses = len(aScanListNames) aScanList = ljm.namesToAddresses(numAddresses, aScanListNames)[0] global scanRate scanRate = scanrate scansPerRead = int(scanRate / 2) try: # Configure the analog inputs' negative channel, range, settling time and # resolution. # Note when streaming, negative channels and ranges can be configured for # individual analog inputs, but the stream has only one settling time and # resolution. aNames = [ "AIN_ALL_NEGATIVE_CH", "AIN_ALL_RANGE", "STREAM_SETTLING_US", "STREAM_RESOLUTION_INDEX" ] aValues = [ljm.constants.GND, 10.0, 0, 0] #single-ended, +/-10V, 0 (default), #0 (default) ljm.eWriteNames(handle, len(aNames), aNames, aValues) eventNumber = 0 # keeps track of the event we make a new one each time the user resets the pendulum and hits enter input('start?') while True: if bKick: # kick the pendulum to drive it so we can take period data. print('Kicking') xr, yr, zr = kickUpAndWait( 0, 4.5e-6, 0, 10) # kick the field and save the current values. #xr,yr,zr = kickUpAndWait(0, 2e-6, 0, 10) # seems like we maight want a bit less kick # Configure and start stream scanRate = ljm.eStreamStart(handle, scansPerRead, numAddresses, aScanList, scanRate) print("\nStream started with a scan rate of %0.0f Hz." % scanRate) print("\nPerforming %i stream reads." % MAX_REQUESTS) if bKick: kickDown(xr, yr, zr) # put the currents back to where they were print('Done Kicking!') # then do the stream. start = datetime.now() totScans = 0 totSkip = 0 # Total skipped samples i = 1 # counter for number of stream requests while i <= MAX_REQUESTS: ret = ljm.eStreamRead(handle) data = ret[0] scans = len(data) / numAddresses totScans += scans # Count the skipped samples which are indicated by -9999 values. Missed # samples occur after a device's stream buffer overflows and are # reported after auto-recover mode ends. curSkip = data.count(-9999.0) totSkip += curSkip print("\neStreamRead %i" % i) ainStr = "" for j in range(0, numAddresses): ainStr += "%s = %0.5f " % (aScanListNames[j], data[j]) print(" 1st scan out of %i: %s" % (scans, ainStr)) print(" Scans Skipped = %0.0f, Scan Backlogs: Device = %i, LJM = " \ "%i" % (curSkip/numAddresses, ret[1], ret[2])) newDataChunk = np.reshape( data, (-1, NUMBER_OF_AINS) ) # reshape the data to have each row be a different reading if i != 1: # if we are not on the first run. rawData = np.vstack((rawData, newDataChunk)) else: rawData = newDataChunk # this should only run on the first time. #print('FIRST RUN THROUGH') #print(rawData,'\n') i += 1 end = datetime.now() print("\nTotal scans = %i" % (totScans)) tt = (end - start).seconds + float( (end - start).microseconds) / 1000000 print("Time taken = %f seconds" % (tt)) print("LJM Scan Rate = %f scans/second" % (scanRate)) print("Timed Scan Rate = %f scans/second" % (totScans / tt)) print("Timed Sample Rate = %f samples/second" % (totScans * numAddresses / tt)) print("Skipped scans = %0.0f" % (totSkip / numAddresses)) print("\nStop Stream") ljm.eStreamStop(handle) print('current querry!') # update the powersupply field readings so we can reference them later xyz.xCoil.getLargeCoilField() xyz.yCoil.getLargeCoilField() print('done with current querry!') # format data to include field values rawDataWithFieldValues = [] print(rawData) first = True for j, row in enumerate( rawData ): # setp throuh and append the field values to each datapoint if row[1] >= minSum: timestamp = j * (1.0 / scanRate) rowWithFieldValues = np.append( row, np.array([ xyz.xCoil.largeCoilField, xyz.yCoil.largeCoilField, timestamp, eventNumber ])) # for now we aren't using the adustment coils if first: first = False rawDataWithFieldValues = rowWithFieldValues else: # not on the first loop rawDataWithFieldValues = np.vstack( (rawDataWithFieldValues, rowWithFieldValues)) print(np.shape(rawDataWithFieldValues)) # and add it to our master data array if eventNumber != 0: #print(np.shape(allTheData)) #print('--------') #print(np.shape(rawDataWithFieldValues)) allTheData = np.vstack((allTheData, rawDataWithFieldValues)) #print(np.shape(allTheData)) else: allTheData = rawDataWithFieldValues print(allTheData) print(np.shape(allTheData)) input( "finished with eventNumber %s. Press enter to start a new data run." % eventNumber) eventNumber += 1 # increment the event number except ljm.LJMError: ljme = sys.exc_info()[1] print(ljme) #xyz.closePorts(handle) except KeyboardInterrupt: # usefull to have a KeyboardInterrupt when your're debugging # save the data to a DataFrame print("saving dataFrame") dataFrame = package_my_data_into_a_dataframe_yay(allTheData) #dataFrame.to_csv("./data/frequencyVsField/testData.csv") # generate timestamp timeStamp1 = time.strftime('%y-%m-%d~%H-%M-%S') dataFrame.to_csv("./data/Calibrations/freqVsField%s.csv" % timeStamp1) xyz.closePorts(handle) except Exception as e: # helpful to close the ports on except when debugging the code. # it prevents the devices from thinking they are still conected and refusing the new connecton # on the next open ports call. print("saving dataFrame") dataFrame = package_my_data_into_a_dataframe_yay(allTheData) #dataFrame.to_csv("./data/frequencyVsField/testData.csv") # generate timestamp timeStamp1 = time.strftime('%y-%m-%d~%H-%M-%S') dataFrame.to_csv("./data/Calibrations/freqVsField%s.csv" % timeStamp1) xyz.closePorts(handle) print('closed all the ports\n') print(e) # print the exception raise
def generador_Frecuecia(f1, f2, f3, f4, nombre): fs = 20000 # f = 500 ciclo1 = f1 / 400.0000000 ciclo1 = np.ceil(ciclo1) ciclo2 = f2 / 400.0000000 ciclo2 = np.ceil(ciclo2) duration1 = np.float32(ciclo1 / f1) duration2 = np.float32(ciclo2 / f2) samples1 = (np.sin(2 * np.pi * np.arange(fs * duration1) * f1 / fs)).astype(np.float32) samples1 = 2.0 * samples1 + 2.5 samples2 = (np.sin(2 * np.pi * np.arange(fs * duration2) * f2 / fs)).astype(np.float32) samples2 = 2.0 * samples2 + 2.5 #plt.plot(samples) #plt.show() # print(len(samples1)) # MAX_REQUESTS = 1000 # The number of eStreamRead calls that will be performed. # Open first found LabJack # handle = ljm.openS("ANY", "ANY", "ANY") info = ljm.getHandleInfo(handle) print("Opened a LabJack with Device type: %i, Connection type: %i,\n" \ "Serial number: %i, IP address: %s, Port: %i,\nMax bytes per MB: %i" % \ (info[0], info[1], info[2], ljm.numberToIP(info[3]), info[4], info[5])) # Desactivacion de parlantes t0 = time.time() ljm.eWriteName(handle, "FIO1", 0) ljm.eWriteName(handle, "FIO4", 0) ljm.eWriteName(handle, "FIO2", 0) ljm.eWriteName(handle, "FIO0", 0) t1 = time.time() TDes_parlantes = t0 - t1 # Setup Stream Out OUT_NAMES = ["DAC0", "DAC1"] NUM_OUT_CHANNELS = len(OUT_NAMES) outAddress1 = ljm.nameToAddress(OUT_NAMES[0])[0] outAddress2 = ljm.nameToAddress(OUT_NAMES[0])[1] # Allocate memory for the stream-out buffer t0 = time.time() ljm.eWriteName(handle, "STREAM_OUT0_TARGET", 1000) ljm.eWriteName(handle, "STREAM_OUT0_BUFFER_SIZE", 2048) ljm.eWriteName(handle, "STREAM_OUT0_ENABLE", 1) ljm.eWriteName(handle, "STREAM_OUT0_LOOP_SIZE", len(samples1)) ljm.eWriteName(handle, "STREAM_OUT1_TARGET", 1002) ljm.eWriteName(handle, "STREAM_OUT1_BUFFER_SIZE", 2048) ljm.eWriteName(handle, "STREAM_OUT1_ENABLE", 1) ljm.eWriteName(handle, "STREAM_OUT1_LOOP_SIZE", len(samples2)) freq1 = 80000000.000000000000000000 / 32 freq1 = freq1 / f3 ljm.eWriteName(handle, "DIO_EF_CLOCK1_ENABLE", 0) ljm.eWriteName(handle, "DIO_EF_CLOCK1_DIVISOR", 32) ljm.eWriteName(handle, "DIO_EF_CLOCK1_ROLL_VALUE", freq1) ljm.eWriteName(handle, "DIO_EF_CLOCK1_ENABLE", 1) ljm.eWriteName(handle, "DIO3_EF_ENABLE", 0) ljm.eWriteName(handle, "DIO3_EF_INDEX", 0) ljm.eWriteName(handle, "DIO3_EF_OPTIONS", 1) ljm.eWriteName(handle, "DIO3_EF_CONFIG_A", freq1 / 2) ljm.eWriteName(handle, "DIO3_EF_ENABLE", 1) ljm.eWriteName(handle, "DIO_EF_CLOCK1_DIVISOR", 32) ljm.eWriteName(handle, "DIO_EF_CLOCK1_ROLL_VALUE", freq1) ljm.eWriteName(handle, "DIO3_EF_CONFIG_A", freq1 / 2) freq2 = 80000000.000000000000000000 / 32 freq2 = freq2 / f4 ljm.eWriteName(handle, "DIO_EF_CLOCK2_ENABLE", 0) ljm.eWriteName(handle, "DIO_EF_CLOCK2_DIVISOR", 32) ljm.eWriteName(handle, "DIO_EF_CLOCK2_ROLL_VALUE", freq2) ljm.eWriteName(handle, "DIO_EF_CLOCK2_ENABLE", 1) ljm.eWriteName(handle, "DIO5_EF_ENABLE", 0) ljm.eWriteName(handle, "DIO5_EF_INDEX", 0) ljm.eWriteName(handle, "DIO5_EF_OPTIONS", 2) ljm.eWriteName(handle, "DIO5_EF_CONFIG_A", freq2 / 2) ljm.eWriteName(handle, "DIO5_EF_ENABLE", 1) ljm.eWriteName(handle, "DIO_EF_CLOCK2_DIVISOR", 32) ljm.eWriteName(handle, "DIO_EF_CLOCK2_ROLL_VALUE", freq2) ljm.eWriteName(handle, "DIO5_EF_CONFIG_A", freq2 / 2) for i in range(0, len(samples1)): ljm.eWriteName(handle, "STREAM_OUT0_BUFFER_F32", samples1[i]) for i in range(0, len(samples2)): ljm.eWriteName(handle, "STREAM_OUT1_BUFFER_F32", samples2[i]) t1 = time.time() Tallocatememory = t0 - t1 tm.sleep(1) ljm.eWriteName(handle, "STREAM_OUT0_SET_LOOP", 1) ljm.eWriteName(handle, "STREAM_OUT1_SET_LOOP", 1) print("STREAM_OUT0_BUFFER_STATUS = %f" % (ljm.eReadName(handle, "STREAM_OUT0_BUFFER_STATUS"))) print("STREAM_OUT0_BUFFER_STATUS = %f" % (ljm.eReadName(handle, "STREAM_OUT1_BUFFER_STATUS"))) # Stream Configuration aScanListNames = ["AIN2"] # Scan list names to stream numAddresses = len(aScanListNames) aScanList = ljm.namesToAddresses(numAddresses, aScanListNames)[0] scanRate = fs scansPerRead = int(scanRate / 1000) # Datos de Transformada de FFT T = 1.00000 / fs x = np.linspace(0.00, scansPerRead * T, scansPerRead) xf = np.linspace(0.00, 1.00 / (2.00 * T), scansPerRead / 2) # fig, (ax, bx) = plt.subplots(2, 1) # plt.ion() # Add the scan list outputs to the end of the scan list. # STREAM_OUT0 = 4800, STREAM_OUT1 = 4801, etc. aScanList.extend([4800]) # STREAM_OUT0 # If we had more STREAM_OUTs aScanList.extend([4801]) # STREAM_OUT1 # aScanList.extend([4802]) # STREAM_OUT2 # aScanList.extend([4803]) # STREAM_OUT3 try: # Configure the analog inputs' negative channel, range, settling time and # resolution. # Note when streaming, negative channels and ranges can be configured for # individual analog inputs, but the stream has only one settling time and # resolution. aNames = [ "AIN2_NEGATIVE_CH", "AIN_ALL_RANGE", "STREAM_SETTLING_US", "STREAM_RESOLUTION_INDEX" ] aValues = [3, 10.0, 0, 0] # single-ended, +/-10V, 0 (default), # 0 (default) ljm.eWriteNames(handle, len(aNames), aNames, aValues) i = 1 j = 0 print("Empieza") t0 = time.time() scanRate = ljm.eStreamStart(handle, scansPerRead, 3, aScanList, scanRate) while j < 1: i = 1 k = 0 h = 0 print(j) while (k < 1000): k = k + 1 ret = ljm.eStreamRead(handle) # str=tm.time() seleccionador(j) # end=tm.time() while i: # i <= M9A;X_REQUESTS: # for g in range(0,2): ret = ljm.eStreamRead(handle) data = ret[0][0:scansPerRead] # print("Hola") # start2 = datetime.now() yf = ft.fft(data) yf = 2.0 / scansPerRead * np.abs(yf[:scansPerRead // 2]) # print("Hola2") #(peaks, indexes) = octave.findpeaks(yf, 'DoubleSided', 'MinPeakHeight', 0.04, 'MinPeakDistance', 100, 'MinPeakWidth', 0) # indexes = find_peaks_cwt(yf, np.arange(1, 2)) indexes = peakutils.indexes(yf, thres=0.01 / max(yf), min_dist=100) print(indexes) i = silenciador(j, indexes) h = h + 1 # end2 = datetime() # end = datetime.now # plt.close() # print("\nTotal scans = %i" % (totScans)) # tt = (end - start).seconds + float((end - start).microseconds) / 1000000 tt = h * 0.001 # tt2= end-str print("Tiempo 1000Hz = %f seconds" % (tt)) # print("Tiempo 500Hz = %f seconds" % (tt2)) ANS[j] = (tt - OFFSET) * MULTIPLICITY j = j + 1 # print("LJM Scan Rate = %f scans/second" % (scanRate)) # print("Timed Scan Rate = %f scans/second" % (totScans / tt)) # print("Timed Sample Rate = %f samples/second" % (totScans * numAddresses / tt)) # print("Skipped scans = %0.0f" % (totSkip / numAddresses)) except ljm.LJMError: ljme = sys.exc_info()[1] print(ljme) except Exception: e = sys.exc_info()[1] print(e) t1 = time.time() TstreamStart = t0 - t1 ljm.eWriteName(handle, "FIO1", 0) ljm.eWriteName(handle, "FIO4", 0) ljm.eWriteName(handle, "FIO2", 0) ljm.eWriteName(handle, "FIO0", 0) h = 1 for dato in ANS: print("Distancia %i : %f" % (h, dato)) h = h + 1 print("\nStop Stream") ljm.eStreamStop(handle) # Close handle ljm.close(handle) print("Termino")
try: # When streaming, negative channels and ranges can be configured for # individual analog inputs, but the stream has only one settling time and # resolution. if deviceType == ljm.constants.dtT4: # T4 configuration # Configure the channels to analog input or digital I/O. # Update all digital I/O channels. b1 = Ignored. b0 = Affected. dioInhibit = 0x00000 # b00000000000000000000 # Set AIN0-AIN3 and AIN FIRST_AIN_CHANNEL to # FIRST_AIN_CHANNEL+NUMBER_OF_AINS-1 as analog inputs (b1), the rest as # digital I/O (b0). dioAnalogEnable = (( (2**NUMBER_OF_AINS) - 1) << FIRST_AIN_CHANNEL) | 0xF ljm.eWriteNames(handle, 2, ["DIO_INHIBIT", "DIO_ANALOG_ENABLE"], [dioInhibit, dioAnalogEnable]) # Configure the analog input ranges. rangeAINHV = 10.0 # HV channels range (AIN0-AIN3) rangeAINLV = 2.5 # LV channels range (AIN4+) aNames = [ "AIN%i_RANGE" % i for i in range(FIRST_AIN_CHANNEL, FIRST_AIN_CHANNEL + NUMBER_OF_AINS) ] aValues = [ rangeAINHV if i < 4 else rangeAINLV for i in range(FIRST_AIN_CHANNEL, FIRST_AIN_CHANNEL + NUMBER_OF_AINS) ] ljm.eWriteNames(handle, len(aNames), aNames, aValues)
def configureT7(self): with open('darkstar_t7.json', 'r') as f: config_data = f.read() config_dict = json.loads(config_data.decode('utf-8'), object_pairs_hook=OrderedDict) for sensor in config_dict['Analog Sensors']: self.analog_sensors[sensor['Name']] = AnalogLJSensor( sensor['Name'], sensor['PChannel'], sensor['NChannel'], sensor['range'], sensor['slope'], sensor['intercept'], sensor['ef_index']) for sensor in config_dict['Digital Sensors']: self.digital_sensors[sensor['Name']] = DigitalLJSensor( sensor['Name'], sensor['Address']) self.t7handle = ljm.openS("T7", "ANY", "ANY") info = ljm.getHandleInfo(self.t7handle) print( "Opened a LabJack with Device type: %i, Connection type: %i,\n" "Serial number: %i, IP address: %s, Port: %i,\nMax bytes per MB: %i" % (info[0], info[1], info[2], ljm.numberToIP( info[3]), info[4], info[5])) # Stream Configuration # for sensorName, sensor in self.analog_sensors.items(): # if sensor is not None: # self.t7readList.append(int(sensor.getPositiveChannel())) # self.channelNames.append(str(sensor.getName())) # print(int(sensor.getPositiveChannel())) # print(str(sensor.getName())) # print "T7 Read list" , self.t7readList aWriteNames = [] aWriteValues = [] # print(type(analog_sensors)) # Stream Configuration for sensor in self.analog_sensors: pChannel = str(self.analog_sensors[sensor].getPositiveChannel()) nChannel = int(self.analog_sensors[sensor].getNegativeChannel()) if (nChannel > 0): print("configuring negative channel") aWriteNames.append("AIN" + pChannel + "_NEGATIVE_CH") aWriteValues.append(nChannel) if (int(self.analog_sensors[sensor].getExtendedFeatures()) > 0): aWriteNames.append("AIN" + pChannel + "_EF_INDEX") aWriteValues.append( int(self.analog_sensors[sensor].getExtendedFeatures())) print "Names written", aWriteNames print "Values written", aWriteValues ljm.eWriteNames(self.t7handle, len(aWriteNames), aWriteNames, aWriteValues) results = ljm.eReadNames(self.t7handle, len(aWriteNames), aWriteNames) print("\neReadNames results: ") for i in range(len(aWriteNames)): print(" Name - %s, value : %d" % (aWriteNames[i], results[i])) self.t7readListNames = [] self.t7channelNames = [] # Read Configuration for sensorName, sensor in self.analog_sensors.items(): if sensor is not None: self.t7channelNames.append(str(sensor.getName())) if (int(sensor.getExtendedFeatures()) > 0): self.t7readListNames.append( "AIN" + str(sensor.getPositiveChannel()) + "_EF_READ_A") else: self.t7readListNames.append( "AIN" + str(sensor.getPositiveChannel()))
# Analog output settings writeDACs = False if numAIN > 0: # Configure analog input settings numFrames = 0 names = [] aValues = [] for i in range(numAIN): numFrames += 2 names.append("AIN%i_RANGE"%i) aValues.append(rangeAIN) names.append("AIN%i_RESOLUTION_INDEX"%i) aValues.append(resolutionAIN) ljm.eWriteNames(handle, numFrames, names, aValues) # Initialize and configure eNames parameters for loop's eNames call numFrames = 0 names = [] aWrites = [] aNumValues = [] aValues = [] # Add analog input reads (AIN 0 to numAIN-1) for i in range(numAIN): numFrames += 1 names.append("AIN%i"%i) aWrites.append(ljm.constants.READ) aNumValues.append(1) aValues.append(0)
#handle = ljm.open(ljm.constants.dtANY, ljm.constants.ctANY, "ANY") # Any device, Any connection, Any identifier info = ljm.getHandleInfo(handle) print("Opened a LabJack with Device type: %i, Connection type: %i,\n" "Serial number: %i, IP address: %s, Port: %i,\nMax bytes per MB: %i" % (info[0], info[1], info[2], ljm.numberToIP(info[3]), info[4], info[5])) # Setup and call eWriteNames to set the ethernet configuration on the LabJack. numFrames = 4 names = [ "ETHERNET_IP_DEFAULT", "ETHERNET_SUBNET_DEFAULT", "ETHERNET_GATEWAY_DEFAULT", "ETHERNET_DHCP_ENABLE_DEFAULT" ] values = [ ljm.ipToNumber("192.168.1.207"), ljm.ipToNumber("255.255.255.0"), ljm.ipToNumber("192.168.1.1"), 1 ] ljm.eWriteNames(handle, numFrames, names, values) print("\nSet ethernet configuration:") for i in range(numFrames): if names[i] == "ETHERNET_DHCP_ENABLE_DEFAULT": print(" %s : %.0f" % (names[i], values[i])) else: print(" %s : %.0f - %s" % (names[i], values[i], ljm.numberToIP(int(values[i])))) # Close handle ljm.close(handle)
# LabJack T7 and other devices configuration # AIN0 and AIN1: # Negative channel = single ended (199) # Range: +/-10.0 V (10.0) # Resolution index = Default (0) # Settling, in microseconds = Auto (0) names = [ "AIN0_NEGATIVE_CH", "AIN0_RANGE", "AIN0_RESOLUTION_INDEX", "AIN0_SETTLING_US" ] aValues = [199, 10, 1, 0] numFrames = len(names) ljm.eWriteNames(handle, numFrames, names, aValues) print("\nSet configuration:") for i in range(numFrames): print(" %s : %f" % (names[i], aValues[i])) # Read AIN0 and AIN1 from the LabJack with eReadNames in a loop. read_names = ["AIN0"] num_read_frames = len(read_names) print("\nStarting %s read loops.%s\n" % (str(loopAmount), loopMessage)) interval_handle = 1 ljm.startInterval(interval_handle, 100000) # Delay between readings (in microseconds) dac_out = 0
def write(self,names,values): if not len(names)==len(values): print("parameters length do not match") numFrames = len(names) ljm.eWriteNames(self.handle, numFrames, names, values)
ljm.eWriteName(handle, "STREAM_TRIGGER_INDEX", 0) # Enabling internally-clocked stream. ljm.eWriteName(handle, "STREAM_CLOCK_SOURCE", 0) # All negative channels are single-ended, AIN0 and AIN1 ranges are # +/-10 V, stream settling is 0 (default) and stream resolution index # is 0 (default). aNames = ["AIN_ALL_NEGATIVE_CH", "AIN0_RANGE", "AIN1_RANGE", "STREAM_SETTLING_US", "STREAM_RESOLUTION_INDEX"] aValues = [ljm.constants.GND, 10.0, 10.0, 0, 0] # Write the analog inputs' negative channels, ranges, stream settling time # and stream resolution configuration. numFrames = len(aNames) ljm.eWriteNames(handle, numFrames, aNames, aValues) configure_device_for_triggered_stream(handle, TRIGGER_NAME) configure_ljm_for_triggered_stream() # Configure and start stream scanRate = ljm.eStreamStart(handle, scansPerRead, numAddresses, aScanList, scanRate) print("\nStream started with a scan rate of %0.0f Hz." % scanRate) print("\nPerforming %i stream reads." % MAX_REQUESTS) start = datetime.now() totScans = 0 totSkip = 0 # Total skipped samples i = 1 ljmScanBacklog = 0
clockValues = [1, time2clock(tot_time), 1] aNames = ["DIO0_EF_INDEX", "DIO0_EF_VALUE_A","DIO0_EF_ENABLE"] aValues = [0, time2clock(mot_time), 1] # Configure the PWM output and counter. ch1 bNames = [ "DIO2_EF_INDEX","DIO2", "DIO2_EF_OPTIONS", "DIO2_EF_VALUE_A","DIO2_EF_VALUE_B", "DIO2_EF_ENABLE", ] bValues = [1,0,0,time2clock(exp_off), time2clock(exp_on),1] numFrames = len(aNames+clockNames+bNames) results = ljm.eWriteNames(handle, numFrames, clockNames+aNames+bNames, clockValues+aValues+bValues) time.sleep(10000) # Turn off PWM output and counter aNames = ["DIO_EF_CLOCK0_ENABLE", "DIO0_EF_ENABLE"] aValues = [0, 0] numFrames = len(aNames) results = ljm.eWriteNames(handle, numFrames, aNames, aValues)