Ejemplo n.º 1
0
    def switch_noise(self, pol, state):
        """Set he bit in the LJ T7 to turn the specified noise source on or off.

        Args:
            pol (str): 'a' or 'b' according to the requested polarization.
            state (str): 'on' or 'off'
        """
        if state is False:
            state_val = 1
        elif state is True:
            state_val = 0
        else:
            msg = "Ant {}: Invalid noise diode state requested: {}".format(
                self.ant_num, state)
            CustomFormatter.log_msg_fmt['class'] = self.class_name
            self.logger.info(msg)
            return
        if pol == 'a':
            msg = "Ant {}: Turning polarization A noise diode {}".format(
                self.ant_num, state)
            ljm.eWriteName(self.lj_handle, Constants.NOISE_A, state_val)
        elif pol == 'b':
            msg = "Ant {}: Turning polarization B noise diode {}".format(
                self.ant_num, state)
            ljm.eWriteName(self.lj_handle, Constants.NOISE_B, state_val)
        else:
            msg = "Ant {}: Invalid noise diode state requested: {}".format(
                self.ant_num, pol)
        CustomFormatter.log_msg_fmt['class'] = self.class_name
        self.logger.info(msg)
Ejemplo n.º 2
0
 def set_cmd(self, *cmd):
   """
   Convert the tension value to a digital value and send it to the output.
   """
   for command,channel,gain,offset in zip(
       cmd,self.out_channels,self.out_gain,self.out_offset):
     ljm.eWriteName(self.handle, channel, command*gain+offset)
 def Set_Anode(self):
     if not self.IsConnected:
         self.ErrorText = "Not connected, not setting Anode."
         self.UpdateErrorText()
         return
     DAC0_Entry_String = self.DAC0_Entry.get(
     )  # read value from entry field
     self.VAnode_setting = 0.  # placeholder
     # check if it is a number
     try:
         self.VAnode_setting = float(DAC0_Entry_String)
     except ValueError:
         self.ErrorText = "Error getting entry for DAC0, value was {}".format(
             DAC0_Entry_String)
         self.UpdateErrorText()
         return
     # enforce limits on VAnode
     if self.VAnode_setting > 5.:
         self.ErrorText = "Can't set Anode voltage {} > 5. kV".format(
             self.VAnode_setting)  # limit of 5 kV based on Bertan supply
         self.UpdateErrorText()
         return
     if self.VAnode_setting < 0.:
         self.ErrorText = "Can't set Anode volts {} < 0. kV".format(
             self.VAnode_setting)
         self.UpdateErrorText()
         return
     self.DAC_volts[
         0] = self.VAnode_setting  # conversion is 1 V remote per 1 kV on anode
     ljm.eWriteName(self.handle, "DAC0", self.DAC_volts[0])
     # update reporting
     self.DAC0_Var.set("{:.3f}".format(self.DAC_volts[0]))
     self.VAnode_Var.set("{:.3f}".format(self.VAnode_setting))
     return
def main():
    try:
        luaScript = """-- Use USER_RAM0_U16 (register 46180) to determine which control loop to run
                    local ramval = 0
                    MB.W(46180, 0, ramval)
                    local loop0 = 0
                    local loop1 = 1
                    local loop2 = 2

                    -- Setup an interval to control loop execution speed. Update every second
                    LJ.IntervalConfig(0,1000)
                    while true do
                      if LJ.CheckInterval(0) then
                        ramval = MB.R(46180, 0)

                        if ramval == loop0 then
                          print("using loop0")
                        end

                        if ramval == loop1 then
                          print("using loop1")
                        end

                        if ramval == loop2 then
                          print("using loop2")
                        end

                      end
                    end"""
        # Open first found LabJack
        handle = ljm.openS("ANY", "ANY",
                           "ANY")  # Any device, Any connection, Any identifier
        #handle = ljm.openS("T7", "ANY", "ANY")  # T7 device, Any connection, Any identifier
        #handle = ljm.openS("T4", "ANY", "ANY")  # T4 device, Any connection, Any identifier
        #handle = ljm.open(ljm.constants.dtANY, ljm.constants.ctANY, "ANY")  # Any device, Any connection, Any identifier

        info = ljm.getHandleInfo(handle)
        print(
            "Opened a LabJack with Device type: %i, Connection type: %i,\n"
            "Serial number: %i, IP address: %s, Port: %i,\nMax bytes per MB: %i"
            % (info[0], info[1], info[2], ljm.numberToIP(
                info[3]), info[4], info[5]))

        loadLuaScript(handle, luaScript)
        print("LUA_RUN %d" % ljm.eReadName(handle, "LUA_RUN"))
        print("LUA_DEBUG_NUM_BYTES: %d" %
              ljm.eReadName(handle, "LUA_DEBUG_NUM_BYTES"))
        readLuaInfo(handle)
        # Close handle
        ljm.close(handle)
    except ljm.LJMError:
        ljm.eWriteName(handle, "LUA_RUN", 0)
        # Close handle
        ljm.close(handle)
        raise
    except Exception:
        ljm.eWriteName(handle, "LUA_RUN", 0)
        # Close handle
        ljm.close(handle)
        raise
Ejemplo n.º 5
0
    def ljtick_dac_set_analog_out(self, port, voltage):
        """ Writes the analog output voltage to the LJTick DAC 0 to 10 V.

        :param port: "A" or "B", type <str>
        :param voltage: output voltage 0-10V, type <float>
        :return: Labjack I2C acknowledgement (Acked if non-zero value)
        :exception TypeError: if port is not string or voltage is not float
        :exception ValueError: if port is invalid or voltage is out of range
        :exception LJMError: An error was returned from the LJM library call
        """

        # check input parameters
        if not isinstance(port, str) or not isinstance(voltage, float):
            raise TypeError

        if voltage < -10 or voltage > 10:
            raise ValueError

        # Generate write statement. Even TDAC# is DACA, odd TDAC# is DACB
        # Labjack doc: For instance, if LJTick-DAC is connected to FIO6/FIO7 block on main device:
        # TDAC6 corresponds with DACA, and TDAC7 corresponds with DACB.
        if port == "A":
            write = str("TDAC" + str(Parameters.LJ_TICK_DAC_DOUT_SCL))
        elif port == "B":
            write = str("TDAC" + str(Parameters.LJ_TICK_DAC_DOUT_SDA))
        else:
            raise ValueError

        # try to write value
        try:
            ljm.eWriteName(self.connection_handle, write, voltage)
        except (TypeError, LJMError):
            self.connection_state = False
            self.close_connection()
            return False
