Exemple #1
0
def open_labjacks():
    global dm, dp, dp_connect, dm_connect
    try:
        if not dm_connect:
            # Open Mono Panels' LabJack
            dm = u3.U3(autoOpen=False)
            dm.open(handleOnly=True, serial=320090158)
            dm.configIO(FIOAnalog=255)  # Set every input to analog
            dm_connect = True
    except LabJackException:
        print("Connection Error to LabJack: Cannot find Mono LabJack")
        if dm:
            dm.close()
        if dp:
            dp.close()
        ws.send_err('Cannot find Mono LabJack')
        return False
    try:
        if not dp_connect:
            # Open Poly Panels' LabJack
            dp = u3.U3(autoOpen=False)
            dp.open(handleOnly=True, serial=320087751)
            dp.configIO(FIOAnalog=255)  # Set every input to analog
            # dp.writeRegister(5000, 3) # testing
            dp_connect = True
    except LabJackException:
        print("Connection Error to LabJack: Cannot find Poly LabJack")
        if dm:
            dm.close()
        if dp:
            dp.close()
        ws.send_err('Cannot find Poly LabJack')
        return False
    return True
Exemple #2
0
    def configure(self, channels=None):
        """Opens labjack and configures to read analog signals.

        channels - List of channel addresses to be read.
        e.g in channels = [0, 2, 15], then read AIN0, AIN2, AIN15
        """
        # initialize a labjack u3 device
        print("Getting a handle for LabJack")
        try:
            self.d = u3.U3()
        except LabJackPython.NullHandleException:
            print("Could not open device. Please check that the device you are trying to open is connected")
            sys.exit(1)

        # get the labjack configuration
        self.ljconfig = self.d.configU3()

        if(self.ljconfig['DeviceName'] != 'U3-HV'):
            print "Sorry, your device %s is not supported. Only U3-HV is supported" % self.ljconfig['DeviceName']
            sys.exit(1)

        # Configure all FIO pins to be analog
        # FIO pins are located on LabJack
        # for U3-HV, FI00-03 are equivalent to AIN0-3
        print "Configuring FI00-07 as analog inputs"
        self.d.writeRegister(FIO_ANALOG, 255)

        # Configure all EIO pins to be analog
        print "Configuring EI00-07 as analog inputs"
        self.d.writeRegister(EIO_ANALOG, 255)

        self.configureChannels(channels)
Exemple #3
0
def getWaterFR(time, i):
    print("in getWaterFR")
    d = u3.U3(
    )  # initializing a u3 object to read the voltage on the LabJack U3-LV port
    d.debug = True
    d.getCalibrationData()
    d.configIO(FIOAnalog=15)
    voltage = d.getAIN(
        1
    )  # gets the voltage; getAIN seems to be better than reading the bits and converting, since it automatically changes the bits to volts for you
    waterFR[i] = (
        voltage - 0.5
    ) / 0.119  # hardcoded the relationship in; as of August 24, 2018, the calculated flow rate seems to be about 0.2 lower than the actual flow rate displayed on the monitor
    d.close()

    ## saving to the data file ##
    file_WaterFR = open(file_WaterFR_Name, 'a')
    file_WaterFR.write(time + "," + "{:5.3f},\n".format(waterFR[i]))
    file_WaterFR.close()

    ## live editing Environment-Data with the most recent value of the flow rate ##
    with open('cryo-Environment-Data.dat', 'r') as environ:
        data = environ.readlines()

    ## HARDCODED the position where the flow rate is!! ##
    data[29] = data[29][:data[29].index("=") + 1] + " " + "{:5.3f}\n".format(
        waterFR[i])

    with open('cryo-Environment-Data.dat', 'w') as environ:
        environ.writelines(data)
    print("exiting getWaterFR")
    def start(self):
        """
        Name:MainWindow.start()
        Desc:Starts reading values from EI1050 probe
        """
        try:
            # Get device selection
            if len(LabJackPython.listAll(3)) > 0:
                self.device = u3.U3()
            elif len(LabJackPython.listAll(6)) > 0:
                self.device = u6.U6()
            else:
                self.device = ue9.UE9()

            self.serialDisplay.config(text=self.device.serialNumber)

            # Create and start the thread
            self.thread = ei1050.EI1050Reader(self.device, self.targetQueue)

            # Start scheduleing
            self.window.after(1000, self.updateLabels)
            self.thread.start()

            # Change button
            self.startButton.config(text="Stop", command=self.stop)
        except:
            showErrorWindow(sys.exc_info()[0], sys.exc_info()[1])
