def __init__(self, name): #'USB0::0x0957::0x1754::MY44002614' #'GPIB0::1' print visa.get_instruments_list() self.mbs = visa.instrument(name) self.mbs.timeout = 60 self.mbs.chunk_size = 10 * 1024 * 1024
def _find_connection(self): """Find the appropriate GPIB connection """ instrument_list = [] print visa.get_instruments_list() for instrument in visa.get_instruments_list(): if instrument.startswith("GPIB"): temp_conn = visa.instrument(instrument) try: response = temp_conn.ask("*IDN?") except VisaIOError: # Need to release connection somehow! print "Cannot connect with %s" % instrument temp_conn.write("GTL") raise if response.startswith("*IDN LE"): instrument_list.append(instrument) if len(instrument_list)==0: raise ScopeException("Cannot find LeCroy684 GPIB") elif len(instrument_list)==1: return visa.instrument(instrument_list[0]) else: print "Select instrument:" for i, instrument in enumerate(instrument_list): temp_conn = visa.instrument(instrument) print "\t%s:\t%s" % (i, temp_conn.ask("*IDN?")) number = raw_input("Make selection [number]: ") return visa_instrument(instrument_list[number])
def detect(self): try: from visa import get_instruments_list, instrument, no_parity except: return [] devlist = get_instruments_list() retval = [] for handle in devlist: if (handle.find("COM") != -1): try: instr = instrument(handle, baud_rate=921600, data_bits=8, stop_bits=1, parity=no_parity, timeout = 0.1, term_chars = "\r\n") version = instr.ask("VE") except: version = "" if (version.find("AG-UC8") != -1 ): for ax in range(1,5): # motion controller - probe axes try: print "probe AG-UC8 axis ", ax ID = instr.ask(str(ax) + " TS")[3:] err = int(instr.ask("TE")[-1]) print ID if(ID != "" and err == 0): retval.append([handle,"Ax:"+str(ax)+" "+version,ax]) else: print "Error "+err except: print "exception" return retval
def refreshDevices(self): """Refresh the list of known devices on this bus. Currently supported are GPIB devices and GPIB over USB. """ try: addresses = visa.get_instruments_list() additions = set(addresses) - set(self.devices.keys()) deletions = set(self.devices.keys()) - set(addresses) for addr in additions: try: if addr.startswith('GPIB'): instName = addr elif addr.startswith('USB'): instName = addr + '::INSTR' else: continue instr = visa.instrument(instName, timeout=self.defaultTimeout['s']) self.devices[addr] = instr self.sendDeviceMessage('GPIB Device Connect', addr) except Exception, e: print 'Failed to add ' + addr + ':' + str(e) for addr in deletions: del self.devices[addr] self.sendDeviceMessage('GPIB Device Disconnect', addr)
def init(self): self.reason = '' self.ResourceManager = visa.ResourceManager() self.instruments = visa.get_instruments_list() # Create application self.app = QtGui.QApplication(sys.argv) # Create GUI self.gui = WavegenGui() # Connect log #self.log_handler = GuiLoggingHandler(self.gui.log) #self.log_handler.setFormatter(HtmlFormatter()) #self.log_handler.setLevel(logging.DEBUG) #log.addHandler(self.log_handler) # Set instruments self.gui.device_chooser.addItems(self.instruments) # Connect events self.connect_events() # Show dialog self.gui.show() if len(self.instruments) < 1: success = False self.reason = 'did not get any instruments from visa' else: success = True # find device ids if success: yield 'preinit', 'wait1' else: yield 'preinit', 'fail_init'
def whoisthere(): if old_visa: port_addresses = visa.get_instruments_list() else: rm = visa.ResourceManager() port_addresses = rm.list_resources() connection_list = {} for port in port_addresses: try: print(port) device = MeasInstr(port) device.connection.timeout = 0.5 # print port +" OK" try: name = device.identify() connection_list[port] = name except: pass except: pass return connection_list
def refreshInstrumentList(self): try: self.AVAILABLE_PORTS = visa.get_instruments_list() except visa.VisaIOError as e: if e.error_code == -1073807343: print "GPIB does not seem to be connected" self.AVAILABLE_PORTS = ["GPIB::8", "GPIB::9", "GPIB::26"]
def detect(self): try: from visa import get_instruments_list, instrument except: return [] devlist = get_instruments_list() retval = [] for handle in devlist: if (handle.find("GPIB") != -1): instr = instrument(handle) version = instr.ask("*IDN?") if (version.find("ESP300") != -1 ): for ax in range(1,4): # motion controller - probe axes #print "probe axis #%d" % (ax) try: print "probe ESP axis ", ax ID = instr.ask(str(ax) + " ID?") err = int(instr.ask("TE?")) print " ..returns ", ID, " and error ", err if(ID != "Unknown" and err == 0): retval.append([handle,"Ax:"+str(ax)+" "+version,ax]) except: print "exception" return retval
def __init__(self): WAVELENGTH = 1563.0 inst_list = visa.get_instruments_list() inst_str = inst_list[0] + '::INSTR' self.instrument = visa.instrument(inst_str) self.instrument.write('*CLS\n') #self.instrument.write('CORR:WAV' + format(WAVELENGTH) + '\n') self.instrument.write('CORR:WAV 1563\n')
def updateVISAListOpen(self): """Get list of connected VISA devices and set combo box.""" try: VISAList = visa.get_instruments_list() except NameError: VISAList = ('No VISA Drivers Found') self.SMUAddress.clear() self.SMUAddress.addItems(QStringList(VISAList))
def GPIB_Init(resource_name): GPIB_Found = False RSA = None IDN_company = None IDN_model = None IDN_serial = None IDN_firmware = None RSA_OPT = None for a in range(0,np.shape(vs.get_instruments_list(True))[0]): if vs.get_instruments_list(True)[a] == resource_name: GPIB_Found = True RSA = vs.instrument(resource_name) RSA_IDN = vs.instrument(resource_name).ask('*idn?') [IDN_company, IDN_model, IDN_serial, IDN_firmware]=RSA_IDN.split(',') RSA_OPT = vs.instrument(resource_name).ask('*opt?') RSA.write('*rst') # reset instrument to start from known state return GPIB_Found, RSA, IDN_company, IDN_model, IDN_serial, IDN_firmware, RSA_OPT
def _io_button_fired(self): try: instr = visa.get_instruments_list()[0] except IndexError: instr = '' if self.io_settings.instr == '': self.io_settings.instr = instr if self.io_settings.edit_traits(kind = 'livemodal'): print('OK')
def setup(self): # Get the USB device, e.g. 'USB0::0x1AB1::0x0588::DS1ED141904883' instruments = visa.get_instruments_list() print(instruments) usb = filter(lambda x: 'USB' in x, instruments) #if len(usb) != 1: # print 'Bad instrument list', instruments # sys.exit(-1) self.scope = visa.instrument(u'USB0::0x1AB1::0x04CE::DS1ZA192409475::INSTR', timeout=20, chunk_size=1024000) # bigger timeout for long mem
def list_resources(): "List PyVisa resource strings" try: # New style PyVISA return visa_rm.list_resources() except AttributeError: # Old style PyVISA return visa.get_instruments_list() return []
def init_Scope(): instruments = visa.get_instruments_list() usb = filter(lambda x: 'USB' in x, instruments) if len(usb) != 1: print 'Bad instrument list', instruments sys.exit(-1) scope = visa.instrument( usb[0], timeout=15, chunk_size=1024000 ) # use bigger timeout for deep mem (i.e. collecting 1e6 points) return scope
def findVisaResources(): try: rm = visa.ResourceManager() visaResources = rm.list_resources() except AttributeError: # Compatibility with old pyvisa (<1.5?) visaResources = visa.get_instruments_list() except Exception as e: warnings.warn('Unable to find VISA resources:', e) visaResources = [] return visaResources
def __init__(self): """ Try the default connection.""" try: for instrument in visa.get_instruments_list(): if instrument[0:3] == "USB": self._connection = visa.instrument(instrument) print "Connecting to", instrument print "Which has identity:", self.ask("*idn?") # Ask the scope for its identity except visa_exceptions.VisaIOError: print "Cannot connect to any instrument." raise
def __init__(self): """ Try the default connection.""" try: for instrument in visa.get_instruments_list(): if instrument[0:3] == "USB": self._connection = visa.instrument(instrument) print "Connecting to", instrument print "Which has identity:", self.ask( "*idn?") # Ask the scope for its identity except visa_exceptions.VisaIOError: print "Cannot connect to any instrument." raise
def get_devices(): """Return list of connected VISA devices. Wrapper for pyVISA's get_instruments_list(). Use this preferably, since it handles situation of working VISA/pyVISA environment but no devices connected by returning an empty list. """ try: devlist = get_instruments_list() except VisaIOError: devlist = [] return devlist
def __init__(self,USB_num=0,GetInstId=0): self.InstId = "" self.dwidth = 1 self.clock = 0 available = [ inst for inst in visa.get_instruments_list() if ("USB%i" % USB_num) in inst] if len(available) == 0: print "No USB%i instrument found." % i sys.exit(1) visa.Instrument.__init__(self,available[0]) if GetInstId == 1: self.write("*IDN?") self.InstId=self.read()
def __init__(self): """ Try the default connection.""" super(VisaUSB, self).__init__() try: for instrument in visa.get_instruments_list(): if instrument[0:3] == "USB": self._connection = visa.instrument(instrument, send_end=True) print "Connecting to", instrument print "Scope identity:", self.identity() except visa_exceptions.VisaIOError: logging.exception("Cannot connect to any instrument.") print "Cannot connect to any instrument." raise
def existing_addresses(recheck = True): """ returns a list of all valid addresses (using visa.get_instruments_list()) """ global EXISTING_ADRESSES if recheck or EXISTING_ADRESSES==[]: try: import visa EXISTING_ADRESSES = visa.get_instruments_list() except VisaIOError: print "visa seems to have a problem on this computer..." return EXISTING_ADRESSES
def find_scope(): # Get the USB device, e.g. 'USB0::0x1AB1::0x04CE::DS1ZA170300600' instruments = visa.get_instruments_list() usb = filter(lambda x: 'DS1' in x, instruments) if len(usb) != 1: print('No Scope found: ', instruments) #sys.exit(-1) else: print("Scope found at: " + usb[0]) global scope scope = visa.instrument( usb[0], timeout=1, chunk_size=10240000) # bigger timeout for long mem
def existing_addresses(recheck=True): """ returns a list of all valid addresses (using visa.get_instruments_list()) """ global EXISTING_ADRESSES if recheck or EXISTING_ADRESSES == []: try: import visa EXISTING_ADRESSES = visa.get_instruments_list() except VisaIOError: print "visa seems to have a problem on this computer..." return EXISTING_ADRESSES
def detect(self): try: from visa import get_instruments_list, instrument except: return [] devlist = get_instruments_list() retval = [] for handle in devlist: if (handle.find("GPIB") != -1): instr = instrument(handle) version = instr.ask("*IDN?") if (version.find("34401A") != -1 ): retval.append([handle,version]) return retval
def refresh_instr_list(self): with self.reserved_access_to_instr: l=visa.get_instruments_list() self.ui.instr_table.setRowCount(len(l)) for i in range(len(l)): if not('ASRL' in l[i] or 'COM' in l[i]):#COM ports don't respond to visa *IDN?, which raises an error, so don't ask them with self.reserved_access_to_instr: try: a=visa.instrument(l[i]) a.timeout=1.5 self.ui.instr_table.setItem(i,0,QTableWidgetItem(a.ask('*IDN?'))) a.timeout=5 except: self.ui.instr_table.setItem(i,0,QTableWidgetItem('Instruments did not respond to *IDN?')) self.ui.instr_table.setItem(i,1,QTableWidgetItem(l[i]))
def buscaAgilent(): """ Busca o equipamento conectado a porta usb do computador Retornando o objeto a ser usado pelas funções de controle da placa de aquisiçao da agilent. """ listaInstrumentos = visa.get_instruments_list() # adquiri a lista de equipamentos conectados ao computador listaAgilent = listaInstrumentos[0] # pega o primeiro equipamento print 'Lista de instrumentos:' print listaAgilent # espera-se que o equipamento seja da agilent ag = visa.instrument(listaAgilent) # cria um objeto a ser manipulado e passado para as outras funções identificacao = ag.ask("*IDN?") print identificacao return ag
def search_for_coms(self): # Pulls all active visa ports # The try.except clause is in case there are no visa port on the computer. Without it, an error is returned try: # Collects a list of all the visa ports on the computer visas = visa.get_instruments_list() except: # If there are no visas connected to the computer, get_instruments_list returns an error # When that occurs, the variable, "visas", the list is defined to is instead defined to an empty string which shows nothing in the combo box visas = '' # Removes any previous data in the combo box self.ui.com_box.clear() if visas == '': self.ui.connected_result.setText('No devices found!') self.ui.connect_disconnect_button.setEnabled(False) else: self.ui.com_box.setEnabled(True) self.ui.connect_disconnect_button.setEnabled(True) for each_visa in visas: self.ui.com_box.addItem(each_visa)
def _initialise(self): """Iterates through all devices on the GPIB bus until it finds the parameter analyser with ID _self.deviceName. If no parameter analyser found the initiation is aborted and a sys.exit is called""" print("HP4156C Initialisation") _devices = visa.get_instruments_list() for _x in range(0, len(_devices)): try: self.pa = visa.instrument(_devices[_x]) self.device_id = self.pa.ask("*IDN?") if (self.device_id == self.deviceName): print("Found device %s" % self.device_id) break except: print("Could not connect to device %s" % _devices[_x]) if (self.device_id != self.deviceName): print("Could not find the parameter analyser.") print("Exiting.") sys.exit() else: self.pa.write("*rst") print("Connected to device %s" % _devices[_x])
def whoisthere(): """ try to connect to all ports availiable and send *IDN? command this is something than can take some time """ if old_visa: port_addresses = visa.get_instruments_list() else: rm = visa.ResourceManager() port_addresses = rm.list_resources() connection_list = {} for port in port_addresses: try: print(port) device = MeasInstr(port) device.connection.timeout = 0.5 # print port +" OK" try: name = device.identify() connection_list[port] = name except: pass except: pass return connection_list
def detect(self): try: from visa import get_instruments_list, instrument, no_parity except: return [] devlist = get_instruments_list() retval = [] for handle in devlist: if (handle.find("COM") != -1): try: instr = instrument(handle, baud_rate=57600, data_bits=8, stop_bits=1, parity=no_parity, timeout = 0.5, term_chars = "\r\n") for ax in range(1,4): # motion controller - probe axes, probe only 1 to 4 (SMC supports up to 31 controllers!) try: version = instr.ask(str(ax) + "VE") # query controllers, each controller can handle 1 axis if (version.find("SMC") != -1): retval.append([handle,"Ax:"+str(ax)+" "+version,ax]) except: pass except: pass return retval
def list_GPIB_ports(): """ Load VISA resource list for use in combo boxes """ try: if old_visa: available_ports = visa.get_instruments_list() else: rm = visa.ResourceManager() available_ports = rm.list_resources() temp_ports = [] for port in available_ports: if "GPIB" in port: temp_ports.append(str(port)) available_ports = temp_ports except: available_ports = [] # pc = PrologixController(com_port = PROLOGIX_COM_PORT) # available_ports = available_ports + pc.get_open_gpib_ports() return available_ports
def __init__(self, name=None, wait_for_settle=True, reset=True): self.wait_for_settle = wait_for_settle if not name: instruments = visa.get_instruments_list() # find first GPIB interface for dev in instruments: if "gpib" in dev.lower(): name = dev break else: raise exception('cannot find device') # connect to device and configure VISA settings self.device = visa.instrument(name) vpp43.gpib_control_ren(self.device.vi, visa.VI_GPIB_REN_ASSERT_ADDRESS) # doesn't work without this self.device.clear() self.set_output_enabled(False) if reset: self.reset()
def __init__(self, name=None, wait_for_settle=True, reset=True): self.wait_for_settle = wait_for_settle if not name: instruments = visa.get_instruments_list() # find first GPIB interface for dev in instruments: if "gpib" in dev.lower(): name = dev break else: raise exception('cannot find device') # connect to device and configure VISA settings self.device = visa.instrument(name) vpp43.gpib_control_ren( self.device.vi, visa.VI_GPIB_REN_ASSERT_ADDRESS) # doesn't work without this self.device.clear() self.set_output_enabled(False) if reset: self.reset()
import visa import numpy as np """ visa.get_instruments_list(use_aliases=True) del NC NC=visa.instrument('GPIB0::%i'%9, delay=0.1, term_chars=';\n') #- test stuff NC.write('*RST') NC.write('*CLS') NC.ask('*IDN?') NC.ask('QUNIT?1') float(NC.ask('QSAMP?1')[:-1]) #- construct CX-1030 calibration table""" if 1: Rmin=46.0 Rmax=14291.5 R1=np.linspace(257.0, 510, 119) R2=np.linspace(46.10, 240.0, 19) R=np.hstack((R1, R2)) R.sort() r=(2*np.log10(R)-np.log10(Rmax)-np.log10(Rmin))/(np.log10(Rmax)-np.log10(Rmin)) T=55.34924-97.76682*np.cos(np.arccos(r))+68.8287*np.cos(2*np.arccos(r))-38.5868*np.cos(3*np.arccos(r))+17.08834*np.cos(4*np.arccos(r))-6.3504*np.cos(5*np.arccos(r))+2.93285*np.cos(6*np.arccos(r))-2.35006*np.cos(7*np.arccos(r))+1.97358*np.cos(8*np.arccos(r))-1.20816*np.cos(9*np.arccos(r))+0.38118*np.cos(10*np.arccos(r)) print R print T if 1: import matplotlib.pyplot as plt plt.plot(T, R, 'bo')
@author: Sean McLaughlin This is my first module coded in the lab. I'm going to try to work with a few moving pieces and operate a few instruments. The program steps the output from the lock-in my 10mV from 0V to 5V. This voltage is proportional to the field strength of the magnet, which is measured by the Gauss probe. I've implemented some convuluted safety features which may be unecessary. ''' try: import numpy as np from matplotlib import pyplot as plt import visa import time except ImportError: print "There was a problem importing the files; check the PYTHONPATH" else: resAddresses = visa.get_instruments_list() #Get all the resource addresses #as far as I can tell, we will need to use the adresses as starter data, because I don't know how to tell what instrument is which from the address #I could use *IDN? to get the model number and maybe use that but I'm not sure if that's a good idea. #the Gauss probe is GPIB0::12 at present, and the Lock-in is GPIB0::24 at present. hallp = visa.Instrument(resAddresses[3]) lockin = visa.Instrument(resAddresses[6]) safe = True #Boolean to see if device is on or off try: def splitRTheta(both, R, T): #This function comes into play for splitting the r and theta string into 2 things for s in both: commaIndex = -1 for i in xrange(len(s)): if s[i]==',':
def __init__(self, threadID, name, wavelength, pulse_separation, fileName): #-- Definitions threading.Thread.__init__(self) self.threadID = threadID self.name = name self.pulse_separation = pulse_separation self.exit_flag = 0 self.wavelength = wavelength wait = 0.25 # Wait call, in s pW = 1e-12 # 1 pico Watt #################### # INSTRUMENT SET-UP #################### print visa.get_instruments_list() # enable this to find the device ID if needed #self.power_meter = visa.instrument("USB0::0x1313::0x8072::P2000781::0") # Leeds self.power_meter = visa.instrument("USB0::0x1313::0x8072::P2001877::0") # Sussex time.sleep(wait); self.power_meter.write("*RST") time.sleep(wait); print "Info: Instrument ID:", self.power_meter.ask("*IDN?") time.sleep(wait); print "Info: Self test status:",self.power_meter.ask("*TST?") time.sleep(wait); print "Info: System version: ", self.power_meter.ask("SYSTEM:VERSION?") time.sleep(wait); response = self.power_meter.ask("SYSTEM:SENSOR:IDN?"); list = response.split(","); print "Info: Sensor ID is ",list[0]; time.sleep(wait); self.power_meter.write("CONFIGURE:SCALAR:TEMPERATURE") time.sleep(wait); temperature = float(self.power_meter.ask("READ?")); print "Info: Sensor temperature is %.1f Celsius" % temperature time.sleep(wait); self.power_meter.write("CONFIGURE:SCALAR:POWER") time.sleep(wait); self.power_meter.write("POWER:DC:UNIT W") time.sleep(wait); print "Info: Unit for DC power is now : ",self.power_meter.ask("POWER:DC:UNIT?") time.sleep(wait); self.power_meter.write("SENSE:CORRECTION:WAVELENGTH "+str(int(wavelength))) time.sleep(wait); nm = float(self.power_meter.ask("SENSE:CORRECTION:WAVELENGTH?")); print "Info: Wavelength now set to [nm]: ",int(nm) time.sleep(wait); self.power_meter.write("SENSE:AVERAGE:COUNT 3000") time.sleep(wait); counts = int(self.power_meter.ask("SENSE:AVERAGE:COUNT?")); print "Info: Samples per average pre zero adjustment: ",int(counts) time.sleep(wait); print "Info: Configuration is set to : ", self.power_meter.ask("CONFIGURE?") time.sleep(wait); print "Info: Power auto range status : ", self.power_meter.ask("POWER:RANGE:AUTO?") #-- zero suppression for n in range(0, 1) : time.sleep(wait); self.power_meter.write("SENSE:CORRECTION:COLLECT:ZERO:INITIATE") state = 1 while state > 0 : time.sleep(wait); state = int(self.power_meter.ask("SENSE:CORRECTION:COLLECT:ZERO:STATE?")) print "Info: Zero adjustment (1=waiting, 0=done) : %s" % (state) else: ped = float(self.power_meter.ask("SENSE:CORRECTION:COLLECT:ZERO:MAGNITUDE?")) time.sleep(wait); print "Info: Pedestal [pW] : %s" % (ped/pW) #-- reduce counts per average (1 count takes 2 ms) counts = 500 cmd = "SENSE:AVERAGE:COUNT %i " % counts time.sleep(wait); self.power_meter.write(cmd) time.sleep(wait); counts = int(self.power_meter.ask("SENSE:AVERAGE:COUNT?")) print "Info: Samples per average post zero adjustment: %i" % (int(counts)) #-- Save header to file data = open(fileName,"w") rate=1./pulse_separation dataStr = "%i %1.2e %i %2.1f %3.3e \n" % (wavelength, pulse_separation, rate, temperature, ped) data.write(dataStr) data.close()
raise Exception("Invalid input channel ID.") def write(self, channel, value): if channel == 0: self.instrument.write(':SOURCE:VOLTAGE ' + value) elif channel == 1: self.instrument.write(':SOURCE:VOLTAGE1 ' + value) else: raise Exception("Invalid output channel ID.") def __del__(self): self.instrument.close() daq = None for resource in visa.get_instruments_list(): try: daq = ArduinoDAQ('COM11') except: continue print "Found instrument on " + resource + "." break if daq == None: print "Could not open find proper instrument." t0 = [] in0 = [] t1 = []
def write(self, channel, value): if channel == 0: self.instrument.write(':SOURCE:VOLTAGE ' + value) elif channel == 1: self.instrument.write(':SOURCE:VOLTAGE1 ' + value) else: raise Exception("Invalid output channel ID.") def __del__(self): self.instrument.close() daq = None for resource in visa.get_instruments_list(): try: daq = ArduinoDAQ('COM11') except: continue print "Found instrument on " + resource + "." break if daq == None: print "Could not open find proper instrument." t0 = [] in0 = [] t1 = []
def handle(self): log("Opening connection...") instruments = [] messenger = Messenger(self.request, is_server=True) while True: message = messenger.recv() if not message: log("Received EOF, closing connection.") break # Break on incoming EOF cmd, rest = message.split(b":", 1) if cmd == b"I": kwargs = json.loads(rest) name = kwargs.pop("visa_address") print(kwargs) log("Client asked for instrument '{}'".format(name)) try: instruments.append(visa.instrument(name, **kwargs)) # Reply with the instrument's unique ID number response = encode(str(len(instruments) - 1)) except visa.Error as e: response = _visa_err_response(e) elif cmd == b"G": log("Client asked for instrument list") # addr_list returns a list of unicode strings addr_list = visa.get_instruments_list() response = "%|%".join(addr_list) response = encode(response, "utf-8") elif cmd == b"A": # Get response from instrument, and send it back to client head, body = rest.split(b":", 1) id = int(head) log("Client asking '{}' from instrument with id {}...".format(body, id)) try: # visa.ask() returns a unicode string str_resp = instruments[id].ask(body) response = encode(str_resp, "utf-8") except visa.Error as e: response = _visa_err_response(e) elif cmd == b"W": # Send message to device and return num bytes written head, body = rest.split(b":", 1) id = int(head) try: log("Client writing '{}' to instrument with id {}...".format(body, id)) except UnicodeDecodeError: log("Client writing binary data to instrument with id {}...".format(id)) try: instruments[id].write(body) response = b"Success" except visa.Error as e: response = _visa_err_response(e) elif cmd == b"R": id = int(rest) log("Client reading from instrument with id '{}'...".format(id)) try: # read_raw() returns bytes object response = instruments[id].read_raw() except visa.Error as e: response = _visa_err_response(e) elif cmd == b"close": id = int(rest) log("Client closing instrument with id '{}'...".format(id)) try: instruments[id].close() response = b"Success" except visa.Error as e: response = _visa_err_response(e) elif cmd == b"getattr": head, body = rest.split(b":", 1) id = int(head) name = decode(body, "utf-8") log("Client asking for attr '{}' from instrument with id {}...".format(name, id)) try: attr = getattr(instruments[id], name) response = encode(json.dumps(attr), "utf-8") except AttributeError as e: response = b"AttributeError" elif cmd == b"setattr": head, raw_name, raw_value = rest.split(b":", 2) id = int(head) name = decode(raw_name, "utf-8") value = json.loads(raw_value) log("Client setting attr '{}' to '{}' for instrument with id {}...".format(name, value, id)) try: setattr(instruments[id], name, value) response = b"Success" except Exception: response = b"ERROR" elif cmd == b"clear": id = int(rest) log("Client clearing instrument with id '{}'...".format(id)) try: instruments[id].clear() response = b"Success" except visa.Error as e: response = _visa_err_response(e) # 'response' should already be encoded as bytes log(b" responding with '" + response + b"'") messenger.send(response)
#!/usr/bin/python """ Download data from a Rigol DS1052E oscilloscope and graph with matplotlib. By Ken Shirriff, http://righto.com/rigol Based on http://www.cibomahto.com/2010/04/controlling-a-rigol-oscilloscope-using-linux-and-python/ by Cibo Mahto. """ import numpy import matplotlib.pyplot as plot import sys import visa # Get the USB device, e.g. 'USB0::0x1AB1::0x0588::DS1ED141904883' instruments = visa.get_instruments_list() usb = filter(lambda x: 'USB' in x, instruments) if len(usb) != 1: print 'Bad instrument list', instruments sys.exit(-1) scope = visa.instrument(usb[0], timeout=20, chunk_size=1024000) # bigger timeout for long mem # Grab the raw data from channel 1 scope.write(":STOP") # Get the timescale timescale = scope.ask_for_values(":TIM:SCAL?")[0] # Get the timescale offset timeoffset = scope.ask_for_values(":TIM:OFFS?")[0]
def findInstruments(self): return visa.get_instruments_list()
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 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' instruments = visa.get_instruments_list() usb = filter(lambda x: 'USB' in x, instruments) if len(usb) != 1: print 'Bad instrument list', instruments sys.exit(-1) scope = visa.instrument( usb[0], timeout=20, chunk_size=1024000) # bigger timeout for long mem 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.ask(':ACQ:SAMP?')) #timescale = float(scope.ask(":TIM:SCAL?")) #timeoffset = float(scope.ask(":TIM:OFFS?")) #voltscale = float(scope.ask(':CHAN1:SCAL?')) #voltoffset = float(scope.ask(":CHAN1:OFFS?")) 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 if SAMPLEdepth == 0: scope.write(':ACQ:MEMD NORM') # Long memory type else: scope.write(':ACQ:MEMD LONG') # normal memory type #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 scope.write(":RUN") #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 scope.ask(':TRIG:STAT?') != 'STOP': sleep(0.1) #sleep(0.1) # Grab the raw data from channel 1, which will take a few seconds for long buffer mode scope.write(":STOP") scope.write(":WAV:POIN:MODE RAW") 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 signals = scope.ask(":WAV:DATA? CHAN1") #do this first data_size = len(signals) SAMPLErate = scope.ask_for_values(':ACQ:SAMP?')[0] #do this second #print 'Data size:', SAMPLEsize, "Sample rate:", SAMPLErate sleep(0.1) # convert data from (inverted) bytes to an array of scaled floats # this magic from Matthew Mets SIGNAL1 = numpy.frombuffer(signals, 'B') #print SIGNAL1 SIGNAL1 = (SIGNAL1 * -1 + 255) - 130 # invert #print SIGNAL1 SIGNAL1 = SIGNAL1 / 127.0 # scale 10 +-1, has a slight DC offset #print SIGNAL1 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): scope.write(":KEY:FORCE") scope.close() 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 handle(self): log("Opening connection...") instruments = [] messenger = Messenger(self.request, is_server=True) while True: message = messenger.recv() if not message: log("Received EOF, closing connection.") break # Break on incoming EOF cmd, rest = message.split(b':', 1) if cmd == b'I': kwargs = json.loads(rest) name = kwargs.pop('visa_address') print(kwargs) log("Client asked for instrument '{}'".format(name)) try: instruments.append(visa.instrument(name, **kwargs)) # Reply with the instrument's unique ID number response = encode(str(len(instruments)-1)) except visa.Error as e: response = _visa_err_response(e) elif cmd == b'G': log("Client asked for instrument list") # addr_list returns a list of unicode strings addr_list = visa.get_instruments_list() response = "%|%".join(addr_list) response = encode(response, 'utf-8') elif cmd == b'A': # Get response from instrument, and send it back to client head, body = rest.split(b':', 1) id = int(head) log("Client asking '{}' from instrument with id {}...".format(body, id)) try: # visa.ask() returns a unicode string str_resp = instruments[id].ask(body) response = encode(str_resp, 'utf-8') except visa.Error as e: response = _visa_err_response(e) elif cmd == b'W': # Send message to device and return num bytes written head, body = rest.split(b':', 1) id = int(head) try: log("Client writing '{}' to instrument with id {}...".format(body, id)) except UnicodeDecodeError: log("Client writing binary data to instrument with id {}...".format(id)) try: instruments[id].write(body) response = b'Success' except visa.Error as e: response = _visa_err_response(e) elif cmd == b'R': id = int(rest) log("Client reading from instrument with id '{}'...".format(id)) try: # read_raw() returns bytes object response = instruments[id].read_raw() except visa.Error as e: response = _visa_err_response(e) elif cmd == b'close': id = int(rest) log("Client closing instrument with id '{}'...".format(id)) try: instruments[id].close() response = b'Success' except visa.Error as e: response = _visa_err_response(e) elif cmd == b'getattr': head, body = rest.split(b':', 1) id = int(head) name = decode(body, 'utf-8') log("Client asking for attr '{}' from instrument with id {}...".format(name, id)) try: attr = getattr(instruments[id], name) response = encode(json.dumps(attr), 'utf-8') except AttributeError as e: response = b'AttributeError' elif cmd == b'setattr': head, raw_name, raw_value = rest.split(b':', 2) id = int(head) name = decode(raw_name, 'utf-8') value = json.loads(raw_value) log("Client setting attr '{}' to '{}' for instrument with id {}...".format(name, value, id)) try: setattr(instruments[id], name, value) response = b'Success' except Exception: response = b'ERROR' elif cmd == b'clear': id = int(rest) log("Client clearing instrument with id '{}'...".format(id)) try: instruments[id].clear() response = b'Success' except visa.Error as e: response = _visa_err_response(e) # 'response' should already be encoded as bytes log(b" responding with '" + response + b"'") messenger.send(response)
""" Download data from a Rigol DS1052E oscilloscope channel 1 and dump to a .wav file. By Ken Shirriff, http://righto.com/rigol 9-20-15 Rich Heslip - added os call to wfm_view for viewing waveforms and spectrum """ import sys import visa import wave import os # Get the USB device, e.g. 'USB0::0x1AB1::0x0588::DS1ED141904883' instruments = visa.get_instruments_list() usb = filter(lambda x: 'USB' in x, instruments) if len(usb) != 1: print 'Bad instrument list', instruments sys.exit(-1) scope = visa.instrument(usb[0], timeout=20, chunk_size=1024000) # bigger timeout for long mem # Grab the raw data from channel 1 scope.write(":STOP") scope.write(":WAV:POIN:MODE RAW") rawdata = scope.ask(":WAV:DATA? CHAN1")[10:] data_size = len(rawdata) sample_rate = scope.ask_for_values(':ACQ:SAMP?')[0] print 'Data size:', data_size, "Sample rate:", sample_rate scope.write(":KEY:FORCE") scope.close()
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 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' instruments = visa.get_instruments_list() usb = filter(lambda x: 'USB' in x, instruments) if len(usb) != 1: print 'Bad instrument list', instruments sys.exit(-1) scope = visa.instrument(usb[0], timeout=20, chunk_size=1024000) # bigger timeout for long mem 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.ask(':ACQ:SAMP?')) #timescale = float(scope.ask(":TIM:SCAL?")) #timeoffset = float(scope.ask(":TIM:OFFS?")) #voltscale = float(scope.ask(':CHAN1:SCAL?')) #voltoffset = float(scope.ask(":CHAN1:OFFS?")) 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 if SAMPLEdepth == 0: scope.write(':ACQ:MEMD NORM') # Long memory type else: scope.write(':ACQ:MEMD LONG') # normal memory type #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 scope.write(":RUN") #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 scope.ask(':TRIG:STAT?') != 'STOP': sleep(0.1) #sleep(0.1) # Grab the raw data from channel 1, which will take a few seconds for long buffer mode scope.write(":STOP") scope.write(":WAV:POIN:MODE RAW") 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 signals= scope.ask(":WAV:DATA? CHAN1") #do this first data_size = len(signals) SAMPLErate = scope.ask_for_values(':ACQ:SAMP?')[0] #do this second #print 'Data size:', SAMPLEsize, "Sample rate:", SAMPLErate sleep(0.1) # convert data from (inverted) bytes to an array of scaled floats # this magic from Matthew Mets SIGNAL1 = numpy.frombuffer(signals, 'B') #print SIGNAL1 SIGNAL1 = (SIGNAL1 * -1 + 255) -130 # invert #print SIGNAL1 SIGNAL1 = SIGNAL1/127.0 # scale 10 +-1, has a slight DC offset #print SIGNAL1 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): scope.write(":KEY:FORCE") scope.close() 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
wave.y = (np.array(d)-wave.yref)*wave.yinc+wave.y0 elif wave.dataFormat == 'ASCII': wave.y = np.array(data.split(',')) peak = False if (peak): m = 2 else: m = 1 wave.t = (np.array(range(0, wave.numberOfPoints))-wave.xref)*m*wave.xinc+wave.x0 return wave if __name__ == "__main__": import visa instrumentList = visa.get_instruments_list() print instrumentList dso = AgilentDSOX2004A(address="USB0::0x0957::0x179A::MY52141087") channel = 1 print "Channel:", channel print "Trigger source:", dso.triggerSource() print "Time base scale: %f s/div" % dso.timeBaseScale() print "Time base full range: %f s" % dso.timeBaseRange() print "Y scale: %f V/div" % dso.channelScale(channel) print "Y range: %f V" % dso.channelRange(channel) import time t = time.time() for i in [0,1]: wave = dso.acquireWaveform(channel) elapsed = time.time() - t
#!/usr/bin/python import numpy import matplotlib.pyplot as plot import visa """ Example program to plot the Y-T data from Channel 1""" # Initialize our scope print visa.get_instruments_list() test = visa.instrument("USB0::0x1AB1::0x0488::DS1BC130900036::INSTR") # Stop data acquisition test.write(":STOP") # Grab the data from channel 1 test.write(":WAV:POIN:MODE NOR") test.write(":WAV:DATA? CHAN1") rawdata1 = test.read() print "channel 1" print rawdata1 test.write(":WAV:DATA? CHAN2") print "channel 2" rawdata2 = test.read() print rawdata2 data1 = numpy.frombuffer(rawdata1, 'B')
def __init__(self, name): #'GPIB0::1' print visa.get_instruments_list() self.mbs = visa.instrument(name) self.mbs.timeout = 10