Ejemplo n.º 6
0
def falling_edge_count(handle, IO):
    #Sets selected IO as falling edge counter
    ljm.eWriteName(handle,str(IO)+"_EF_ENABLE",0)
    ljm.eWriteName(handle,str(IO)+"_EF_INDEX",9)
    ljm.eWriteName(handle,str(IO)+"_EF_CONFIG_A",20000)
    ljm.eWriteName(handle,str(IO)+"_EF_CONFIG_B",0)
    ljm.eWriteName(handle,str(IO)+"_EF_ENABLE",1)
def readLuaInfo(handle):
    """Function that selects the current lua execution block and prints
       out associated info from lua

    """
    try:
        for i in range(20):
            # The script sets the interval length with LJ.IntervalConfig.
            # Note that LJ.IntervalConfig has some jitter and that this program's
            # interval (set by sleep) will have some minor drift from
            # LJ.IntervalConfig.
            sleep(1)
            print("LUA_RUN: %d" % ljm.eReadName(handle, "LUA_RUN"))
            # Add custom logic to control the Lua execution block
            executionLoopNum = i % 3
            # Write which lua control block to run using the user ram register
            ljm.eWriteName(handle, "USER_RAM0_U16", executionLoopNum)
            numBytes = ljm.eReadName(handle, "LUA_DEBUG_NUM_BYTES")
            if (int(numBytes) == 0):
                continue
            print("LUA_DEBUG_NUM_BYTES: %d\n" % numBytes)
            aBytes = ljm.eReadNameByteArray(handle, "LUA_DEBUG_DATA",
                                            int(numBytes))
            luaMessage = "".join([("%c" % val) for val in aBytes])
            print("LUA_DEBUG_DATA: %s" % luaMessage)
    except ljm.LJMError:
        print("Error while running the main loop")
        raise
def labjack_impulse():
	#ou would typically use LJM_eWriteNames() or LJM_eNames()
	#Pulse the valve
	ljm.eWriteName(handle,"FIO1",1)
	time.sleep(0.01)
	ljm.eWriteName(handle,"FIO1",0)
	print "send pulse"
 def Set_IBuck(self):
     if not self.IsConnected:
         self.ErrorText = "Not connected, not setting IBuck."
         self.UpdateErrorText()
         return
     DAC1_Entry_String = self.DAC1_Entry.get(
     )  # read value from entry field
     self.IBuck_setting = 0.  # placeholder
     # check if it is a number
     try:
         self.IBuck_setting = float(DAC1_Entry_String)
     except ValueError:
         self.ErrorText = "Error getting entry for DAC1, value was {}".format(
             DAC1_Entry_String)
         self.UpdateErrorText()
         return
     # enforce limits on Ibuck
     if self.IBuck_setting > 10.:
         self.ErrorText = "Can't set IBuck current {} > 10. A".format(
             self.IBuck_setting)
         self.UpdateErrorText()
         return
     if self.IBuck_setting < 0.:
         self.ErrorText = "Can't set IBuck current {} < 0. A".format(
             self.IBuck_setting)
         self.UpdateErrorText()
         return
     self.DAC_volts[
         1] = 0.1 * self.IBuck_setting  # conversion is 1 V = 10 A (max)
     ljm.eWriteName(self.handle, "DAC1", self.DAC_volts[1])
     # update reporting
     self.DAC1_Var.set("{:.3f}".format(self.DAC_volts[1]))
     self.IBuck_Var.set("{:.3f}".format(self.IBuck_setting))
     return
Ejemplo n.º 10
0
    def write_digital(self, port, value):
        """ Write a digital value ("HIGH" or "LOW") to a given port.

        :param port: Digital port to write a value
        :param value: Value to write, either "HIGH" or "LOW"
        :return: None
        :exception TypeError: if port or value is not string
        :exception ValueError: if value is not "HIGH" or "LOW"
        :exception LJMError: An error was returned from the LJM library call
        """

        # check input parameters
        if not isinstance(value, str) or not isinstance(port, str):
            raise TypeError

        # map input string to write value
        if value == "LOW":
            state = 0
        elif value == "HIGH":
            state = 1
        else:
            raise ValueError

        # try to write
        try:
            ljm.eWriteName(self.connection_handle, port, state)
        except (TypeError, LJMError):
            self.connection_state = False
            self.close_connection()
            return False
Ejemplo n.º 11
0
 def selectRFSource(self, list=["H","V"]):
     self.errorCheck()
     
     if "H" in list:
         ljm.eWriteName(self.handle, "EIO1", 0)
     if "V" in list:
         ljm.eWriteName(self.handle, "EIO2", 0)
Ejemplo n.º 12
0
    def _init_ant_labjack(self):
        """Initialize the LabJack T7 hardware.

        This function queries the antenna LabJack to get information about its hardware and
        software versions and states. It sets the range for the analog inputs, and the states of
        the digital IO (i.e., for each bit, input, output or tri-state). This is a safety measure,
        since these should be set in the power-up hardware defaults, and then also by the Lua
        script that should run on start-up.

        Returns:
            startup_mp (:obj:'dict'): A monitor point dictionary of values queried from the
            LabJack T7 on start up.
        """

        # Digital section
        # Input register for LabJack ID
        ljm.eWriteName(self.lj_handle, "FIO_DIRECTION", 0b00000000)
        # Output register for drive motor control
        ljm.eWriteName(self.lj_handle, "EIO_DIRECTION", 0b00011110)
        # Input register for drive status
        ljm.eWriteName(self.lj_handle, "CIO_DIRECTION", 0b00000000)
        # Input/output for noise source and fan
        ljm.eWriteName(self.lj_handle, "MIO_DIRECTION", 0b00000000)

        # Analog section
        # Input voltage range
        ljm.eWriteName(self.lj_handle, "AIN_ALL_RANGE", 10.0)

        # Query LabJack for its current configuration.
        startup_mp = sf.t7_startup_check(self.lj_handle)

        return startup_mp