Exemple #5
0
    def __init__(self):
        """
		Lab Jack interface for thermocouple.
		"""

        # Default system parameters.
        self.__u3Channel = 0
        self.__vOffset = 0.4
        self.__gainSetting = 51
        self.__tempUnits = 'C'
        self.__tcType = 'K'
        self.__debug = False
        self.__logData = False

        # Counters
        self.__sid = 0  # Sample ID

        # Temperature conversion matrix.
        self.__converter = {'K': float, 'C': self.__kToC, 'F': self.__kToF}

        try:
            # Set up library for a type K thermocouple.
            self.__tc = None
        except:
            raise

        try:
            # Create LabJack U3 object and set debugging.
            self.__u3 = u3.U3()
        except:
            raise
Exemple #6
0
    def __init__(self):

        
        self.d = u3.U3()
        self.d.getCalibrationData()
        
        FIOAnalogChans = 0
        EIOAnalogChans = 0
        fios = FIOAnalogChans & 0xFF  
        eios = EIOAnalogChans & 0xFF  
        self.d.configIO(FIOAnalog=fios, EIOAnalog=eios)
        
        self.d.getFeedback(u3.PortDirWrite(Direction=[0, 0, 0], WriteMask=[0, 0, 15]))
#        print("Before Feedback")
        #Pin 0 (FIO0) Hold low to select Valves 0-15 on the Valve Master 2000 Board
        self.d.getFeedback(u3.BitStateWrite(IONumber=8, State = 0))
        #Pin 1 (FIO1) Hold low to enable output
        self.d.getFeedback(u3.BitStateWrite(IONumber=9, State = 0))
        #Pin 2 (FIO2) Set Low to disable H-Bridge Drivers Port A (Open Valve)
        self.d.getFeedback(u3.BitStateWrite(IONumber=10, State = 0))
        #Pin 3 (FIO3) Set Low to disable H-Bridge Drivers Port B (Close Valve)
        self.d.getFeedback(u3.BitStateWrite(IONumber=11, State = 0))
        self.d.getFeedback(u3.BitStateWrite(IONumber=12, State = 0))
        self.d.getFeedback(u3.BitStateWrite(IONumber=13, State = 0))
        self.d.getFeedback(u3.BitStateWrite(IONumber=14, State = 0))
        self.d.getFeedback(u3.BitStateWrite(IONumber=15, State = 0))
Exemple #7
0
def init_daq(debug=False):
    d = u3.U3()
    d.debug = debug

    #----------------------------------
    # Configure the counter channel
    #----------------------------------
    # TimerCounterPinOffset specifies the number of lines
    #            above FIO0 for the counter.  MUST BE in [4,8].
    #            Assuming that no timers are in play, then
    #            4 --> Counter0 on FIO4
    #            5 --> Counter0 on FIO5
    #            6 --> Counter0 on FIO6
    #            7 --> Counter0 on FIO7
    #            8 --> Counter0 on EIO0
    #            9 --> Counter0 on EIO0
    # FIOAnalog  Each bit sets whether that FIO line is analog input (=1)
    #            or digital I/O (=0)
    # EIOAnalog  Same as fioAnalog, but for the EIO lines
    pinOffset = 8
    fioAnalog = 0
    eioAnalog = 0
    d.configIO(EnableCounter0=True,
               FIOAnalog=fioAnalog,
               EIOAnalog=eioAnalog,
               TimerCounterPinOffset=pinOffset)
    return d
Exemple #8
0
 def openu3(self):
     print 'Opening LabJack...'
     try:
         self.dac = u3.U3()
         print 'Done'
     except:
         print 'The device may be not connected'
    def __init__(self, timeout=0.5):
        """Opens U3 and performs initialization tasks.
        Parameters:
        timeout:  Determines how long access will be tried before timing out
            due to an existing lock on the device.
        """

        self.timeout = timeout
        self.dev = u3.U3()  # open U3
        self.dev.getCalibrationData()  # get the calibration data

        # Configure the U3 for this project.  This sets the power up
        # defaults as well. Found that I had to call configIO() even
        # though I already called configU3 (which sets power on defaults).
        # FI0-3 set to Analog Inputs, FI4-7 set to Digital Inputs
        # (so power up doesn't turn on SSR)
        # EI0-7 set to Analog Inputs
        self.dev.configU3(
            FIOAnalog=0x0F,
            EIOAnalog=0xFF,
            FIODirection=0x00,
        )
        self.dev.configIO(
            FIOAnalog=0x0F,
            EIOAnalog=0xFF,
        )

        # This is the variable that will control access to the U3.
        # If True, device is locked (in use).
        self.access_lock = False
