def write(self, query): """ writes a query to remote device Arguments: query -- (string) the query which shall be sent """ gpib.write(self.device, query + self.term_chars)
def get_mkr_amp(self): """Get marker amplitude Return marker value in dBm """ gpib.write(self.device, "MA") result = gpib.read(self.device, 8) return float(result)
def set_center_freq(self, center_freq): """Set center frequency Keyword arguments: center_freq -- Center frequency in Hz """ cmd = "CF" + str(center_freq) + "HZ" gpib.write(self.device, cmd) return()
def set_span(self, span): """Set span Keyword arguments: span -- Span in Hz """ cmd = "SP" + str(span) + "HZ" gpib.write(self.device, cmd) return()
def set_rbw(self, rbw): """Set resolution bandwidth Keyword arguments: rbw -- RBW in Hz """ cmd = "RB" + str(rbw) + "HZ" gpib.write(self.device, cmd) return()
def set_vbw(self, vbw): """Set video bandwidth Keyword arguments: vbw -- VBW in Hz """ cmd = "VB" + str(vbw) + "HZ" gpib.write(self.device, cmd) return()
def set_ref_level(self, ref_level): """Set reference level Keyword arguments: ref_level -- Reference level in dBm """ cmd = "RL" + str(ref_level) gpib.write(self.device, cmd) return()
def set_mkr_freq(self, mkr_freq): """Set marker frequency Keyword arguments: mkr_freq -- Marker frequency in Hz """ cmd = "MKF" + str(mkr_freq) + "HZ" gpib.write(self.device, cmd) return()
def write(self, cmd): while True: status = ord(gpib.serial_poll(self.dev)) #print '.', if status & Poll.COMMAND_DONE != 0: break elif status & Poll.OUTPUT_READY != 0: raise PARWriteError("Data is ready, can't write") gpib.write(self.dev, cmd)
def get_power(self, filename='test_save_file_', PLOT=False, typ='BYTE', SAVE=False): print "ACQUIRING..." #gpib.write(self.scope,'*IDN?') gpib.write(self.scope, 'POWER?') self.data = gpib.read(self.scope, 1000) print "CHEERS!!!" return self.data
def write(self, str, calls=0): try: gpib.write(self.id, str) self.last_write = str except gpib.GpibError: if calls == 2: Logging.error("Unrecoverable error. Please reboot") raw_input("Press ENTER when done.") exit(1) self.reset() self.write(str, calls=calls + 1)
def meas(): gpib.write(dc1, 'MEAS:CURR?') s = gpib.read(dc1, 1000) global t0 if t0 is None: t0 = datetime.datetime.now() t = datetime.timedelta(0) else: t = datetime.datetime.now() - t0 print('{}.{:06d},{}'.format(t.seconds, t.microseconds, s.decode().rstrip())) sys.stdout.flush()
def setV(self,c,v): i_meas = 0 v_meas = 0 if(c != self.curchan): self.curchan=c msg="INST:NSEL " + str(self.curchan) if(self.debug): print(msg) else: gpib.write(self.pm2812,msg) msg = "VOLT " + str(v) if(self.debug): print(msg) else: gpib.write(self.pm2812,msg) time.sleep(0.5) gpib.write(self.pm2812,"MEAS:VOLT?") time.sleep(0.1) v_meas=gpib.read(self.pm2812,100) v_meas = float(v_meas.rstrip()) if(self.negative): v_meas = -v_meas gpib.write(self.pm2812,"MEAS:CURR?") i_meas=gpib.read(self.pm2812,100) i_meas = float(i_meas.rstrip()) time.sleep(.5) return([v_meas,i_meas])
def off(self): gpib.write(self.smiq, ':FREQ:MODE?') answer = gpib.read(self.smiq, 256) if answer == 'LIST': gpib.write(self.smiq, ':FREQ:MODE CW') gpib.write(self.smiq, ':OUTP OFF') gpib.write(self.smiq, '*WAI')
def __init__(self, sad=0, timeout=13, send_eoi=1, eos_mode=0, debug=False, reset=False, interfaces=[]): if os.geteuid() != 0: Logging.error("You need to have root privileges to run this script.") self.started = False exit(1) self.debug = debug self.reset = reset self.devices = {} self.started = True self.drivers = {} # We go through each driver and look at the attribute DEVICES which contains all devices the driver should be loaded for. for i in dir(Drivers.GPIB): if i[0] != "_" and i != "GenericDriver": driver = getattr(Drivers.GPIB, i) if hasattr(driver, "DEVICES"): self.drivers.update(driver.DEVICES) if self.debug: Logging.info("Drivers for following devices have been loaded: %s" % self.drivers) self.reset_usb_controller() # Interface ids are used to determine which usb connections need to be reset # Example: """ Bus 001 Device 006: ID 3923:709b National Instruments Corp. GPIB-USB-HS """ self.interfaces = ["3923:709b", "0957:0518"] + interfaces self.reset_interfaces() progress_bar = ProgressBar(30) discovered = {} for pad in range(0, 31): id = gpib.dev(0, pad, sad, timeout, send_eoi, eos_mode) try: driver_avaliable = False gpib.clear(id) gpib.write(id, "*IDN?") device_id = gpib.read(id, 1024).rstrip() for i in self.drivers: if i in device_id: self.devices[pad] = self.drivers[i](GPIBCommunicator(id, self.reset_interfaces), device_id) driver_avaliable = True if not driver_avaliable: self.devices[pad] = Drivers.GPIB.GenericDriver.GenericDriver(GPIBCommunicator(id, self.reset_interfaces), device_id) discovered[id] = device_id except gpib.GpibError: pass progress_bar.update(pad) for i in discovered: Logging.header("%s on %s" % (discovered[i], i - 16)) Logging.success("Discovery finished successfully!")
def write(self, command, keep_open=False, **kwargs): """Format string and send it to the device Depending on the connection the command string can be send directly to the device or has to formatted first. Args: command (str): Command that is send to the device keep_open (bool, optional): Keep port open at the end """ if self._backend == "usbtmcWR": keep_open = True self._open() if self._backend == 'pySerial': if not self._port.is_open: self._open() self._port.write( bytes('{0}{1}'.format(command, self._write_termination), 'utf-8')) elif self._backend == 'pyVISA': self._port.write(command) elif self._backend == 'linux-gpib': gpib.write(self._port, command) elif self._backend == 'pyDAQmx': self._port = Task() self._port.CreateDOChan(self._connection['port'], "", DAQmx_Val_ChanForAllLines) self._port.StartTask() self._port.WriteDigitalLines(1, 1, 10.0, DAQmx_Val_GroupByChannel, command, None, None) self._port.StopTask() elif self._backend == 'file': try: with open(self._port, "w") as writer: writer.write(str(command)) except OSError as error_object: self.log.warning(error_object) elif self._backend in ['usbtmc', 'usbtmcWR']: self._port.write('{0}{1}'.format(command, self._write_termination)) elif self._backend == 'vxi11': self._port.write(command) elif self._backend == 'modbus': modbus_write(self._port, command, **kwargs) if not keep_open: self._close()
def scanGpib(board): if not has_gpib: warnings.warn( "Linux-GPIB is not available. ScanGpib with VISA not implemented at the moment.", RuntimeWarning, stacklevel=2, ) else: for pad in range(1, 31): listen = gpib.listener(board, pad) # print(board, pad, listen) if listen: print("GPIB" + str(board) + "::" + str(pad)) try: ud = gpib.dev(board, pad, 0, 10, 1, 0) if ud > 0: gpib.write(ud, "*CLS;*IDN?") description = gpib.read(ud, 256) print(description.strip().decode("ascii")) except Exception: pass
def update(self): """ updates the DMM; set the mode variable appropriately: 0 = returns DMM to the local display (voltage) 1 = DMM display in TORR 2 = DMM display in buffer gas density """ # read voltage self.V = float(gpib.read(self.dmm, self.__bytes__)) self.torr = (self.V - self.calib[0])\ * (self.atm/(self.calib[1]-self.calib[0])) # read temperature self.Tsensor.write('CDAT?\n') self.T = float(self.Tsensor.readline()) # calculate density. 100^3 necessary to bring the density to # 1/cm^3 that we are used to. self.dens = (self.torr * self.pascalPerTorr) / \ (1000000 * self.boltzmann * self.T) if self.mode == 2: gpib.write(self.dmm, "D2%.4E %s\r\n" % (self.dens,self.BGUnit)) elif self.mode == 1: gpib.write(self.dmm, "D2%.5f %s\r\n" % (self.torr,self.unit)) elif self.mode == 0: gpib.write(self.dmm, "D1\n")
def hpsetV(self,v): gpib.write(self.hp6633a ,"VSET " + str(v)) time.sleep(0.5) gpib.write(self.hp6633a,"VOUT?") time.sleep(0.1) v_meas=gpib.read(self.hp6633a,100) v_meas = float(v_meas.rstrip()) gpib.write(self.hp6633a,"IOUT?") time.sleep(0.1) i_meas=gpib.read(self.hp6633a,100) i_meas = float(i_meas.rstrip()) return(v_meas,i_meas)
def __init__(self, query=None, command=None, FORCE=False, filename=None, SAVE=True): ### establish GPIB communication ### self.scope = gpib.dev(0, 05) #gpib.write(scope,'ZERO') #gpib.write(scope,'ZERO?') #gpib.read(scope,1000) ### establish settings ### # gpib.write(self.scope,'ZERO') gpib.write(self.scope, 'Filter FAST') gpib.write(self.scope, 'RANGE:AUTO 1') gpib.write(self.scope, 'WAVE 980') if query: # to execute command from outside print '\nAnswer to query:', query self.write(query + '\n') rep = self.read() print rep, '\n' sys.exit() elif command: self.command = command print '\nExecuting command', self.command self.scope.write(self.command) print '\n' sys.exit() if filename: self.amp = self.get_power() ### TO SAVE ### if SAVE: temp = C.getoutput('ls').splitlines() # if file exist => exit for i in range(len(temp)): temp_filename = filename + 'fpm8210' if temp[i] == temp_filename: print '\nFile ', temp_filename, ' already exists, change filename or remove old file\n' sys.exit() f = open(filename + '_fpm8210', 'w') # Save data f.write(self.data) f.close()
def setlist(self, freqlist, powerlist, dt=0.010, adt=0.001): freqliststring = ', '.join(np.char.mod('%d', freqlist)) powerliststring = 'dBm, '.join(np.char.mod('%d', powerlist)) gpib.write(self.smiq, ':FREQ:MODE CW') gpib.write(self.smiq, ':FREQ '+str(np.mean(freqlist))) gpib.write(self.smiq, ':POW '+str(np.mean(powerlist))+'dBm') gpib.write(self.smiq, '*WAI') gpib.write(self.smiq, ':LIST:DELETE:ALL') gpib.write(self.smiq, ':LIST:SELECT \'MINION\'') gpib.write(self.smiq, ':TRIG1:LIST:SOURCE SINGLE') # single trigger an liste gpib.write(self.smiq, ':LIST:MODE AUTO') # liste einmal durchfahren gpib.write(self.smiq, ':LIST:DWELL '+str(dt+adt)) gpib.write(self.smiq, ':LIST:FREQ '+freqliststring) gpib.write(self.smiq, ':LIST:POW '+powerliststring) print('list set')
counterbins = res.to_bytes(2, byteorder='little') counter.write(b'B'+counterbins) #SetNumberOfTriggeredCountingBins triggermask = 8 triggerinvertmask = 8 counter.write(b'M'+(8).to_bytes(1, byteorder='little')) #SetTriggerMask counter.write(b'Q'+(8).to_bytes(1, byteorder='little')) #SetTriggerinvertedMask counter.write(b'K'+(1).to_bytes(4, byteorder='little')) #SetTriggeredCountingBinRepetitions counter.write(b'0') #ResetTriggeredCountingData counter.write(b'R') #EnableTriggeredCounting test = 0 try: gpib.write(smiq, '*RST') # nicht jedes mal machen - nur bei programmstart time.sleep(0.1) gpib.write(smiq, ':FREQ '+str(np.mean(freqlist))) gpib.write(smiq, ':POW '+str(np.mean(powerlist))+'dBm') gpib.write(smiq, ':LIST:DELETE:ALL') gpib.write(smiq, ':LIST:SELECT \'CWODMR\'') gpib.write(smiq, ':TRIG1:LIST:SOURCE SINGLE') # single trigger an liste gpib.write(smiq, ':LIST:MODE AUTO') # liste einmal durchfahren gpib.write(smiq, ':LIST:DWELL '+str(dt+adt)) gpib.write(smiq, ':LIST:FREQ '+freqliststring) gpib.write(smiq, ':LIST:POW '+powerliststring)
def write(self, str): gpib.write(self.id, str)
def rango(self, ra): cc = gpib.write(self.equipo, "R" + ra)
def write(self, data: str): gpib.write(self._handle, data)
def initialise_device(handle): # set up device to assert SRQ/RQS gpib.write(handle, "*CLS") # Clear status registers gpib.write(handle, "*SRE 32") # Assert SRQ on Event return
def query(handle, command, numbytes=100): gpib.write(handle, command) time.sleep(0.1) response = gpib.read(handle, numbytes) return response
# EXCLUDE ALL COMMENTED LINES for line in cflines: if line == '': continue elif line[0] == '#': continue else: commands.append(line) # IMPORT NEEDED MODULES import gpib # OPENING GPIB DEVICE (LASER) herring = gpib.find("laser") # SENDING COMMANDS TO DEVICE for comm in commands: gpib.write(herring, comm) # DISPLAY SETTINGS print('========================') print(' NEW SETTINGS ') print('========================') for comm in commands: gpib.write(herring, comm.split()[0] + ' ' + comm.split()[1]) print( str(gpib.read(herring, 1024)).replace('b\'', '').replace('\\r\'', '')) print('========================') ################################################################################
def liston(self): gpib.write(self.smiq, ':OUTP ON') gpib.write(self.smiq, ':LIST:LEARN') gpib.write(self.smiq, ':FREQ:MODE LIST') gpib.write(self.smiq, '*WAI')
import gpib, time, sys from datetime import datetime path = '.' ncycle = 100000 nmeas = 10 interval = 60 #secondo microampere = 1.e6 index = 0 #connect to picoammeter picoam = gpib.find("picoammeter") #initialize print('initialize picoammeter') gpib.write(picoam, "*RST") #reset settings gpib.write(picoam, "SYST:ZCH ON") #zero check gpib.write(picoam, "RANGE 2e-2") #set current range. -0.021-0.021 A gpib.write(picoam, "RANGE:AUTO OFF") #change current range manually gpib.write(picoam, "INIT") #read value of zero correction gpib.write(picoam, "SYST:ZCOR:ACQ") #acquire value of zero correction gpib.write(picoam, "SYST:ZCOR ON") #zero correction gpib.write(picoam, "SYST:ZCOR OFF") gpib.write(picoam, "SYST:ZCH OFF") #turn on HV gpib.write(picoam, "SOUR:VOLT:RANG 500") #set voltage range. (only 10, 50, 500 V) gpib.write( picoam, "SOUR:VOLT:ILIM 25") #set current limit. (only 25, 250, 2.5e-3, 25e-3 A)
def __init__(self, sad=0, timeout=13, send_eoi=1, eos_mode=0, debug=False, reset=False, interfaces=[]): if os.geteuid() != 0: Logging.error( "You need to have root privileges to run this script.") self.started = False exit(1) self.debug = debug self.reset = reset self.devices = {} self.started = True self.drivers = {} # We go through each driver and look at the attribute DEVICES which contains all devices the driver should be loaded for. for i in dir(Drivers.GPIB): if i[0] != "_" and i != "GenericDriver": driver = getattr(Drivers.GPIB, i) if hasattr(driver, "DEVICES"): self.drivers.update(driver.DEVICES) if self.debug: Logging.info("Drivers for following devices have been loaded: %s" % self.drivers) self.reset_usb_controller() # Interface ids are used to determine which usb connections need to be reset # Example: """ Bus 001 Device 006: ID 3923:709b National Instruments Corp. GPIB-USB-HS """ self.interfaces = ["3923:709b", "0957:0518"] + interfaces self.reset_interfaces() progress_bar = ProgressBar(30) discovered = {} for pad in range(0, 31): id = gpib.dev(0, pad, sad, timeout, send_eoi, eos_mode) try: driver_avaliable = False gpib.clear(id) gpib.write(id, "*IDN?") device_id = gpib.read(id, 1024).rstrip() for i in self.drivers: if i in device_id: self.devices[pad] = self.drivers[i](GPIBCommunicator( id, self.reset_interfaces), device_id) driver_avaliable = True if not driver_avaliable: self.devices[ pad] = Drivers.GPIB.GenericDriver.GenericDriver( GPIBCommunicator(id, self.reset_interfaces), device_id) discovered[id] = device_id except gpib.GpibError: pass progress_bar.update(pad) for i in discovered: Logging.header("%s on %s" % (discovered[i], i - 16)) Logging.success("Discovery finished successfully!")
def freq(self, freq=None): if freq != None: gpib.write(self.smiq, ':FREQ '+str(freq)) gpib.write(self.smiq, '*WAI') gpib.write(self.smiq, ':FREQ?') return float(gpib.read(self.smiq, 256))
def meas(): gpib.write(dc1, 'MEAS:CURR?') s = gpib.read(dc1, 1000) global t0 if t0 is None: t0 = datetime.datetime.now() t = datetime.timedelta(0) else: t = datetime.datetime.now() - t0 print('{}.{:06d},{}'.format(t.seconds, t.microseconds, s.decode().rstrip())) sys.stdout.flush() gpib.write(dc1, '*IDN?') s = gpib.read(dc1, 1000) print('#', s.decode().rstrip()) gpib.write(dc1, 'SENS:CURR:DET DC') gpib.write(dc1, 'SENS:CURR:DET?') s = gpib.read(dc1, 1000) print('#', s.decode().rstrip()) gpib.write(dc1, 'VOLT 5.0') gpib.write(dc1, 'VOLT?') s = gpib.read(dc1, 1000) print('#', s.decode().rstrip(), 'V') gpib.write(dc1, 'CURR 2.0') gpib.write(dc1, 'CURR?')
def set_inst(self, handle, command, numbytes=100): gpib.write(handle, command) time.sleep(0.1) return
def cw(self, freq=None, power=None): gpib.write(self.smiq, ':FREQ:MODE CW') if freq != None: gpib.write(self.smiq, ':FREQ '+str(freq)) if power != None: gpib.write(self.smiq, ':POW '+str(power))
def listrun(self): gpib.write(self.smiq, ':TRIG:LIST') # startet
def _write(self, cmd): if self._gpib_used: gpib.write(self._dev, cmd) else: self._dev.write(cmd.encode())
def setpower(self, power=None): if power != None: gpib.write(self.smiq, ':POW '+str(power))
def initialise_device(handle): # set up device to assert SRQ/RQS gpib.write(handle,"*CLS") # Clear status registers gpib.write(handle,"*SRE 32") # Assert SRQ on OPC return def show_devid(handle): # Show device ID print query(handle,"*IDN?") return print gpib.version() # Show package version ud = gpib.dev(board,device) # Open the device gpib.config(board,gpib.IbcTMO, gpib.T30s) # Set timeout to 30 seconds show_devid(ud); initialise_device(ud); gpib.write(handle,"*TST;*OPC") # Initiate selftest and request OPC # Wait for Timeout or Service Request on board sta = gpib.wait(board, gpib.TIMO | gpib.SRQI) if (sta & gpib.TIMO) != 0: print "Timed out" else: print "SRQ asserted " # For each device which might pull SRQ stb = gpib.serial_poll(ud) # Read status byte print "stb = %#x"%(stb) if (stb & gpib.IbStbRQS) != 0: # Check for RQS bit print "Device asserted RQS" if (stb & gpib.IbStbESB) != 0: # Check for Event Status bit esr = int(query(ud,"ESR?")) # Read Event Status Register if (esr & 1) != 0: # Check for operation completed print "Device Operation Completed"
def output_off(dev): gpib.write(dev, 'OUTP OFF')
def write(self, command): """Write a command to the GPIB bus.""" gpib.write(self.scope, command)
def power(self, power=None): if power != None: print(power) gpib.write(self.smiq, ':POW '+str(power)) gpib.write(self.smiq, ':POW?') return float(gpib.read(self.smiq, 256))
gpib.write(handle, "*SRE 32") # Assert SRQ on Event return def show_devid(handle): # Show device ID print query(handle, "*IDN?") return print gpib.version() # Show package version ud = gpib.dev(board, device) # Open the device gpib.config(board, gpib.IbcAUTOPOLL, 1) # Enable automatic serial polling gpib.config(ud, gpib.IbcTMO, gpib.T30s) # Set timeout to 30 seconds show_devid(ud) initialise_device(ud) gpib.write(handle, "*TST;*OPC") # Selftest and request OPC event # Wait for Timeout or Request Service on device sta = gpib.wait(ud, gpib.TIMO | gpib.RQS) if (sta & gpib.TIMO) != 0: print "Timed out" else: print "Device asserted RQS" stb = gpib.serial_poll(ud) # Read status byte print "stb = %#x" % (stb) if (stb & gpib.IbStbESB) != 0: # Check for Event Status bit esr = int(query(ud, "ESR?")) # Read Event Status Register if (esr & 1) != 0: # Check for operation completed print "Device Operation Completed" # done gpib.close(ud)
def preset(self): """Preset the instrument""" gpib.write(self.device, "IP") return()
def query(handle, command, numbytes=100): gpib.write(handle, command) response = gpib.read(handle, numbytes) response = response.rstrip("\r\n") return response
def sweep(self): """Take a sweep""" gpib.write(self.device, "TS") return()
def mandar(self, mensaje): bb = gpib.write(self.equipo, mensaje)
def on(self): gpib.write(self.smiq, ':OUTP ON') gpib.write(self.smiq, '*WAI')
def _write(self, message: str): gpib.write(self._device_handler, message + '\r')
def output(self): gpib.write(self.smiq, ':OUTP?') return gpib.read(self.smiq, 256)
def write( self, buf ): gpib.write( self.__interface, buf )
def connect(self): self.smiq = gpib.find('smiq06b') gpib.write(self.smiq, '*RST') print('smiq connected')
def disconnect(self): gpib.write(self.smiq, '*RST') gpib.close(self.smiq) print('smiq disconnected')
def __del__(self): print('smiq disconnected') gpib.write(self.smiq, '*RST') gpib.close(self.smiq)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Oct 28 20:57:10 2018 @author: jonathan """ import gpib import numpy as np # GPIB interface 0, address 15 con = gpib.dev(0,15) status = gpib.write(con, "COMM_FORMAT OFF") #status = gpib.write(con, "COMM_FORMAT OFF,WORD,BIN") status = gpib.write(con, "COMM_HEADER OFF") status = gpib.write(con, "*IDN?") deviceID = gpib.read(con, 1000).decode() print("found device: " + deviceID) # get template print("fetching template") status = gpib.write(con, "TEMPLATE?") template = "" chunk_size = 1024 keepFetching = True while keepFetching:
def setfreq(self, freq=None): if freq != None: gpib.write(self.smiq, ':FREQ '+str(freq))
def write(self,text): if self.eot: text += "\n" gpib.write(self.id, text)
def write(self, cmd): gpib.write(self.dev, '%s\n' % (cmd, ))