Ejemplo n.º 13
0
 def switch_nd(self, pol_state):
     if len(pol_state) != 2:
         self.log_msg_q.put(
             (log.ERROR, MODULE,
              "Ant {}: Invalid number of noise diode arguments".format(
                  self.ant_num)))
         return
     (pol, state) = pol_state
     if state == 'off':
         state_val = 1
     elif state == 'on':
         state_val = 0
     else:
         msg = "Ant {}: Invalid noise diode state requested: {}".format(
             self.ant_num, state)
         self.log_msg_q.put((log.ERROR, MODULE, msg))
         return
     if pol == 'ab' or pol == 'both':
         msg = "Ant {}: Turning both polarizations noise diode {}".format(
             self.ant_num, state)
         ljm.eWriteNames(self.lj_handle, 1, [port.ND_A, port.ND_B],
                         [state_val, state_val])
     elif pol == 'a':
         msg = "Ant {}: Turning polarization a noise diode {}".format(
             self.ant_num, state)
         ljm.eWriteName(self.lj_handle, port.ND_A, state_val)
     elif pol == 'b':
         msg = "Ant {}: Turning polarization b noise diode {}".format(
             self.ant_num, state)
         ljm.eWriteName(self.lj_handle, port.ND_B, state_val)
     else:
         msg = "Ant {}: Invalid noise diode state requested: {}".format(
             self.ant_num, pol)
     self.log_msg_q.put((log.ERROR, MODULE, msg))
Ejemplo n.º 14
0
    def WriteRegister(self, name, value):
        with self.lock:
            if name not in self.driver.registers:
                raise LabJackException("%s not a register",
                                       LJD_NOT_A_VALID_REGISTER)

            type_info = self.driver._typeraw(name)
            print("Read: type_info for %s is %s" % (name, type_info))

            if 'W' not in self.driver.registers[name]['readwrite']:
                raise LabJackException("Cannot read %s" % name,
                                       LJD_REGISTER_NOT_WRITABLE)

            if type_info in ["INT16", "INT32", "UINT16", "UINT32"]:
                ljm.eWriteName(self.handle, name, int(value))

            elif type_info in ["STRING"]:
                value = ljm.eWriteNameString(self.handle, name, str(value))

            elif type_info in ["FLOAT32", "FLOAT64"]:
                value = ljm.eWriteName(self.handle, float(name))

            else:
                raise LabJackException(
                    "%s type unknown for %s" % (type_info, name),
                    LJD_UNKNOWN_TYPE)
Ejemplo n.º 15
0
    def motorRamp(self, start, target, direction):
        ljm.eWriteName(handle, "DIO" + str(motorDirectionPin), direction)
        while start < target:
            incrementFreq = (start / 60) * microstep
            self.generateUserPWM(
                motorPWM, incrementFreq, defaultDuty
            )  # Potentially change freq/duty based on desired RPM
            ljm.eWriteName(handle, "DIO" + str(motorDirectionPin), direction)
            time.sleep(1)
            start += 40

        # incrementFreq = (start / 60) * microstep
        # self.generateUserPWM(motorPWM, incrementFreq, defaultDuty)  # Potentially change freq/duty based on desired RPM
        # time.sleep(1)
        #
        # incrementFreq = (400 / 60) * microstep
        # self.generateUserPWM(motorPWM, incrementFreq, defaultDuty)  # Potentially change freq/duty based on desired RPM
        # time.sleep(1)
        #
        # incrementFreq = (550 / 60) * microstep
        # self.generateUserPWM(motorPWM, incrementFreq, defaultDuty)  # Potentially change freq/duty based on desired RPM
        # time.sleep(1)

        finalFreq = (target / 60) * microstep
        self.generateUserPWM(
            motorPWM, finalFreq,
            defaultDuty)  # Potentially change freq/duty based on desired RPM
Ejemplo n.º 16
0
    def lifeTestSuspend(self):
        global motorEnabled, lifeTestActive

        if not lifeTestActive:  #Test is not active, restart:
            print("Restarting life cycle test")
            motorEnabled = True
            lifeTestActive = True
            self.ui.lifeCycleSuspendBTN.setChecked(False)
            self.ui.lifeCycleSuspendBTN.setText("SUSPEND")
            self.ui.lifeCycleStartBTN.setDisabled(True)
            self.ui.lifeCycleStartBTN.setChecked(True)
            self.ui.lifeCycleStartBTN.setText("RUNNING")
            self.simpleLifeTest()  #Restart the test

        elif lifeTestActive:  # Test is live, shut it down
            print("Suspending life cycle test")
            motorEnabled = False
            lifeTestActive = False
            ljm.eWriteName(handle, "DAC" + str(motorEnablePin),
                           5)  # 0V high to disable
            ljm.eWriteName(handle, "DIO" + str(motorPWM) + "_EF_ENABLE",
                           0)  # Disable the EF system

            self.ui.lifeCycleSuspendBTN.setChecked(True)
            self.ui.lifeCycleSuspendBTN.setText("SUSPENDED")
            self.ui.lifeCycleStartBTN.setDisabled(False)
            self.ui.lifeCycleStartBTN.setChecked(False)
            self.ui.lifeCycleStartBTN.setText("START")
Ejemplo n.º 17
0
 def SetDigitalIO(name, high=True):
     if high not in [True, False]:
         logging.warning("labjackT7 error: high has to be True or False")
         return
     if high:
         eWriteName(self.handle, name, 1)
     else:
         eWriteName(self.handle, name, 0)
Ejemplo n.º 18
0
 def digital_output(self, channel, level):
     if channel not in range(8):
         raise BeamPatternArgumentError("LabJack T7",
                                        "channel should be >= 0 and <8")
     if level not in (0, 1):
         raise BeamPatternArgumentError("LabJack T7",
                                        "level should be 0 or 1")
     ljm.eWriteName(self.handle, 'FIO%1d' % channel, level)
Ejemplo n.º 19
0
    def _command(self, register, value):
        ''' Writes a value to a specified register.

            Args:
                register (str): a Modbus register on the LabJack.
                value: the value to write to the register.
                '''
        ljm.eWriteName(self.handle, register, value)
Ejemplo n.º 20
0
 def __setitem__(self,chan,val):
   """
   Allows setting of an output chan by calling lj[chan] = val
   """
   try:
     ljm.eWriteName(self.handle,chan,
       self.out_chan_dict[chan]['gain']*val+self.out_chan_dict[chan]['offset'])
   except KeyError:
     ljm.eWriteName(self.handle,chan,val)