Exemple #10
0
    def loadDevice(self, deviceType):
        """
        Name: loadDevice(deviceType)
        Desc: loads the first device of device type
        """

        self.deviceType = deviceType

        # Determine which device to use
        if self.deviceType == LJTickDAC.U3:
            self.device = u3.U3()
        elif self.deviceType == LJTickDAC.U6:
            self.device = u6.U6()
        else:
            self.device = ue9.UE9()

        # Display serial number
        self.serialDisplay.config(text=self.device.serialNumber)

        # Configure pins if U3
        if self.deviceType == LJTickDAC.U3:
            self.device.configIO(
                FIOAnalog=15,
                TimerCounterPinOffset=8)  # Configures FIO0-2 as analog

        # Get the calibration constants
        self.getCalConstants()
Exemple #11
0
    def __init__(self):
        # Have to ensure u3 isn't imported unless the U3Port is explicitly needed
        import u3
        # from psychopy.hardware.labjacks import U3

        self.u3dev = u3.U3()  # noqa
        self.PortStateWrite = u3.PortStateWrite
Exemple #12
0
 def open(self, *args, **kw):
     try:
         self._device = u3.U3()
     except BaseException:
         self.warning('failed to create U3 device')
         return
     return True
Exemple #13
0
def main():
    f = open("cup.txt", "w")
    cup_number = raw_input("Enter cup number: ")
    cup_density = raw_input("Enter its density: ")
    #print "Cup no.: ", cup_number, "\n", "Density: ", cup_density
    f.write("Cup_number: ")
    f.write(cup_number)
    f.write("\nCup_density: ")
    f.write(cup_density)
    f.write("\n")

    # Set up LabJack
    d = u3.U3()
    # print d.configU3()
    AIN0_REGISTER = 0

    while True:
        sample = str(d.getAIN(0))
        now = str(datetime.datetime.now())
        print sample
        f.write(now)
        f.write(" ")
        f.write(sample)
        f.write("\n")
        time.sleep(0.1)
Exemple #14
0
 def open(self):
     if not self.is_open:
         self.device = u3.U3(autoOpen = False)
         self.device.open(serial = 320044118)
         self.device.getCalibrationData()
         self.device.configU3(FIOAnalog = 255, EIOAnalog = 255)
         self.is_open = True
Exemple #15
0
def labjackInit():
    try:
        device = u3.U3() #Open first found U3
    except:
        #Handle all exceptions here
        print "Error : labjack device non available"
    return device
Exemple #16
0
def main():

	#configure electronic load
	print 'Connecting to Agilent 6060B'
	el = mtest.Agilent6060B('Agilent6060B')
	el.set_input('ON')
	el.set_mode('CURRENT')

	#configure labjack
	print 'Connecting to LabJack'
	lj = u3.U3() 
	DisconnectCharger(lj)
	# Set ANALOG_INPUT_PORT to analog
	lj.configAnalog(ANALOG_INPUT_PORT)

	#bounds check on CURRENT_PROFILE durations
	for pair in CURRENT_PROFILE:
		if pair[1] < el.timeout:
			raise Exception('ERROR: all durations in CURRENT_PROFILE must be greater than %f. This is the minimum time required to set current on the electronic load.' % el.timeout)

	#set initial time
	startTime = time.time()

	#create output base filename (YYYYMMDD-HHMMSS)
	outputBaseFilename = 'battery-cycle-test-' + time.strftime("%Y%m%d") + '-' + time.strftime("%H%M%S")

	#create directory for output files
	os.mkdir(outputBaseFilename)

	#create summary file
	summaryFile = open(os.path.join(outputBaseFilename, 'summary.csv'), 'wb')
	summaryWriter = csv.writer(summaryFile, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL)
	WriteRow(summaryWriter, ['Charge Cycle', 'Number of Discharge Cycles'])

	chargeCycle = 0
	while True:
		el.set_input('ON')
		chargeCycle += 1
		#create output file
		outputFile = open(os.path.join(outputBaseFilename, 'charge-cycle-%d.csv' % chargeCycle), 'wb')
		writer = csv.writer(outputFile, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL)
		WriteRow(writer, ['Time (s)', 'Voltage (V)', 'Current (A)', 'Phase', 'Discharge Cycle'])
		dischargeCycle = 0
		print '\nCharge cycle: %d' % chargeCycle
		while ReadVoltage(lj) >= MIN_BATTERY_VOLTAGE:
			dischargeCycle += 1
			print '\nDischarge cycle: %d' % dischargeCycle
			ApplyCurrentProfile(el, lj, CURRENT_PROFILE, startTime, writer, dischargeCycle)
			print 'Recover voltage: %f' % ReadVoltage(lj)
			print '____________________________'
		el.set_current(0)
		el.set_input('OFF')
		WriteRow(summaryWriter, [chargeCycle, dischargeCycle])
		while ReadVoltage(lj) < CHARGED_BATTERY_VOLTAGE:
				ConnectCharger(lj)
				WriteRow(writer, [time.time()-startTime, ReadVoltage(lj), None, 'charge', None])
				print ReadVoltage(lj)
				time.sleep(CHARGE_SAMPLING_PERIOD)
		DisconnectCharger(lj)
