if '?' in cmd: instr.query(cmd) else: instr.write(cmd) error = instr.query('SYST:ERR?') outStr = f'{error.strip()} {cmd.strip()}' logging.info(outStr) except pyvisa.VisaIOError: error = 'SCPI TIMEOUT' + instr.query('SYST:ERR?') outStr = f'{error.strip()} {cmd.strip()}' logging.error(outStr) ############################################################################### ### Main Code ############################################################################### rm = pyvisa.ResourceManager() #Create Resource Manager instr = rm.open_resource(f'TCPIP0::{host}::hislip0::INSTR') #Create Visa Obj instr.timeout = 5000 #Timeout, millisec # logger = logging.getLogger(__name__) # logger.setLevel(logging.DEBUG) # file_handler = logging.FileHandler(os.path.splitext(__file__)[0] + '.log') # formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') # file_handler.setFormatter(formatter) # logger.addHandler(file_handler) logging.basicConfig(level=logging.DEBUG, \ filename=os.path.splitext(__file__)[0] + '.log', filemode='w', \ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') arry = readSCPI() sendSCPI(arry) # getSysInfo()
def X8060_strip_path(programNumber, laserpath, iteration): pathDict = { '2x7 12x8': [ 19515, 81720, 31920, 19515, 104655, 31920, 19515, 97690, 31920, 19515, 120625, 31920, 30405, 81720, 31920, 30405, 104655, 31920, 30405, 97690, 31920, 30405, 120625, 31920 ], '3x4 1x4': [ 15840, 91000, 31920, 15840, 113935, 31920, 26730, 91000, 31920, 26730, 113935, 31920, 37620, 91000, 31920, 37620, 113935, 31920, 48510, 91000, 31920, 48510, 113935, 31920 ] } LJX8060 = serial.Serial(port='COM7', baudrate=115200, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout=0.5, xonxoff=False, rtscts=False, write_timeout=None, dsrdtr=False, inter_byte_timeout=None, exclusive=None) print(LJX8060.name) LJX8060.write(b'R0\r') #Switch to communication mode response = LJX8060.read(12) print(response) LJX8060.write(b'PW,1,' + programNumber + b'\r') #Switch to BCH Program response = LJX8060.read(12) print(response) LJX8060.write(b'TE,1\r') #Switch to communication mode response = LJX8060.read(12) print(response) rm = visa.ResourceManager() TTA = rm.open_resource('COM4') Servo_on(TTA) if iteration == 1: Home(TTA) time.sleep(1) if laserpath == '2x7 12x8': if iteration > 1 and iteration < 8: for t in range(0, 24, 3): pathDict[laserpath][t] = pathDict[laserpath][t] + 26000 * ( iteration - 1) if iteration > 7: for t in range(0, 24, 3): pathDict[laserpath][t] = pathDict[laserpath][t] + 26000 * ( iteration - 8) for t in range(1, 24, 3): pathDict[laserpath][t] = pathDict[laserpath][t] - 36300 if laserpath == '3x4 1x4': if iteration > 1 and iteration < 5: for t in range(0, 24, 3): pathDict[laserpath][t] = pathDict[laserpath][t] + 47000 * ( iteration - 1) if iteration > 4 and iteration < 9: for t in range(0, 24, 3): pathDict[laserpath][t] = pathDict[laserpath][t] + 47000 * ( iteration - 5) for t in range(1, 24, 3): pathDict[laserpath][t] = pathDict[laserpath][t] - 20700 if iteration > 8: for t in range(0, 24, 3): pathDict[laserpath][t] = pathDict[laserpath][t] + 47000 * ( iteration - 9) for t in range(1, 24, 3): pathDict[laserpath][t] = pathDict[laserpath][t] - 20700 * 2 acc = 20 dcl = 20 delay = 0.1 for i in range(0, len(pathDict[laserpath]), 6): vel = 150 ###### Move_XYZ(TTA, acc, dcl, vel, pathDict[laserpath][i], pathDict[laserpath][i + 1], pathDict[laserpath][i + 2], delay) vel = 19 LJX8060.write(b'T1\r') #Switch to communication mode Move_XYZ(TTA, acc, dcl, vel, pathDict[laserpath][i + 3], pathDict[laserpath][i + 4], pathDict[laserpath][i + 5], delay) if laserpath == '2x7 12x8': if iteration == 14: vel = 150 Move_XYZ(TTA, acc, dcl, vel, 10, 10, 10, delay) Home(TTA) if laserpath == '3x4 1x4': if iteration == 12: vel = 150 Move_XYZ(TTA, acc, dcl, vel, 10, 10, 10, delay) Home(TTA) time.sleep(0.8) rm.close() LJX8060.close()
def __init__(self): super().__init__() self._piezo = None self._VISA_rm = pyvisa.ResourceManager() self.com_ports = self.get_ressources()
import pyvisa #### ============================================================================= #### Input Parameters #### ============================================================================= ### leave all values as strings ### e3 for kHz, e6 for MHz ff_ip = '10.169.7.49' ###IP address ff_cf = '10e6' ### center frequency ff_span = '10e6' ### span ff_res = '300e3' ### resolution bandwidth manual setting ff_vbw = '100e3' ### video bandwidth #### ============================================================================= #### Transmit commands to the Field Fox #### ============================================================================= ### opens connection to field fox and enters parameters from above ffsa = pyvisa.ResourceManager() SA = ffsa.open_resource('TCPIP0::' + ff_ip + '::inst0::INSTR') SA.timeout = 5000 SA.write('FREQuency:CENTer ' + ff_cf) SA.write('FREQ:SPAN ' + ff_span) SA.write('BAND ' + ff_res) SA.write('BAND:VID ' + ff_vbw) ### closes connection to field fox at completion of program SA.close() ffsa.close()
#!/usr/bin/env python import pyvisa as visa import time delay = 0.01 #delay in seconds (50 ms) rm = visa.ResourceManager('@py') #WF = rm.open_resource('USB0::0xF4ED::0xEE3A::SDG00003140724::INSTR') WF = rm.open_resource('TCPIP::192.168.9.12::INSTR') def toggleOutput(chan, state): cmd1 = 'C%s:OUTP %s' % (chan, state) WF.write(cmd1) time.sleep(1) def sine(chan, amp, freq): if (amp > 5): print('ERR (amp too large)') else: cmd1 = 'C%s:BSWV WVTP,SINE,AMP,%s,FRQ,%s' % (chan, amp, freq) WF.write(cmd1) time.sleep(delay)
def __init__(self, address='TCPIP::192.168.0.3::INSTR', **kwargs): import pyvisa as v rm = v.ResourceManager() self.inst = rm.get_instrument(address) Driver.__init__(self, **kwargs)
def Sweep(): # Read samples and store the data into the arrays global X0L # Left top X value global Y0T # Left top Y value global GRW # Screenwidth global GRH # Screenheight global SIGNAL1 global RUNstatus global SWEEPsingle global SMPfftlist global SMPfftindex global SAMPLErate global SAMPLEsize global SAMPLEdepth global UPDATEspeed global STARTfrequency global STOPfrequency global COLORred global COLORcanvas global COLORyellow global COLORgreen global COLORmagenta global scope while (True): # Main loop # RUNstatus = 1 : Open Stream if (RUNstatus == 1): if UPDATEspeed < 1: UPDATEspeed = 1.0 TRACESopened = 1 try: # Get the USB device, e.g. 'USB0::0x1AB1::0x0588::DS1ED141904883' # pyVisa 1.6 compatibilty # instruments = visa.get_instruments_list() rm = pyvisa.ResourceManager('@py') instruments = rm.list_resources() for index, content in enumerate(instruments): if (instruments[index].find('USB') != -1): inst_index = index #if len(usb) != 1: # print('Bad instrument list', instruments) # sys.exit(-1) #print(usb) # pyVisa 1.6 compatibilty #instr = usb[0] # instr = 'TCPIP0::10.96.0.240::INSTR' scope = rm.open_resource(instruments[inst_index], timeout=100000, chunk_size=1024000) sleep(0.2) scope.write(":RUN") scope.write(":WAV:SOUR CHAN1") scope.write(":WAV:FORM BYTE") scope.write(":WAV:MODE RAW") sleep(0.2) if SAMPLEdepth == 0: print('NORM') scope.write(':ACQ:MDEP 120000') # normal memory type else: print('LONG') scope.write(':ACQ:MDEP ' + str(longSweepMdep(channelsEnabled(scope)))) # long memory type sleep(0.5) print ('mem depth'+ scope.query(':ACQ:MDEP?')) RUNstatus = 2 except: # If error in opening audio stream, show error RUNstatus = 0 #txt = "Sample rate: " + str(SAMPLErate) + ", try a lower sample rate.\nOr another audio device." showerror("VISA Error","Cannot open scope") # get metadata # sample_rate = float(scope.query(':ACQ:SRAT?')) # timescale = float(scope.query(":TIM:SCAL?")) # timeoffset = float(scope.query(":TIM:OFFS?")) # voltscale = float(scope.query(':CHAN1:SCAL?')) # voltoffset = float(scope.query(":CHAN1:OFFS?")) # scope.write(":ACQ:MDEP 12000000") # scope.write(":WAV:SOUR CHAN1") # scope.write(":WAV:FORM BYTE") # scope.write(":WAV:MODE RAW") UpdateScreen() # UpdateScreen() call # RUNstatus = 2: Reading audio data from soundcard if (RUNstatus == 2): # Grab the raw data from channel 1 #try: # Set the scope the way we want it #scope.write(':CHAN1:COUP DC') # DC coupling #scope.write(':CHAN1:DISP ON') # Channel 1 on #scope.write(':CHAN2:DISP ON') # Channel 2 off #scope.write(':CHAN1:SCAL 1') # Channel 1 vertical scale 1 volts #scope.write(':CHAN1:OFFS -2') # Channel 1 vertical offset 2 volts #scope.write(':TIM:SCAL 0.001') # time interval #scope.write(':TIM:OFFS .05') # Offset time 50 ms #scope.write(':TRIG:EDGE:SOUR CHAN1') # Edge-trigger from channel 1 #scope.write(':TRIG:EDGE:SWE SING') # Single trigger #scope.write(':TRIG:EDGE:COUP AC') # trigger coupling #scope.write(':TRIG:EDGE:SLOP NEG') # Trigger on negative edge #scope.write(':TRIG:EDGE:LEV 0.01') # Trigger volts # sleep(0.1) # print ('mem depth: ', scope.query(':ACQ:MDEP?')) # scope.write(":TRIG:SWE SING") # scope.write(":SINGLE") #txt = "Trig" #x = X0L + 250 #y = Y0T+GRH+32 #IDtxt = ca.create_text (x, y, text=txt, anchor=W, fill=COLORyellow) #root.update() # update screen # while True: # trigStat = scope.query(':TRIG:STAT?').strip() # if 'STOP' == trigStat: # break # sleep(0.1) #sleep(0.1) # Grab the raw data from channel 1, which will take a few seconds for long buffer mode sleep(0.1) txt = "->Acquire" x = X0L + 275 y = Y0T+GRH+32 IDtxt = ca.create_text (x, y, text=txt, anchor=W, fill=COLORgreen) root.update() # update screen scope.write(":STOP") memdepth = int(scope.query(':ACQ:MDEP?')) l2md = int(math.log(memdepth,2)) # truncate the logarithm samplelength = (1<<l2md) +1 # print ('mem depth'+ str(memdepth)) # print ('needed sample length'+ str(samplelength)) tbeg = time.time(); signals = getWavData(scope, samplelength) tend = time.time(); print ("acquisition:" + str (tend - tbeg)) data_size = len(signals) SAMPLErate = float(scope.query(':ACQ:SRAT?')) #do this second # print 'Data size:', data_size , "Sample rate:", SAMPLErate scope.write(":RUN") SIGNAL = signals # convert data from (inverted) bytes to an array of scaled floats # this magic from Matthew Mets # tbeg = time.time(); # print signals signals = numpy.multiply(signals,-1) # print signals signals = numpy.add(signals,255) # print signals signals = numpy.subtract(signals,130) # print signals signals = numpy.divide(signals,127.0) # print signals # tend = time.time(); SIGNAL1 = signals # print ("numpy scaling:" + str (tend - tbeg)) UpdateAll() # Update Data, trace and screen if SWEEPsingle == True: # single sweep mode, sweep once then stop SWEEPsingle = False RUNstatus = 3 # RUNstatus = 3: Stop # RUNstatus = 4: Stop and restart if ((RUNstatus == 3) or (RUNstatus == 4)) and (scope != None) : scope.write(":RUN") # not for DS1054Z # scope.write(":KEY:FOR") scope.close() scope = None print (" scope closed") if RUNstatus == 3: RUNstatus = 0 # Status is stopped if RUNstatus == 4: RUNstatus = 1 # Status is (re)start UpdateScreen() # UpdateScreen() call # Update tasks and screens by TKinter root.update_idletasks() root.update() # update screens
def worker(self): while True: task = self.taskq.get() self.log_msg( f"New task: {task['cmd']} (queue size = {self.taskq.unfinished_tasks})", lvl=logging.DEBUG) # handle pcb and stage virtualization stage_pcb_class = pcb pcb_class = pcb if 'stage_virt' in task: if task['stage_virt'] == True: stage_pcb_class = virt.pcb if 'pcb_virt' in task: if task['pcb_virt'] == True: pcb_class = virt.pcb try: # attempt to do the task if task['cmd'] == 'home': with stage_pcb_class(task['pcb'], timeout=1) as p: mo = motion(address=task['stage_uri'], pcb_object=p) mo.connect() mo.home() self.log_msg('Homing procedure complete.', lvl=logging.INFO) self.send_pos(mo) del (mo) # send the stage some place elif task['cmd'] == 'goto': with stage_pcb_class(task['pcb'], timeout=1) as p: mo = motion(address=task['stage_uri'], pcb_object=p) mo.connect() mo.goto(task['pos']) self.send_pos(mo) del (mo) # handle any generic PCB command that has an empty return on success elif task['cmd'] == 'for_pcb': with pcb_class(task['pcb'], timeout=1) as p: # special case for pixel selection to avoid parallel connections if (task['pcb_cmd'].startswith('s') and ('stream' not in task['pcb_cmd']) and (len(task['pcb_cmd']) != 1)): p.query('s') # deselect all before selecting one result = p.query(task['pcb_cmd']) if result == '': self.log_msg( f"Command acknowledged: {task['pcb_cmd']}", lvl=logging.DEBUG) else: self.log_msg( f"Command {task['pcb_cmd']} not acknowleged with {result}", lvl=logging.WARNING) # get the stage location elif task['cmd'] == 'read_stage': with stage_pcb_class(task['pcb'], timeout=1) as p: mo = motion(address=task['stage_uri'], pcb_object=p) mo.connect() self.send_pos(mo) del (mo) # zero the mono elif task['cmd'] == 'mono_zero': if task['mono_virt'] == True: self.log_msg("0 GOTO virtually worked!", lvl=logging.INFO) self.log_msg("1 FILTER virtually worked!", lvl=logging.INFO) else: with serial.Serial(task['mono_address'], 9600, timeout=1) as mono: mono.write("0 GOTO") self.log_msg(mono.readline.strip(), lvl=logging.INFO) mono.write("1 FILTER") self.log_msg(mono.readline.strip(), lvl=logging.INFO) elif task['cmd'] == 'spec': if task['le_virt'] == True: le = virt.illumination( address=task['le_address'], default_recipe=task['le_recipe']) else: le = illumination(address=task['le_address'], default_recipe=task['le_recipe'], connection_timeout=1) con_res = le.connect() if con_res == 0: response = {} int_res = le.set_intensity(task['le_recipe_int']) if int_res == 0: response["data"] = le.get_spectrum() response["timestamp"] = time.time() output = { 'destination': 'calibration/spectrum', 'payload': pickle.dumps(response) } self.outputq.put(output) else: self.log_msg( f'Unable to set light engine intensity.', lvl=logging.INFO) else: self.log_msg(f'Unable to connect to light engine.', lvl=logging.INFO) del (le) # device round robin commands elif task['cmd'] == 'round_robin': if len(task['slots']) > 0: with pcb_class(task['pcb'], timeout=1) as p: p.query( 'iv' ) # make sure the circuit is in I-V mode (not eqe) p.query( 's' ) # make sure we're starting with nothing selected if task['smu_virt'] == True: smu = virt.k2400 else: smu = sm k = smu(addressString=task['smu_address'], terminator=task['smu_le'], serialBaud=task['smu_baud'], front=False) # set up sourcemeter for the task if task['type'] == 'current': pass # TODO: smu measure current command goes here elif task['type'] == 'rtd': k.setupDC(auto_ohms=True) elif task['type'] == 'connectivity': self.log_msg( f'Checking connections. Only failures will be printed.', lvl=logging.INFO) k.set_ccheck_mode(True) for i, slot in enumerate(task['slots']): dev = task['pads'][i] mux_string = task['mux_strings'][i] p.query(mux_string) # select the device if task['type'] == 'current': pass # TODO: smu measure current command goes here elif task['type'] == 'rtd': m = k.measure()[0] ohm = m[2] if (ohm < 3000) and (ohm > 500): self.log_msg( f'{slot} -- {dev} Could be a PT1000 RTD at {self.rtd_r_to_t(ohm):.1f} °C', lvl=logging.INFO) elif task['type'] == 'connectivity': if k.contact_check() == False: self.log_msg( f'{slot} -- {dev} appears disconnected.', lvl=logging.INFO) p.query(f"s{slot}0") # disconnect the slot if task['type'] == 'connectivity': k.set_ccheck_mode(False) self.log_msg(f'Contact check complete.', lvl=logging.INFO) elif task['type'] == 'rtd': self.log_msg( f'Temperature measurement complete.', lvl=logging.INFO) k.setupDC(sourceVoltage=False) p.query("s") del (k) except Exception as e: self.log_msg(e, lvl=logging.WARNING) logging.exception(e) try: del (le) # ensure le is cleaned up except: pass try: del (mo) # ensure mo is cleaned up except: pass try: del (k) # ensure k is cleaned up except: pass # system health check if task['cmd'] == 'check_health': rm = pyvisa.ResourceManager('@py') if 'pcb' in task: self.log_msg(f"Checking controller@{task['pcb']}...", lvl=logging.INFO) try: with pcb_class(task['pcb'], timeout=1) as p: self.log_msg('Controller connection initiated', lvl=logging.INFO) self.log_msg( f"Controller firmware version: {p.firmware_version}", lvl=logging.INFO) self.log_msg(f"Controller axes: {p.detected_axes}", lvl=logging.INFO) self.log_msg( f"Controller muxes: {p.detected_muxes}", lvl=logging.INFO) except Exception as e: emsg = f'Could not talk to control box' self.log_msg(emsg, lvl=logging.WARNING) logging.exception(emsg) if 'psu' in task: self.log_msg(f"Checking power supply@{task['psu']}...", lvl=logging.INFO) if task['psu_virt'] == True: self.log_msg(f'Power supply looks virtually great!', lvl=logging.INFO) else: try: with rm.open_resource(task['psu']) as psu: self.log_msg( 'Power supply connection initiated', lvl=logging.INFO) idn = psu.query("*IDN?") self.log_msg( f'Power supply identification string: {idn.strip()}', lvl=logging.INFO) except Exception as e: emsg = f'Could not talk to PSU' self.log_msg(emsg, lvl=logging.WARNING) logging.exception(emsg) if 'smu_address' in task: self.log_msg( f"Checking sourcemeter@{task['smu_address']}...", lvl=logging.INFO) if task['smu_virt'] == True: self.log_msg(f'Sourcemeter looks virtually great!', lvl=logging.INFO) else: # for sourcemeter open_params = {} open_params['resource_name'] = task['smu_address'] open_params['timeout'] = 300 # ms if 'ASRL' in open_params[ 'resource_name']: # data bits = 8, parity = none open_params['read_termination'] = task[ 'smu_le'] # NOTE: <CR> is "\r" and <LF> is "\n" this is set by the user by interacting with the buttons on the instrument front panel open_params[ 'write_termination'] = "\r" # this is not configuable via the instrument front panel (or in any way I guess) open_params['baud_rate'] = task[ 'smu_baud'] # this is set by the user by interacting with the buttons on the instrument front panel open_params[ 'flow_control'] = pyvisa.constants.VI_ASRL_FLOW_RTS_CTS # user must choose NONE for flow control on the front panel elif 'GPIB' in open_params['resource_name']: open_params['write_termination'] = "\n" open_params['read_termination'] = "\n" # GPIB takes care of EOI, so there is no read_termination open_params[ 'io_protocol'] = pyvisa.constants.VI_HS488 # this must be set by the user by interacting with the buttons on the instrument front panel by choosing 488.1, not scpi elif ('TCPIP' in open_params['resource_name']) and ( 'SOCKET' in open_params['resource_name']): # GPIB <--> Ethernet adapter pass try: with rm.open_resource(**open_params) as smu: self.log_msg( 'Sourcemeter connection initiated', lvl=logging.INFO) idn = smu.query("*IDN?") self.log_msg( f'Sourcemeter identification string: {idn}', lvl=logging.INFO) except Exception as e: emsg = f'Could not talk to sourcemeter' self.log_msg(emsg, lvl=logging.WARNING) logging.exception(emsg) if 'lia_address' in task: self.log_msg(f"Checking lock-in@{task['lia_address']}...", lvl=logging.INFO) if task['lia_virt'] == True: self.log_msg(f'Lock-in looks virtually great!', lvl=logging.INFO) else: try: with rm.open_resource(task['lia_address'], baud_rate=9600) as lia: lia.read_termination = '\r' self.log_msg('Lock-in connection initiated', lvl=logging.INFO) idn = lia.query("*IDN?") self.log_msg( f'Lock-in identification string: {idn.strip()}', lvl=logging.INFO) except Exception as e: emsg = f'Could not talk to lock-in' self.log_msg(emsg, lvl=logging.WARNING) logging.exception(emsg) if 'mono_address' in task: self.log_msg( f"Checking monochromator@{task['mono_address']}...", lvl=logging.INFO) if task['mono_virt'] == True: self.log_msg(f'Monochromator looks virtually great!', lvl=logging.INFO) else: try: with rm.open_resource(task['mono_address'], baud_rate=9600) as mono: self.log_msg( 'Monochromator connection initiated', lvl=logging.INFO) qu = mono.query("?nm") self.log_msg( f'Monochromator wavelength query result: {qu.strip()}', lvl=logging.INFO) except Exception as e: emsg = f'Could not talk to monochromator' self.log_msg(emsg, lvl=logging.WARNING) logging.exception(emsg) if 'le_address' in task: self.log_msg( f"Checking light engine@{task['le_address']}...", lvl=logging.INFO) le = None if task['le_virt'] == True: ill = virt.illumination else: ill = illumination try: le = ill(address=task['le_address'], default_recipe=task['le_recipe'], connection_timeout=1) con_res = le.connect() if con_res == 0: self.log_msg('Light engine connection successful', lvl=logging.INFO) elif (con_res == -1): self.log_msg( "Timeout waiting for wavelabs to connect", lvl=logging.WARNING) else: self.log_msg( f"Unable to connect to light engine and activate {task['le_recipe']} with error {con_res}", lvl=logging.WARNING) except Exception as e: emsg = f'Light engine connection check failed: {e}' self.log_msg(emsg, lvl=logging.WARNING) logging.exception(emsg) try: del (le) except: pass self.taskq.task_done()
def main(verbose=False): circuitpython_drive = find_circuitpython_drive() resource_manager = pyvisa.ResourceManager("@ivi") meter = multimeter.Multimeter(resource_manager) sol = Sol(verbose=verbose) print("Copying calibration script...") copy_calibration_script(circuitpython_drive) time.sleep(3) # Wait a few second for circuitpython to maybe reload. sol.reset() cpu_id = sol.get_cpu_id() print(f"Sol CPU ID: {cpu_id}") channel_calibrations = {} channel_voltages = {} try: for channel in ("a", "b", "c", "d"): print(f"========= Channel {channel} =========") print(f"Connect to channel {channel}...") sol.set_dac(channel, 0) for n in range(100): if meter.read_voltage_fast() < -4.8: break time.sleep(0.1) else: raise RuntimeError("Channel connection failed!") # Sleep another second to account for bouncing time.sleep(1) calibration_values = {} channel_voltages[channel] = {} for step in range(16): dac_code = int((2**16 - 1) * step / 15) sol.set_dac(channel, dac_code) voltage = meter.read_voltage() calibration_values[voltage] = dac_code print(f"DAC code: {dac_code}, Voltage: {voltage}") sol.set_calibration(channel, calibration_values) channel_calibrations[channel] = calibration_values for desired_voltage in range(-5, 9): sol.set_voltage(channel, desired_voltage) measured_voltage = meter.read_voltage() channel_voltages[channel][desired_voltage] = measured_voltage print( f"Desired voltage: {desired_voltage}, Measured voltage: {measured_voltage}" ) calibration_file_contents = generate_calibration_file( channel_calibrations) sol.write_calibration_to_nvm(calibration_file_contents) finally: meter.close() print("========= Stats =========") for channel, voltages in channel_voltages.items(): if not voltages: continue print(f"Channel {channel}:") differences = [ abs(desired - measured) for desired, measured in voltages.items() ] avg = statistics.mean(differences) * 1000 dev = statistics.stdev(differences) * 1000 worst = max(differences) * 1000 best = min(differences) * 1000 print(f"Average: {avg:.3f} mV ({avg / MILIVOLTS_PER_CODE:.0f} lsb)") print(f"Std. dev: {dev:.3f} mV ({dev / MILIVOLTS_PER_CODE:.0f} lsb)") print(f"Worst: {worst:.3f} mV ({worst / MILIVOLTS_PER_CODE:.0f} lsb)") print(f"Best: {best:.3f} mV ({best / MILIVOLTS_PER_CODE:.0f} lsb)") print( f"Saving calibration to calibrations/{cpu_id} and {circuitpython_drive}" ) calibration_file_path = os.path.join("calibrations", f"{cpu_id}.py") with open(calibration_file_path, "w") as fh: fh.write("# This is generated by the factory when assembling your\n") fh.write("# device. Do not remove or change this.\n\n") fh.write(calibration_file_contents) fh.flush() fs.copyfile(calibration_file_path, os.path.join(circuitpython_drive, "calibration.py")) restore_code_py(circuitpython_drive) fs.unmount(circuitpython_drive) print("Done.")
def visaResource(deviceName, searchString=""): import pyvisa as visa global rm global list global resources global inst searchString = searchString.lower() rm = visa.ResourceManager() list = rm.list_resources() # Place the resources into tuple "List" resources = [ ] # Prep for the tuple to be converted "resources" from "list" for i, a in enumerate(list): # Enumerate through the tuple "list" resources.append( a ) # Place the current enumeration into the indexed spot of "resources" if searchString != "": inst = "" x = 0 for index, i in enumerate( resources): # Enumerate through list "resources" currentString = i.lower() tempSearch = currentString.find(searchString) # print("{} - {} - {}".format(i, searchString, tempSearch)) if tempSearch == 0: inst = rm.open_resource(resources[index]) if inst == "": print("Could not find GPIB resource containing: {}".format( searchString)) return "Could not find GPIB resource containing: {}".format( searchString) else: print("Detected VISA resources") print("=========================================================") x = 0 for i in resources: # Enumerate through list "resources" print('Resource ' + str(x) + ': ' + i) # Print each resource contained in list "resources" x += 1 # X is used to itemize and index the list that gets printed print("Resource " + str(x) + ': The GPIB address of my instrument was not auto-detected') print("=========================================================") address = -1 while (address < 0) or (address > (x)): try: address = int( input(" > Enter the resource number of the " + str(deviceName) + " (0 through " + str(x) + "): ")) except ValueError: print("No valid integer entered! Please try again ...") if address < 0 or address > (x): print("Available resources are 0 through " + str(x) + ". Please try again.") if address == x: address = GPIB_User_Entry(deviceName) inst = rm.open_resource(address) del inst.timeout return inst else: inst = rm.open_resource(resources[address]) del inst.timeout return inst return inst
# =============================================================================== # Copyright 2017 ross # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # =============================================================================== from __future__ import absolute_import import pyvisa resource_manager = pyvisa.ResourceManager() # ============= EOF =============================================
autoRange, aperture) def setResistanceMeasurement(self, range=0, autoRange=True, aperture=0.001): self.dev.setMeasureQuantity(MeasureQuantity.Resistance, range, autoRange, aperture) def directMeasure(self, count=1): return self.dev.directMeasure(count) def directMeasureAndFetchLater(self, count=1): return self.dev.directMeasureAndFetchLater(count) if __name__ == '__main__': import pyvisa as visa print(visa.ResourceManager().list_resources()) visaResource = 'TCPIP0::192.168.25.110::inst0::INSTR' dev = KeySight_MultiMeter_34465A(visaResource) wrap = MultiMeterServiceWrap(dev) wrap.setDCCurrentMeasurement(2, True, 0.005) while True: r = wrap.directMeasure(200) npr = np.array(r) print('{}, {}'.format(np.average(npr), np.std(npr)))
# rm.list_resources() #Print resource list # scope = rm.open_resource('USB0::0x0699::0x0363::C061073::INSTR') #Enter the resource to be connected manually 'USB0::0x0699::0x0363::C061073::INSTR'; 'TEKTRONIX,TDS 1002B,C061073,CF:91.1CT FV:v22.11\n' # scope = pylef.TektronixTBS1062() #use the Pylef functions, to handle oscilloscope # scope.start_acquisition() #Start the aquisition of the waveform # scope.ch1.turn_on() #Turn channel on # scope.ch1.set_scale('0.010') #Ch1 10,0mV = 0,010 VOLTS # scope.ch1.set_position(2) #Vertical position for channel 1 must be 2 # scope.ch1.set_probe(1) #Voltage probe must be at 1 # scope.trigger.set_level(-0.020) #Trigger in -20mV # scope.set_horizontal_scale(1 / 1000000) #Oscilloscope SEC/DIV time 1.00 us = 1e-06 # scope.write('HORizontal:MAIn:POSition 0;') #Initial horizontal position 0 default # scope.write('HORizontal:MAIn:POSition 0.00000460;') #Horizontal position with respect to the start of the oscilloscope window # scope.write('DISplay:PERSistence INF') #Infinite persistence # scope.write('TRIGGER:MAIN:EDGE:SLOPE FALL') #Negative slope rm = pyvisa.ResourceManager() # Calling PyVisa library scope = rm.open_resource( 'USB0::0x0699::0x0363::C061073::INSTR') # Connecting via USB Scope_Set_Parameters(oscilloscope=scope) number_of_samples = int( input('\nQual o tamanho da amostra que precisa ser obtida?') ) #number of samples needed to search osc_resolution = 2500 #número de pontos em cada waveform selecionada numberBins = 100 #number of bins to graph #Iniciando a aquisição #========================================================================================================== print(f'\nStarting acquisition... Local time: {ctime(time())} \n' ) # Print da hora local marcada no computador
encoding = 'utf-8' import os import pyvisa as visa # import tkinter from tkinter import * from tkinter import filedialog root = Tk() # uses Tk for file dialog path = os.getcwd() try: # Tested on Linux with pyvisa-py and linux-gpib rm = visa.ResourceManager('@py') # nd with NI-VISA under windows 7 except: rm = visa.ResourceManager() i = 0 adr = input('Enter HP 437B GPIB address: ') # dialog for 437B GPIB address HP437B = rm.open_resource('GPIB0::%s::INSTR' % adr) sensor = input('Enter sensor table number to update: ' ) # dialog to input what table to write to try: HP437B.write('SE%sEN' % sensor) # Read selected sensor ID data = HP437B.query('OD') except: print("Error communicating with: %s\n" % HP437B) # exit with error if no communication with 437B exit()
# -*- coding: utf-8 -*- """ Created on Fri Jan 31 11:23:50 2020 @author: P. M. Harrington """ import numpy as np import pyvisa import matplotlib.pyplot as plt import time address = "GPIB0::24::INSTR" rm = pyvisa.ResourceManager() inst = pyvisa.ResourceManager().open_resource(address) #inst.write(":SYST:BEEP:STAT OFF") def set_current(set_value_mA, step_size_mA=0.001): value_stop = 1e-3*set_value_mA value_start = measure_current() #np.round(measure_current(), 3+2) num_steps = int(np.ceil(abs((value_stop-value_start)/(1e-3*step_size_mA)))) value_sweep = np.linspace(value_start, value_stop, num_steps) # for v in value_sweep: str_cmd = "SOUR:FUNC CURR;:SOUR:CURR "+"{}".format(v)+";:VOLT:PROT 0.100000;" inst.write(str_cmd) mA_start = 1e3*value_start mA_end = 1e3*measure_current()
def readingwriting(timeint, countmax, newstdin, continuous, datalist, flag, a, b, c): # -- SERIAL CONNECTION -- #ser1 = serial.Serial( # port = "/dev/tty.usbserial-FTYNZXW4", # baudrate = 19200, # parity = serial.PARITY_NONE, # stopbits = serial.STOPBITS_ONE, # bytesize = serial.EIGHTBITS, # xonxoff=True, # timeout=1 #) # -- GPIB CONNECTION -- rm = visa.ResourceManager() multimeter = rm.open_resource("GPIB0::11::INSTR") # Function that is executed in the first thread. But only if the continuous variable is set to "n" at the beginning in the main process. # This function (thread) runs forever except the flag is set. Since the size of the storage array is fixed, the oldest data points # are going to be deleted. def recordingresistance1(timeint, countmax, multimeter, datalist, a, b, c): count = 0 starttime1 = time.time() timearray = np.zeros(countmax, dtype="float") resistancearray = np.zeros(countmax, dtype="float") temperaturearray = np.zeros(countmax, dtype="float") timestamparray = np.zeros(countmax, dtype="float") while True: if (flag.value == 0): starttime2 = time.time() #ser.write(":FETC?\r\n") #resis = ser.readline() #print resis[1:len(resis)-3] resis = multimeter.query(":FETC?") try: #resis = float(resis[1:len(resis)-3]) resis = float(resis) if (resis > 1e10): resis = np.nan except: print "\n - Wrong readout: ", resis resis = np.nan if (count < countmax): timearray[count] = time.time() - starttime1 resistancearray[count] = resis temperaturearray[count] = f(resis, a, b, c) timestamparray[count] = starttime2 count += 1 else: timearray = np.roll(timearray, len(timearray) - 1) resistancearray = np.roll(resistancearray, len(resistancearray) - 1) temperaturearray = np.roll(temperaturearray, len(temperaturearray) - 1) timestamparray = np.roll(timestamparray, len(timestamparray) - 1) timearray[countmax - 1] = time.time() - starttime1 resistancearray[countmax - 1] = resis temperaturearray[contmax - 1] = f(resis, a, b, c) timestamparray[countmax - 1] = starttime2 datalist.append([ timearray, resistancearray, temperaturearray, timestamparray ]) if (count >= 3): del datalist[0] try: time.sleep(timeint - time.time() + starttime2) except: time.sleep(2 * timeint - time.time() + starttime2) else: break # Function that is executed in the first thread. But only if the continuous variable is set to "y" at the beginning in the main process. # This function (thread) stops when the storage array is completely filled. No data points are going to be deleted. # This function (thread) can also be stopped by entering "exit". def recordingresistance2(timeint, countmax, multimeter, datalist, a, b, c): count = 0 starttime1 = time.time() timearray = np.zeros(countmax, dtype="float") resistancearray = np.zeros(countmax, dtype="float") temperaturearray = np.zeros(countmax, dtype="float") timestamparray = np.zeros(countmax, dtype="float") while True: if (flag.value == 0): starttime2 = time.time() #ser.write(":FETC?\r\n") #resis = ser.readline() #print resis[1:len(resis)-3] resis = multimeter.query(":FETC?") try: #resis = float(resis[1:len(resis)-3]) resis = float(resis) if (resis > 1e10): resis = np.nan except: print "\n - Wrong readout: ", resis resis = np.nan if (count < countmax): timearray[count] = time.time() - starttime1 resistancearray[count] = resis temperaturearray[count] = f(resis, a, b, c) timestamparray[count] = starttime2 count += 1 else: flag.value = 1 break datalist.append([ timearray, resistancearray, temperaturearray, timestamparray ]) if (count >= 3): del datalist[0] try: time.sleep(timeint - time.time() + starttime2) except: time.sleep(2 * timeint - time.time() + starttime2) else: break # Function that is executed in the second thread. THe function waits for user input. One can either enter a new set temperature or the exit # command. def exitfunction(newstdin): newstdinfile = os.fdopen(os.dup(newstdin)) while True: print(" - End acquisition with \"exit\": "), exit_checkout = newstdinfile.readline() exit_checkout = exit_checkout[:len(exit_checkout) - 1] if (exit_checkout == "exit"): flag.value = 1 newstdinfile.close() break else: continue # -- ACTUAL CHILD PROCESS -- # Start both actions in tow different threads: if (continuous == "n"): thread1 = threading.Thread(target=recordingresistance1, args=(timeint, countmax, multimeter, datalist, a, b, c)) thread2 = threading.Thread(target=exitfunction, args=(newstdin, )) thread1.start() thread2.start() thread1.join() thread2.join() else: thread1 = threading.Thread(target=recordingresistance2, args=(timeint, countmax, multimeter, datalist, a, b, c)) thread2 = threading.Thread(target=exitfunction, args=(newstdin, )) thread2.daemon = True thread1.start() thread2.start() thread1.join() #ser1.close() multimeter.close()
import pyvisa as visa # Instrument communication/control import numpy as np # import matplotlib as mtl # # import matplotlib.pyplot as plt # ------------------------------ # # GETTING ACCESS TO THE SMU 2450 # # ------------------------------ # rm = visa.ResourceManager() instAddress = rm.list_resources() # Instruments addresses # IMPORTANT: Alwasy check the address of the instrument to be controlled # In this script, the SMU2450 is on the last address in the list print(instAddress) smuAddress = instAddress[0] # SMU2450 Address print(smuAddress)
def check_system_error(instrument_object): err_chk = instrument_query(instrument_object, "SYST:ERR?") if err_chk.find("NO ERROR") == -1: print(err_chk) time.sleep(0.5) return # ================================================================================ # # MAIN CODE STARTS HERE # # ================================================================================ t1 = time.time() # Start the timer... resource_manager = visa.ResourceManager() # Opens the resource manager # connect to and configure the load dmm2015 = None inst_resource_string = "GPIB0::16::INSTR" #resource_manager, dmm2015 = instrument_connect(resource_manager, dmm2015, inst_resource_string, 20000, 1, 1, 0, # stop_bits=pyconst.StopBits.one, # parity=pyconst.Parity.none, # flow_control=0, # read_terminator="\n") resource_manager, dmm2015 = instrument_connect(resource_manager, dmm2015, inst_resource_string, 20000, 1, 1, 0) print(instrument_query(dmm2015, "*IDN?")) # query is the same as write + read
def __init__(self): self.rm = pyvisa.ResourceManager() self.device_handle = self.rm.open_resource("COM4")
def __init__(self, address): rm = pyvisa.ResourceManager() self.address = address self.device = rm.open_resource(address) self.device.clear() self.id = self.device.query("*IDN?")
def __init__(self, address, **kwargs): """ Initialize a network analyzer object Parameters ---------- address : str a visa resource string, or an ip address kwargs : dict visa_library (str), timeout in milliseconds (int), card_number (int), interface (str) Notes ----- General initialization of a skrf vna object. Defines the class methods that all subclasses should provide, and therefore defines the basic functionality, currently focused on grabbing data more than on controlling the state of the vna Keyword Arguments ----------------- visa_library : str allows pyvisa to use different visa_library backends, including the python-based pyvisa-py. backend which can handle SOCKET and Serial (though not GPIB) connections. It should be possible to use this library without NI-VISA libraries installed if the analyzer is so configured. timeout : int milliseconds interface : str one of "SOCKET", "GPIB" card_number : int for GPIB, default is usually 0 """ rm = kwargs.get("resource_manager", None) if not rm: rm = pyvisa.ResourceManager( visa_library=kwargs.get("visa_library", "")) interface = str(kwargs.get("interface", None)).upper() # GPIB, SOCKET if interface == "GPIB": board = str(kwargs.get("card_number", "")).upper() resource_string = "GPIB{:}::{:}::INSTR".format(board, address) elif interface == "SOCKET": port = str(kwargs.get("port", 5025)) resource_string = "TCPIP0::{:}::{:}::SOCKET".format(address, port) else: resource_string = address self.resource = rm.open_resource( resource_string ) # type: pyvisa.resources.messagebased.MessageBasedResource self.resource.timeout = kwargs.get("timeout", 3000) self.resource.read_termination = "\n" # most queries are terminated with a newline self.resource.write_termination = "\n" if "instr" in resource_string.lower(): self.resource.control_ren(2) # convenience pyvisa functions self.write = self.resource.write self.read = self.resource.read self.query = self.resource.query self.query_values = self.resource.query_values
import GPIB_FUNCS as GPIB #Importing our GPIB communication functions for easier comprehension and use import pyvisa #import GPIB communication module import time #imports time to sleep program temporarily from tkinter import * #importing GUI library import tkinter RM = pyvisa.ResourceManager() #pyVISA device manager print(RM.list_resources()) #Printing out all detected device IDs SG = RM.open_resource( 'GPIB0::10::INSTR') #Opening the Signal generator as an object OS = RM.open_resource( 'GPIB0::16::INSTR') #Opening the oscilloscope as an object running = False # Global flag, used for run status of GUI reset = False # Global flag, used to pause modulation and reset the oscilloscope pulsing = False # Global flag, used to change the modulation parameters for CW to pulsing IF_Channel = 3 #The channel that the error signal is on Trigger_Channel = 4 #The channel which shows the SRF pulse Trigger_Level = 20 / 1000 #mv #The level of the pulse trigger Read_Start_Voltage = True Measurement = 3 #Measurement channel Step_size = 20 #(Hz) Change in frequency with each regulation step Pulse_Step_Size = 10 #(Hz) Change in frequency with each regulation step when pulsing Max_Threshold = 100000 #(Hz) Total amount of frequency change before automatically tripping off program Walk_Threshold = 0.5 #(mV) Deviation from 0 the error signal needs to be before CW regulation kicks in Pulse_Walk_Threshold = 0.5 #(mV) Deviation from 0 the error signal needs before pulsing regulation kicks in Wait_after_step = 0.0400 #Seconds, the time waited after a step is taken, necessary to allow oscope measurements to change Wait_between_reads = 0.0100 #Seconds, currently not used, supplemented by GUI time between reads Interlock_Threshold_mv = 30 #mv, this is the amount of deviation before regulation trips off
def __init__(self, com): '生成串口实例,列出可用端口' self.com = com self.rm = pyvisa.ResourceManager() print(self.rm.list_resources())
def __init__(self): self.rm = pyvisa.ResourceManager() print(self.rm.list_resources()) self.device_handle = self.rm.open_resource( "GPIB0::30::INSTR") # for keithely 2602B
def X8060_XYZ_path(programNumber, laserpath, flowplate): if (flowplate == True): pathDict = { '8by12 Bottom Stack': [ 121000, 25300, 17610, 121000, 46360, 17610, 121000, 41260, 17610, 121000, 64360, 17610, 131590, 25300, 17610, 131590, 46360, 17610, 131590, 41260, 17610, 131590, 64360, 17610 ], } if (flowplate == False): pathDict = { '8by12 Bottom Stack': [ 177760, 44635, 31920, 177760, 67570, 31920, 177760, 60605, 31920, 177760, 83540, 31920, 188650, 44635, 31920, 188650, 67570, 31920, 188650, 60605, 31920, 188650, 83540, 31920 ], '1by4 Bottom Stack': [ 166870, 29365, 31920, 166870, 52300, 31920, 177760, 29365, 31920, 177760, 52300, 31920, 188650, 29365, 31920, 188650, 52300, 31920, 199540, 29365, 31920, 199540, 52300, 31920 ], '8by12 Actuator': [ 177760, 44635, 31920, 177760, 67570, 31920, 177760, 60605, 31920, 177760, 83540, 31920, 188650, 44635, 31920, 188650, 67570, 31920, 188650, 60605, 31920, 188650, 83540, 31920, ], '1by4 Actuator': [ 166870, 29365, 31920, 166870, 52300, 31920, 177760, 29365, 31920, 177760, 52300, 31920, 188650, 29365, 31920, 188650, 52300, 31920, 199540, 29365, 31920, 199540, 52300, 31920 ], '8by12 Jet Channel': [ 177760, 44635, 31920, 177760, 67570, 31920, 177760, 60605, 31920, 177760, 83540, 31920, 188650, 44635, 31920, 188650, 67570, 31920, 188650, 60605, 31920, 188650, 83540, 31920, ], '1by4 Jet Channel': [ 166870, 29365, 31920, 166870, 52300, 31920, 177760, 29365, 31920, 177760, 52300, 31920, 188650, 29365, 31920, 188650, 52300, 31920, 199540, 29365, 31920, 199540, 52300, 31920 ], '8by12 Orifice': [ 177760, 44635, 31920, 177760, 67570, 31920, 177760, 60605, 31920, 177760, 83540, 31920, 188650, 44635, 31920, 188650, 67570, 31920, 188650, 60605, 31920, 188650, 83540, 31920, ], '1by4 Orifice': [ 166870, 29365, 31920, 166870, 52300, 31920, 177760, 29365, 31920, 177760, 52300, 31920, 188650, 29365, 31920, 188650, 52300, 31920, 199540, 29365, 31920, 199540, 52300, 31920 ] } LJX8060 = serial.Serial(port='COM7', baudrate=115200, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout=0.5, xonxoff=False, rtscts=False, write_timeout=None, dsrdtr=False, inter_byte_timeout=None, exclusive=None) print(LJX8060.name) LJX8060.write(b'R0\r') #Switch to communication mode response = LJX8060.read(12) print(response) LJX8060.write(b'PW,1,' + programNumber + b'\r') #Switch to BCH Program response = LJX8060.read(12) print(response) LJX8060.write(b'TE,1\r') #Switch to communication mode response = LJX8060.read(12) print(response) rm = visa.ResourceManager() TTA = rm.open_resource('COM4') Servo_on(TTA) Home(TTA) time.sleep(1) acc = 20 dcl = 20 delay = 0.1 for i in range(0, len(pathDict[laserpath]), 6): vel = 150 ###### Move_XYZ(TTA, acc, dcl, vel, pathDict[laserpath][i], pathDict[laserpath][i + 1], pathDict[laserpath][i + 2], delay) vel = 19 LJX8060.write(b'T1\r') #Switch to communication mode Move_XYZ(TTA, acc, dcl, vel, pathDict[laserpath][i + 3], pathDict[laserpath][i + 4], pathDict[laserpath][i + 5], delay) #time.sleep(1) vel = 150 Move_XYZ(TTA, acc, dcl, vel, 10, 10, 10, delay) Home(TTA) rm.close() LJX8060.close()
def open_device(): rm = pv.ResourceManager() r = rm.list_resources() print 'opening', r[0] return rm.open_resource(r[0])
import pyvisa """ If everything is connected in the right way, this script will print all avaliable devices """ rm = pyvisa.ResourceManager() devices = rm.list_resources() print(devices)
def __init__(self, params): self.vx = None # tcp implementation self.conn = None # visa implementation self.params = params self.channels = params.get('channels') self.visa_id = params.get('visa_id') self.ip_addr = params.get('ip_addr') self.ip_port = params.get('ip_port') self.username = params.get('username') self.password = params.get('password') self.ts = params.get('ts') self.data_points = ['TIME'] self.pf_points = [] self.buffer_size = 255 self.config_array = [] self.b_expct = 6 # create query string for configured channels query_chan_str = '' item = 0 for i in range(1, 5): chan = self.channels[i] if chan is not None: chan_type = chan.get('type') points = chan.get('points') if points is not None: chan_label = chan.get('label') if chan_type is None: raise DeviceError('No channel type specified') if points is None: raise DeviceError('No points specified') for p in points: item += 1 point_str = '%s_%s' % (chan_type, p) chan_str = query_points.get(point_str) self.config_array.append( ':NUMERIC:NORMAL:ITEM%d %s,%d;' % (item, chan_str, i)) #query_chan_str += ':NUMERIC:NORMAL:ITEM%d %s,%d;' % (item, chan_str, i) if chan_label: point_str = '%s_%s' % (point_str, chan_label) self.data_points.append(point_str) #query_chan_str += '\n:NUMERIC:NORMAL:VALUE?' # self.query_str = ':NUMERIC:FORMAT ASCII\nNUMERIC:NORMAL:NUMBER %d\n' % (item) + query_chan_str self.query_str = ':NUMERIC:NORMAL:VALUE?' self.config_array.insert( 0, ':NUMERIC:FORMAT ASCII\nNUMERIC:NORMAL:NUMBER %d\n' % item) pf_scan(self.data_points, self.pf_points) if self.params.get('comm') == 'Network': # self.vx = vxi11.Instrument(self.params['ip_addr']) self.conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_address = (self.ip_addr, self.ip_port) self.conn.connect(server_address) self.conn.settimeout(2.0) self.ts.log_debug('WT1600 is Connected') # Enter the username "anoymous" and password "". # If the WT1600 is not configured correctly, a connection cannot be made. # Read the WT1600 device asking for username resp = self._query(None) self.ts.log_debug('WT1600 response: %s' % resp[4:len(resp)]) # Provide the username resp = self.query( self.username ) # Read the WT1600 device asking for password, but ignore response self.ts.log_debug('WT1600 response: %s' % resp[4:len(resp)]) resp = self.query( self.password ) # Read the WT1600 device asking for password, but ignore response self.ts.log_debug( 'WT1600 response: %s' % resp[4:len(resp)]) # Should print a password OK message self.b_expct = 4 for n in range(1, 24): resp = self.query( self.config_array[n]) # Send channel configuration self.b_expct = 6 resp = self.query( ':NUMERIC:NORMAL?') # Read the WT1600 Channel configuration self.ts.log_debug('WT1600 Channel Configuration: %s' % resp[4:len(resp)]) # Print Channel Configuration elif self.params.get('comm') == 'VISA': try: # sys.path.append(os.path.normpath(self.visa_path)) import pyvisa as visa self.rm = visa.ResourceManager() self.conn = self.rm.open_resource(params.get('visa_id')) # the default pyvisa write termination is '\r\n' which does not work with the SPS self.conn.write_termination = '\n' self.ts.sleep(1) except Exception as e: raise Exception('Cannot open VISA connection to %s\n\t%s' % (params.get('visa_id'), str(e))) # clear any error conditions self.cmd('*CLS')
def __init__(self): self.rm = visa.ResourceManager("@py") self.instr = self.rm.open_resource( 'USB0::65535::37376::802204020747010080::0::INSTR')
def __init__(self, address): self.rm = pyvisa.ResourceManager() self.SP = self.rm.open_resource(address) # Spec An