Ejemplo n.º 21
0
def closeFunc():
    print("Closing")
    ljm.eWriteName(handle, "LUA_RUN", 0)
    waitingForStop = True
    while waitingForStop:
        print("Waiting for script to stop...")
        waitingForStop = ljm.eReadName(handle, "LUA_RUN") == 1

    ljm.close(handle)
Ejemplo n.º 22
0
    def ping_FIO(self, port, time_delay=0):
        """
        Sends a quick signal in the port, used to communicate with the hydra harp
        """

        #Different command then eWriteAddress, not entirely sure why
        ljm.eWriteName(self.handle, port, 1)
        time.sleep(time_delay)  #Might slow down the program
        ljm.eWriteName(self.handle, port, 0)
 def selectRFSource(self, list=["H","V"]):
     self.errorCheck()
     
     if "H" in list:
         ljm.eWriteName(self.handle, "EIO1", 0)
         self.noiseRFswitch['H'] = 0
     if "V" in list:
         ljm.eWriteName(self.handle, "EIO2", 0)
         self.noiseRFswitch['V'] = 0
def velocityToVoltage(velocityL,velocityR):
	maxVelocity=3000; #in mm/s
	minVelocity=0; #in mm/s
	maxVoltage=5; #in volts
	minVoltage=0;
	outputVoltageL=maxVoltage/maxVelocity*velocityL
	outputVoltageR=(maxVoltage-minVoltage)/(maxVelocity-minVelocity)*velocityR
#	print outputVoltageL, outputVoltageR
	ljm.eWriteName(handle, "DAC0", outputVoltageL)
	ljm.eWriteName(handle,"DAC1",outputVoltageR) ### fix
Ejemplo n.º 25
0
 def __setitem__(self, chan, val):
     """
 Allows setting of an output chan by calling lj[chan] = val
 """
     try:
         ljm.eWriteName(
             self.handle, chan, self.out_chan_dict[chan]['gain'] * val +
             self.out_chan_dict[chan]['offset'])
     except KeyError:
         ljm.eWriteName(self.handle, chan, val)
Ejemplo n.º 26
0
def DAC_wrting(Volt):
    name = "DAC0"
    aValue = [Volt]  # 2.5 V
    #    Shutter_open = 'n'
    #    Shutter_open = raw_input("Press Y to open the shutter and srart recording:").lower()
    #    print Shutter_open
    #    if Shutter_open == 'y':
    #        aValues[0] = int(raw_input("Enter the voltage"))
    ljm.eWriteName(handle, name, aValue[0])
    #        break
    return
Ejemplo n.º 27
0
    def connectLabjack(self):
        self.labjackHandle = ljm.openS("T7", "ANY", "ANY")
        info = ljm.getHandleInfo(self.labjackHandle)
        print(
            "Opened a LabJack with Device type: %i, Connection type: %i,\n"
            "Serial number: %i, IP address: %s, Port: %i,\nMax bytes per MB: %i"
            % (info[0], info[1], info[2], ljm.numberToIP(
                info[3]), info[4], info[5]))

        ljm.eWriteName(self.labjackHandle, "AIN_ALL_RANGE", 10.0)
        ljm.eWriteName(self.labjackHandle, "AIN_ALL_RESOLUTION_INDEX", 8)
Ejemplo n.º 28
0
    def _init_beb_labjack(self):
        """Check the configuration of the LJ T7 and set analog ranges.

        Returns:
            :obj:'dict': Dictionary of monitor points containing LJ T7 startup information.
        """
        startup_mp = sf.t7_startup_check(self.lj_handle)
        # Analog section
        # Input voltage range
        ljm.eWriteName(self.lj_handle, "AIN_ALL_RANGE", 10.0)
        return startup_mp
Ejemplo n.º 29
0
 def SetLJTickVoltage(self, name, voltage):
     """
     Set the voltage output of the LTTick DAC
     """
     if (voltage < 0) or (voltage > 10):
         logging.warning(
             "labjackT7 error: Set voltage LJTick out of range 0-10V")
         return
     else:
         logging.debug("Setting LJTICK to {0:.3f}V".format(voltage))
         eWriteName(self.handle, name, voltage)
Ejemplo n.º 30
0
def silenciador(x, peak):

    # print ("hola")
    for dato in peak:
        # print (dato)
        if (dato != 0):
            # end = datetime.now()
            ljm.eWriteName(handle, DIGITAL[x], 0)
            return (0)

    return (1)
Ejemplo n.º 31
0
def update_stream_out_buffer(handle, out_context):
    # Write values to the stream-out buffer. Note that once a set of values have
    # been written to the stream out buffer (STREAM_OUT0_BUFFER_F32, for
    # example) and STREAM_OUT#_SET_LOOP has been set, that set of values will
    # continue to be output in order and will not be interrupted until their
    # "loop" is complete. Only once that set of values have been output in their
    # entirety will the next set of values that have been set using
    # STREAM_OUT#_SET_LOOP start being used.

    out_names = out_context["names"]

    ljm.eWriteName(handle, out_names["loop_size"], out_context["state_size"])

    state_index = out_context["current_index"]
    error_address = -1
    current_state = out_context["states"][state_index]
    values = current_state["values"]

    info = ljm.getHandleInfo(handle)
    max_bytes = info[5]
    SINGLE_ARRAY_SEND_MAX_BYTES = 520
    if max_bytes > SINGLE_ARRAY_SEND_MAX_BYTES:
        max_bytes = SINGLE_ARRAY_SEND_MAX_BYTES

    NUM_HEADER_BYTES = 12
    NUM_BYTES_PER_F32 = 4
    max_samples = int((max_bytes - NUM_HEADER_BYTES) / NUM_BYTES_PER_F32)

    start = 0
    while start < len(values):
        num_samples = len(values) - start
        if num_samples > max_samples:
            num_samples = max_samples
        end = start + num_samples
        write_values = values[start:end]

        ljm.eWriteNameArray(handle, out_names["buffer"], num_samples,
                            write_values)

        start = start + num_samples

    ljm.eWriteName(handle, out_names["set_loop"], out_context["set_loop"])

    print("  Wrote " + \
        out_context["names"]["stream_out"] + \
        " state: " + \
        current_state["state_name"]
    )

    # Increment the state and wrap it back to zero
    out_context["current_index"] = (state_index + 1) % len(
        out_context["states"])