Exemple #17
0
 def __init__(self):
     self.labjackModule = u3.U3()
     self.labjackModule.configTimerClock(
         2, 0
     )  #Clock configuration to 48 MHz (Default) according to Labjack user manual section 5.2.4
     self.labjackModule.configIO(
         EnableCounter1=1,
         TimerCounterPinOffset=6)  # Configure EIO-0 to act as counter (1)
Exemple #18
0
 def _init_u3(self):
     """initializes the U3. 
     
     This function requires the U3 being connceted to
     the computer.
     """
     self.d = u3.U3()
     self.d.configU3()
Exemple #19
0
 def __init__(self, chan, ser_num=None):
     try:
         u3.U3().close()
     except u3.LabJackException:
         print('caught LJ exception on close()')
     self.channels = []
     for dic in chan:
         self.channels.append({
             'adc_pin': dic['adc_in'],
             'load_pin': dic['load_enable'],
             'load': dic['load_ohms'],
             'enabled': False
         })
     self.dacq = u3.U3()
     #self.dacq.open(serial=ser_num)
     self.dacq.configU3(FIOAnalog=0xFF, EIODirection=0xFF, EIOState=0x00)
     self.dacq.configIO(FIOAnalog=0xFF, EIOAnalog=0)
Exemple #20
0
 def _get_device(self):
     device = None
     try:
         device = u3.U3()
     except LabJackPython.LabJackException as e:
         self.status = e.errorString
     else:
         self.status = "OK"
     return device
Exemple #21
0
 def __init__(self, use_labjack):
     if use_labjack == 'true':
         import u3
         self.labjack = u3.U3()
         self.u3 = u3
         # enable counter for GPS pulse
         self.labjack.configIO(TimerCounterPinOffset=5,
                               EnableCounter0=True,
                               NumberOfTimersEnabled=1)
def connect_labjack():
    '''Documentation for this method
    
    '''

    print('connecting to u3 device')
    device = u3.U3()
    print('getting calibration data')
    device.getCalibrationData()
    return device
	def __init__(self, samplingRate=2000.0, dig_callback=None):
		"""Setup a LabJack U3 for multithreaded sampling.

		Open the LabJack using standard LabJack library calls, then
		instantiate this specifying the deviceHandle (really object
		you get back from u3.U3()) and optional samplingRate in Hz.

		Should be instantiated in main thread -- signals be caught
		by the main thread!

		If dig_callback is provided, then the callback function will
		be called when the DIN lines change state with two args: (self
		(this object), event-details). Either callback OR signals will
		happen, not both: callback, if defined, otherwise signal. In
		both cases, this will only happen if `running` and din_alerts
		are enabled!

		"""
		self.d = u3.U3()			# take first available U3
		self.samplingRate = samplingRate

		self.config = self.d.configU3()
		self.frags = []
		self.nsamps_ad = 0
		self.running = 0
		self.nrunning = 0
		self.errorcount = 0
		self.fragstart_host = None
		self.dig_callback = dig_callback

		# setup a timer on EIO0 (DB15) -- timers use an EIO or FIO line.
		# offset of 8 pushed it to the DB15 connector...
		self.d.configIO(TimerCounterPinOffset=8,
						NumberOfTimersEnabled=2)

		# timer0 as "system timer low" (mode 10; low 32bits of 4mhz clk)
		# timer1 as "system timer high" (mode 11; high 32bits of 4mhz clk)
		self.d.getFeedback(u3.TimerConfig(timer=0, TimerMode=10,
										  Value=0),
						   u3.TimerConfig(timer=1, TimerMode=11,
										  Value=0))

		# Set up streaming acquisition:
		#	Acquire 6 channels of two clocks + AIN (0-3) at max gain, at
		#   specified sampling rate (default: 2.0 kHz)
		self.d.streamConfig(NumChannels=6,
							PChannels=[200, 224,  0,  1,  2,  3],
							NChannels=[	 0,	  0, 31, 31, 31, 31],
							SampleFrequency=self.samplingRate)

		# configure FIO4-6 for Digital I/O
		self.d.writeRegister(6104, 1)		# Dig OUT
		self.d.writeRegister(6105, 1)		# Dig OUT
		self.d.writeRegister(6106, 0)		# Dig IN
		self.d.writeRegister(6107, 0)		# Dig IN