Ejemplo n.º 32
0
 def _init_labjack(self):
     # Analog section
     # Input voltage range
     ljm.eWriteName(self.lj_handle, "AIN_ALL_RANGE", 10.0)
     # Digital section
     # Input register for LabJack ID
     ljm.eWriteName(self.lj_handle, "FIO_DIRECTION", 0)
     # Output register for drive motor control
     ljm.eWriteName(self.lj_handle, "EIO_DIRECTION", 3)
     # Input register for drive status
     ljm.eWriteName(self.lj_handle, "CIO_DIRECTION", 0)
     # Input/output for noise diode and fan
     ljm.eWriteName(self.lj_handle, "MIO_DIRECTION", 3)
Ejemplo n.º 33
0
 def switch_brake(self, state):
     if type(state) is list:
         state = state[0]
     if state == 'off':
         msg = "Ant {}: Turning brake {}".format(self.ant_num, state)
         ljm.eWriteName(self.lj_handle, port.BRAKE, 0)
     elif state == 'on':
         msg = "Ant {}: Turning brake {}".format(self.ant_num, state)
         ljm.eWriteName(self.lj_handle, port.BRAKE, 1)
     else:
         msg = "Ant {}: Invalid brake state requested: {}".format(
             self.ant_num, state)
     self.log_msg_q.put((log.ERROR, MODULE, msg))
 def __init__(self,channel,enable=False,set = 23.0, gain_p = 2.0, gain_i = 0.1, gain_d = 1000):
     self.channel = channel
     self.enable = enable
     self.set = set
     self.gain_p = gain_p
     self.gain_i = gain_i
     self.gain_d = gain_d
     self.small_accumulator = 0
     self.accumulator = 0
     self.prev_sig = 0
     self.n_accum = 0
     ljm.eWriteName(handle, self.channel.output, ZEROV)
     self.rth = thermistor_resistance(set) #what the thermistor resistance should be at setpoint temp
Ejemplo n.º 35
0
def update_stream_out_buffer(handle, out_context):
    # Write values to the stream-out buffer. Note that once a set of values have
    # been written to the stream out buffer (STREAM_OUT0_BUFFER_F32, for
    # example) and STREAM_OUT#_SET_LOOP has been set, that set of values will
    # continue to be output in order and will not be interrupted until their
    # "loop" is complete. Only once that set of values have been output in their
    # entirety will the next set of values that have been set using
    # STREAM_OUT#_SET_LOOP start being used.

    out_names = out_context["names"]

    ljm.eWriteName(handle, out_names["loop_size"], out_context["state_size"])

    state_index = out_context["current_index"]
    error_address = -1
    current_state = out_context["states"][state_index]
    values = current_state["values"]

    info = ljm.getHandleInfo(handle)
    max_bytes = info[5]
    SINGLE_ARRAY_SEND_MAX_BYTES = 520
    if max_bytes > SINGLE_ARRAY_SEND_MAX_BYTES:
        max_bytes = SINGLE_ARRAY_SEND_MAX_BYTES

    NUM_HEADER_BYTES = 12
    NUM_BYTES_PER_F32 = 4
    max_samples = int((max_bytes - NUM_HEADER_BYTES) / NUM_BYTES_PER_F32)

    start = 0
    while start < len(values):
        num_samples = len(values) - start
        if num_samples > max_samples:
            num_samples = max_samples
        end = start + num_samples
        write_values = values[start:end]

        ljm.eWriteNameArray(handle, out_names["buffer"], num_samples, write_values)

        start = start + num_samples

    ljm.eWriteName(handle, out_names["set_loop"], out_context["set_loop"])

    print("  Wrote " + \
        out_context["names"]["stream_out"] + \
        " state: " + \
        current_state["state_name"]
    )

    # Increment the state and wrap it back to zero
    out_context["current_index"] = (state_index + 1) % len(out_context["states"])
Ejemplo n.º 36
0
def initialize_stream_out(handle, out_context):
    # Allocate memory on the T7 for the stream-out buffer
    out_address = convert_name_to_address(out_context["target"])
    names = out_context["names"]
    ljm.eWriteName(handle, names["target"], out_address)
    ljm.eWriteName(handle, names["buffer_size"], out_context["buffer_num_bytes"])
    ljm.eWriteName(handle, names["enable"], 1)

    update_stream_out_buffer(handle, out_context)
 def __setUpAttenuations(self, val):
     attDict = {1: "FIO1", 2: "FIO2", 3: "FIO3", 4: "FIO4", 5: "FIO5"}
     
     if val > 31:
         newVal = 63
     elif val < 0:
         newVal = 0
     else:
         newVal = math.ceil(val * 2)
         
     temp = newVal / 2.0
         
     if newVal % 2 == 1:
         ljm.eWriteName(self.handle, "FIO0", 1)
         newVal = (newVal - 1) / 2
     else:
         ljm.eWriteName(self.handle, "FIO0", 0)
         newVal = newVal / 2
     
     for i in range(1, 6):
         ljm.eWriteName(self.handle, attDict[i], newVal % 2)
         newVal /= 2
         
     return temp
Ejemplo n.º 38
0
handle = ljm.openS("ANY", "ANY", "ANY")
#handle = ljm.open(ljm.constants.dtANY, ljm.constants.ctANY, "ANY")


info = ljm.getHandleInfo(handle)
print("Opened a LabJack with Device type: %i, Connection type: %i,\n" \
    "Serial number: %i, IP address: %s, Port: %i,\nMax bytes per MB: %i" % \
    (info[0], info[1], info[2], ljm.numberToIP(info[3]), info[4], info[5]))


#set digital channels to low state
statelow=0
for i in range(0,8):
    num=str(i)
    chF="FIO"+num
    ljm.eWriteName(handle, chF, statelow)


# Setup Stream Out
OUT_NAMES = ["FIO_STATE", "DAC1", "DAC0"]
NUM_OUT_CHANNELS = len(OUT_NAMES)
outAddress = ljm.nameToAddress(OUT_NAMES[0])[0]

# Allocate memory for the stream-out buffer
ljm.eWriteName(handle, "STREAM_OUT0_TARGET", outAddress)
ljm.eWriteName(handle, "STREAM_OUT0_BUFFER_SIZE", 512)
ljm.eWriteName(handle, "STREAM_OUT0_ENABLE", 1)

# Write values to the stream-out buffer
ljm.eWriteName(handle, "STREAM_OUT0_LOOP_SIZE", 3)
ljm.eWriteName(handle, "STREAM_OUT0_BUFFER_U16", 0b1011) #FIO0 = high, FIO1-7 = low
Ejemplo n.º 39
0
 def setNoiseSourceOn(self):
     self.errorCheck()
     
     ljm.eWriteName(self.handle, "EIO0", 1)
Ejemplo n.º 40
0
#handle = ljm.open(ljm.constants.dtANY, ljm.constants.ctANY, "ANY")


info = ljm.getHandleInfo(handle)
print("Opened a LabJack with Device type: %i, Connection type: %i,\n" \
    "Serial number: %i, IP address: %s, Port: %i,\nMax bytes per MB: %i" % \
    (info[0], info[1], info[2], ljm.numberToIP(info[3]), info[4], info[5]))


# Setup Stream Out
OUT_NAMES = ["DAC0"]
NUM_OUT_CHANNELS = len(OUT_NAMES)
outAddress = ljm.nameToAddress(OUT_NAMES[0])[0]

# Allocate memory for the stream-out buffer
ljm.eWriteName(handle, "STREAM_OUT0_TARGET", outAddress)
ljm.eWriteName(handle, "STREAM_OUT0_BUFFER_SIZE", 512)
ljm.eWriteName(handle, "STREAM_OUT0_ENABLE", 1)

# Write values to the stream-out buffer
'''ljm.eWriteName(handle, "STREAM_OUT0_LOOP_SIZE", 6)
ljm.eWriteName(handle, "STREAM_OUT0_BUFFER_F32", 0.0) # 0.0 V
ljm.eWriteName(handle, "STREAM_OUT0_BUFFER_F32", 1.0) # 1.0 V
ljm.eWriteName(handle, "STREAM_OUT0_BUFFER_F32", 2.0) # 2.0 V
ljm.eWriteName(handle, "STREAM_OUT0_BUFFER_F32", 3.0) # 3.0 V
ljm.eWriteName(handle, "STREAM_OUT0_BUFFER_F32", 4.0) # 4.0 V'''
ljm.eWriteName(handle, "STREAM_OUT0_BUFFER_F32", 0.0) # 5.0 V

ljm.eWriteName(handle, "STREAM_OUT0_SET_LOOP", 1)

print("STREAM_OUT0_BUFFER_STATUS = %f" % (ljm.eReadName(handle, "STREAM_OUT0_BUFFER_STATUS")))
Ejemplo n.º 41
0
	def set_cmd(self,cmd):
		"""Convert the tension value to a digital value and send it to the output."""
		#self.out=(cmd/self.gain)-self.offset
		#out_a=c.comedi_from_phys(self.out,self.range_ds,self.maxdata) # convert the cmd to digital value
		self.out=(cmd*self.gain)+self.offset
		ljm.eWriteName(self.handle, self.channel, self.out)
Ejemplo n.º 42
0
names = ["AIN0"]
results = ljm.eReadNames(handle, numFrames, names)
read_signal[I] = results[0]
read_time[I] = time.time()
I += 1
 
for Integration_index in Integration_list:
    
    #SB.Init(spec,Integration_index,3)
    Process(target=SB_Init, args=(spec,Integration_index,3)).start()
    Process(target=SB_Main, args=(spec,1,handle)).start()
    
    Half_Cycle = No_Sample*(II) + No_Sample/2
    Full_Cycle = No_Sample*(II) + No_Sample
    
    ljm.eWriteName(handle, "DAC1", 5)       #Laser is on
    
    results = ljm.eReadNames(handle, numFrames, names)
    read_signal[I] = results[0]
    read_time[I] = time.time()
    I += 1
    II += 1
    print 'Integration_index: %i' %Integration_index
    while I < Half_Cycle:
        results = ljm.eReadNames(handle, numFrames, names)
        read_signal[I] = results[0]
        read_time[I] = time.time()
        I += 1    
    ljm.eWriteName(handle, "DAC0", 5)       #Shutter opens in ~22ms since now
    while I < Full_Cycle:
        if SB_Is_Done.value == 1:
 def __VQAttenLatch(self, newVal):
     ljm.eWriteName(self.handle, "CIO1", 1)
     self.__turnOffAllLatches()
     self.allAtt["VQ"] = newVal
Ejemplo n.º 44
0
''' ************** Initialization for the DAQT7 **************** '''
#DAC0 setup
# Setup and call eWriteName to write a value to the LabJack.
names = "DAC0"
aValues = [2.5] # 2.5 V

Shutter_open = 'n'
i = 10
while i  > 1:
    i = i - 1
    Shutter_open = raw_input("Press Y to open the shutter and srart recording:").lower()
    print Shutter_open
    if Shutter_open == 'y':
        aValues[0] = int(raw_input("Enter the voltage"))
        ljm.eWriteName(handle, names, aValues[0])
        break
    
#A2D setup
info = ljm.getHandleInfo(handle)
print("Opened a LabJack with Device type: %i, Connection type: %i,\n" \
    "Serial number: %i, IP address: %s, Port: %i,\nMax bytes per MB: %i" % \
    (info[0], info[1], info[2], ljm.numberToIP(info[3]), info[4], info[5]))
# Setup and call eWriteNames to configure AINs on the LabJack.
numFrames = 6
names = ["AIN0_NEGATIVE_CH", "AIN0_RANGE", "AIN0_RESOLUTION_INDEX",
         "AIN1_NEGATIVE_CH", "AIN1_RANGE", "AIN1_RESOLUTION_INDEX"]
aValues = [199, 10, 0,
           199, 10, 0]
ljm.eWriteNames(handle, numFrames, names, aValues)
Ejemplo n.º 45
0
from random import randrange


# Open first found LabJack
handle = ljm.openS("ANY", "ANY", "ANY")
#handle = ljm.open(ljm.constants.dtANY, ljm.constants.ctANY, "ANY")


info = ljm.getHandleInfo(handle)
print("Opened a LabJack with Device type: %i, Connection type: %i,\n" \
    "Serial number: %i, IP address: %s, Port: %i,\nMax bytes per MB: %i" % \
    (info[0], info[1], info[2], ljm.numberToIP(info[3]), info[4], info[5]))


# Configure the I2C communication.
ljm.eWriteName(handle, "I2C_SDA_DIONUM", 1) # SDA pin number = 1 (FIO1)
ljm.eWriteName(handle, "I2C_SCL_DIONUM", 0) # SCL pin number = 0 (FIO0)