Exemple #24
0
    def load(self, *args, **kw):
        self._dio_mapping = {}

        try:
            self._device = u3.U3()
        except NullHandleException:
            return

        config = self.get_configuration()
        if config:
            return self.load_additional_args(config)
Exemple #25
0
 def __init__(self):
     self.live = True
     try:
         self.device = u3.U3()
     except:
         self.live = False
     if not self.live:
         print "Could not connect to Labjack, reset by unplugging / plugging the USB connection"
     else:
         self.device.writeRegister(6004, 0)  # set FIO4 state to low.
         self.device.configTimerClock(TimerClockBase=5, TimerClockDivisor=1)
Exemple #26
0
    def update(self):
        super().update()
        device = u3.U3()
        chan = u3.DAC0_8
        chan_value = device.voltageToDACBits(
            self.voltage_out, dacNumber=0, is16Bits=False
        )
        device.getFeedback(chan(chan_value))

        device.configIO(FIOAnalog=15)
        self.voltage_in_thermo = device.getAIN(2, 32)
        self.voltage_in_peltier = device.getAIN(1, 32)
Exemple #27
0
 def Loop(self):
   self.u3 = u3.U3()
   # AIN0-3 are always analog but we need to set FIO4-7 to analog before we can
   # read voltages on these terminals.
   self.u3.configIO(FIOAnalog = 0b11111111)
   self.Set5vOutput()
   frequency_hz = int(
       self.config.get('labjack', {}).get('frequency_hz')) or 10
   while not self.stop_process_signal.value:
     cycle_time = time.time()
     self.ReadValues()
     time.sleep(sensor.SleepBasedOnHertz(cycle_time, frequency_hz))
Exemple #28
0
    def getLocalLabJack(self):
        """
    Name: edges.getLocalLabJack()

    Args: N/A

    Desc: Returns the handle to the local LabJack  
    """
        if self.labjack == None:
            self.labjack = u3.U3()

        return self.labjack
Exemple #29
0
 def __init__(self, ):
     self.u = u3.U3()
     self.u.getCalibrationData()
     self.clockSpeed = 48e6  # 48 MHz
     self.clockDivisor = 7  # gets the correct PWM output
     self.u.configIO(NumberOfTimersEnabled=2,
                     EnableCounter1=1,
                     TimerCounterPinOffset=4)
     self.u.getFeedback(u3.TimerConfig(timer=1, TimerMode=3))
     self.u.getFeedback(u3.TimerConfig(timer=0, TimerMode=1, Value=0))
     # self.u.configTimerClock(TimerClockBase=6, TimerClockDivisor=7) # 187500/7 = 26785.7 Hz
     self.u.configTimerClock(TimerClockBase=2)  # needed for smooth
def stimulate():
    import u3  # Open the first found LabJack U3
    vibrator = u3.U3()  # defines vibrator variable as u3 labjack
    FIO4_STATE_REGISTER = 6004  # defines which connection will be used to deliver power to vibrator
    vibrator.writeRegister(FIO4_STATE_REGISTER,
                           1)  # Deliver voltage to FIO4 to power the vibrator
    time.sleep(
        0.15)  # wait for 0.15 seconds, the length of the stimulus vibration
    t = time_stamp()
    stim_stamp.append(t)
    print stim_stamp
    vibrator.writeRegister(FIO4_STATE_REGISTER,
                           0)  # Deliver voltage to FIO4 to power the vibrator