# Speed throttle is inversely proportional to clock frequency. 0 = max.
ljm.eWriteName(handle, "I2C_SPEED_THROTTLE", 0) # Speed throttle = 0

# Options bits:
#   bit0: Reset the I2C bus.
#   bit1: Restart w/o stop
#   bit2: Disable clock stretching.
ljm.eWriteName(handle, "I2C_OPTIONS", 0) # Options = 0

ljm.eWriteName(handle, "I2C_SLAVE_ADDRESS", 80) # Slave Address of the I2C chip = 80 (0x50)


# Initial read of EEPROM bytes 0-3 in the user memory area. We need a single I2C
Ejemplo n.º 46
0
def Digital_Ports_Write(handle,Port,State):     
    ljm.eWriteName(handle, Port, State)
    #print int(round(time.time() * 1000))
    return
 def reboot(self):
     self.errorCheck()
     
     ljm.eWriteName(self.handle, "SYSTEM_REBOOT",
                    0x4C4A0000)
Ejemplo n.º 48
0
aValues = [ljm.ipToNumber("192.168.1.207"), ljm.ipToNumber("255.255.255.0"),
           ljm.ipToNumber("192.168.1.1")]
ljm.eWriteNames(handle, numFrames, names, aValues)

print("\nSet WiFi configuration:")
for i in range(numFrames):
    print("    %s : %.0f - %s" % \
        (names[i], aValues[i], ljm.numberToIP(aValues[i])))

# Setup and call eWriteString to configure the default WiFi SSID on the LabJack.
name = "WIFI_SSID_DEFAULT"
string = "LJOpen"
ljm.eWriteNameString(handle, name, string)
print("    %s : %s" % (name, string))

# Setup and call eWriteString to configure the default WiFi password on the
# LabJack.
name = "WIFI_PASSWORD_DEFAULT"
string = "none"
ljm.eWriteNameString(handle, name, string)
print("    %s : %s" % (name, string))

# Setup and call eWriteName to apply the new WiFi configuration on the LabJack.
name = "WIFI_APPLY_SETTINGS"
value = 1
ljm.eWriteName(handle, name, value)
print("    %s : %.0f" % (name, value))

# Close handle
ljm.close(handle)
Ejemplo n.º 49
0
"""

from labjack import ljm
from random import randrange

# Open first found LabJack
handle = ljm.open(ljm.constants.dtANY, ljm.constants.ctANY, "ANY")
#handle = ljm.openS("ANY", "ANY", "ANY")

info = ljm.getHandleInfo(handle)
print("Opened a LabJack with Device type: %i, Connection type: %i,\n" \
    "Serial number: %i, IP address: %s, Port: %i,\nMax bytes per MB: %i" % \
    (info[0], info[1], info[2], ljm.numberToIP(info[3]), info[4], info[5]))

# CS is FIO1
ljm.eWriteName(handle, "SPI_CS_DIONUM", 1)

# CLK is FIO0
ljm.eWriteName(handle, "SPI_CLK_DIONUM", 0)

# MISO is FIO3
ljm.eWriteName(handle, "SPI_MISO_DIONUM", 3)

# MOSI is FIO2
ljm.eWriteName(handle, "SPI_MOSI_DIONUM", 2)

# Selecting Mode CPHA=1 (bit 1), CPOL=1 (bit 2)
ljm.eWriteName(handle, "SPI_MODE", 3)

# Speed Throttle: Max. Speed (~ 1 MHz) = 0
ljm.eWriteName(handle, "SPI_SPEED_THROTTLE", 0)
 def __setFreq(self, leftBit, rightBit):
     ljm.eWriteName(self.handle, "EIO3", rightBit)
     ljm.eWriteName(self.handle, "EIO4", leftBit)   
 def __HIAttenLatch(self, newVal):
     ljm.eWriteName(self.handle, "CIO2", 1)
     self.__turnOffAllLatches()
     self.allAtt["HI"] = newVal
Ejemplo n.º 52
0
#handle = ljm.open(ljm.constants.dtANY, ljm.constants.ctANY, "ANY")


info = ljm.getHandleInfo(handle)
print("Opened a LabJack with Device type: %i, Connection type: %i,\n" \
    "Serial number: %i, IP address: %s, Port: %i,\nMax bytes per MB: %i" % \
    (info[0], info[1], info[2], ljm.numberToIP(info[3]), info[4], info[5]))


# Setup Stream Out
OUT_NAMES = ["DAC0"]
NUM_OUT_CHANNELS = len(OUT_NAMES)
outAddress = ljm.nameToAddress(OUT_NAMES[0])[0]

# Allocate memory for the stream-out buffer
ljm.eWriteName(handle, "STREAM_OUT0_TARGET", outAddress)
ljm.eWriteName(handle, "STREAM_OUT0_BUFFER_SIZE", 512)
ljm.eWriteName(handle, "STREAM_OUT0_ENABLE", 1)

# Write values to the stream-out buffer
ljm.eWriteName(handle, "STREAM_OUT0_LOOP_SIZE", 6)
ljm.eWriteName(handle, "STREAM_OUT0_BUFFER_F32", 0.0) # 0.0 V
ljm.eWriteName(handle, "STREAM_OUT0_BUFFER_F32", 1.0) # 1.0 V
ljm.eWriteName(handle, "STREAM_OUT0_BUFFER_F32", 2.0) # 2.0 V
ljm.eWriteName(handle, "STREAM_OUT0_BUFFER_F32", 3.0) # 3.0 V
ljm.eWriteName(handle, "STREAM_OUT0_BUFFER_F32", 4.0) # 4.0 V
ljm.eWriteName(handle, "STREAM_OUT0_BUFFER_F32", 5.0) # 5.0 V

ljm.eWriteName(handle, "STREAM_OUT0_SET_LOOP", 0)

print("STREAM_OUT0_BUFFER_STATUS = %f" % (ljm.eReadName(handle, "STREAM_OUT0_BUFFER_STATUS")))
Ejemplo n.º 53
0
from time import sleep

ser = serial.Serial(port='COM7', baudrate=115200, timeout=1)
if not gt.login(ser):
    gt.fail(ser)
#open the labjack with the specified serial # on any available connection
lj = ljm.open(ljm.constants.dtANY, ljm.constants.ctANY, "470010285")
gpios = []
#iterate over all GPIOs
for i in xrange(8):
    gpios.append(True)
    #just to save copiable code, loop over I/O 0 or 1
    for val in xrange(2):
        #VERY IMPORTANT always reset LJ to low out to avoid driving LJ and Gumstix simultaneously
        DIO = "FIO%i" % i
        ljm.eWriteName(lj, DIO, 0)
        #configure GPIO to output
        ser.write('echo out > /gpio/boardio%i/direction\r' % (i+1))
        sleep(1)
        ser.write('echo %i > /gpio/boardio%i/value\r' % (val, i+1))
        sleep(1)
        #read value on LJ
        ljread = int(ljm.eReadName(lj, DIO))
        print 'LJRead on GPIO %i expecting %i got %i' % (i, val, ljread)
        if ljread != val:
            gpios[i] = False
        ser.write('echo in > /gpio/boardio%i/direction\r' % (i+1))
        #configure LJ to output
        ljm.eWriteName(lj, DIO, val)
        sleep(1)
        #read value on gumstix
Ejemplo n.º 54
0
# Open first found LabJack
handle = ljm.open(ljm.constants.dtANY, ljm.constants.ctANY, "ANY")
#handle = ljm.openS("ANY", "ANY", "ANY")

info = ljm.getHandleInfo(handle)
print("Opened a LabJack with Device type: %i, Connection type: %i,\n" \
    "Serial number: %i, IP address: %s, Port: %i,\nMax bytes per MB: %i" % \
    (info[0], info[1], info[2], ljm.numberToIP(info[3]), info[4], info[5]))

# Setup and call eWriteName to set the DIO state on the LabJack.
name = "FIO6"

while True:
    A = raw_input("1 or 0")
    if  A == '1':
        state = 1
    else:
        state = 0
    time.sleep(1)    
    ljm.eWriteName(handle, name, state)    
    print("\nSet %s state : %f" % (name, state))
'''    
ljm.eWriteName(handle, name, state)    
print("\nSet %s state : %f" % (name, state))
'''


# Close handle
ljm.close(handle)
Ejemplo n.º 55
0
#handle = ljm.open(ljm.constants.dtANY, ljm.constants.ctANY, "ANY")


info = ljm.getHandleInfo(handle)
print("Opened a LabJack with Device type: %i, Connection type: %i,\n" \
    "Serial number: %i, IP address: %s, Port: %i,\nMax bytes per MB: %i" % \
    (info[0], info[1], info[2], ljm.numberToIP(info[3]), info[4], info[5]))


# ### FIO LOW ### 
#set all FIO digital channels to low state (prevent malfunction of digital channels)
statelow=0
for i in range(0,8):
    num=str(i)
    chF="FIO"+num
    ljm.eWriteName(handle, chF, statelow)
# ### FIO LOW ###

# Setup Stream Out
OUT_NAMES = ["FIO_STATE", "DAC1", "DAC0"]
NUM_OUT_CHANNELS = len(OUT_NAMES)
outAddress = ljm.nameToAddress(OUT_NAMES[0])[0]

# FIO ###
# Allocate memory for the stream-out buffer
ljm.eWriteName(handle, "STREAM_OUT0_TARGET", outAddress)
ljm.eWriteName(handle, "STREAM_OUT0_BUFFER_SIZE", 512)
ljm.eWriteName(handle, "STREAM_OUT0_ENABLE", 1)

matriz = np.array([[1,1,1,1],[0,0,0,0],[1,1,1,1], [0,0,0,0],[1,1,1,1],[0,0,0,0]])
rowsdim=matriz.shape[0]
 def __turnOffAllLatches(self):
     ljm.eWriteName(self.handle, "CIO0", 0)
     ljm.eWriteName(self.handle, "CIO1", 0)
     ljm.eWriteName(self.handle, "CIO2", 0)
     ljm.eWriteName(self.handle, "CIO3", 0)
Ejemplo n.º 57
0
def DAC_Write(handle,DAC, Volt): # Volt is an integer (e.g., can be used for clossing or openning Shutter: 0=close, 5=open)
                                 # This can also be used for digital ports e.g.: DAC_Write(DAQ_handle, 'FIO0', 1) brings the port FIO0 to 3 v 
    ljm.eWriteName(handle, DAC, Volt)
    #print int(round(time.time() * 1000))
    return
 def setNoiseSourceOff(self):
     self.errorCheck()
     self.noiseOn = 0
     ljm.eWriteName(self.handle, "EIO0", 0)
Ejemplo n.º 59
0
info = ljm.getHandleInfo(handle)
print(
    "Opened a LabJack with Device type: %i, Connection type: %i,\n"
    "Serial number: %i, IP address: %s, Port: %i,\nMax bytes per MB: %i"
    % (info[0], info[1], info[2], ljm.numberToIP(info[3]), info[4], info[5])
)


# Setup Stream Out
OUT_NAMES = ["FIO_STATE", "DAC0"]
NUM_OUT_CHANNELS = len(OUT_NAMES)
outAddress = ljm.nameToAddress(OUT_NAMES[0])[0]

# Allocate memory for the stream-out buffer
ljm.eWriteName(handle, "STREAM_OUT2_TARGET", outAddress)
ljm.eWriteName(handle, "STREAM_OUT2_BUFFER_SIZE", 512)
ljm.eWriteName(handle, "STREAM_OUT2_ENABLE", 1)

# Write values to the stream-out buffer
ljm.eWriteName(handle, "STREAM_OUT2_LOOP_SIZE", 8)
ljm.eWriteName(handle, "STREAM_OUT2_BUFFER_U16", 110)
ljm.eWriteName(handle, "STREAM_OUT2_BUFFER_U16", 100)
ljm.eWriteName(handle, "STREAM_OUT2_BUFFER_U16", 110)
ljm.eWriteName(handle, "STREAM_OUT2_BUFFER_U16", 100)
ljm.eWriteName(handle, "STREAM_OUT2_BUFFER_U16", 110)
ljm.eWriteName(handle, "STREAM_OUT2_BUFFER_U16", 100)
ljm.eWriteName(handle, "STREAM_OUT2_BUFFER_U16", 111)
ljm.eWriteName(handle, "STREAM_OUT2_BUFFER_U16", 100)
# ljm.eWriteName(handle, "STREAM_OUT0_BUFFER_U16", 00)
Ejemplo n.º 60
0
 def setallzero(self):
     statelow=0
     for i in range(0,8):
         num=str(i)
         chF="FIO"+num
         ljm.eWriteName(self.handle, chF, statelow)