Esempio n. 1
0
def print_device_info(handle):
    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\n" % \
        (info[0], info[1], info[2], ljm.numberToIP(info[3]), info[4], info[5])
    )
Esempio n. 2
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"])
Esempio n. 3
0
def Init():                 
    # Open first found LabJack
    handle = ljm.open(ljm.constants.dtANY, ljm.constants.ctANY, "ANY")
    #handle = ljm.openS("ANY", "ANY", "ANY")
    #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 = 3
    names = ["AIN_ALL_NEGATIVE_CH", "AIN_ALL_RANGE", "AIN_ALL_RESOLUTION_INDEX"]
    aValues = [199, 10, 1]
    ljm.eWriteNames(handle, numFrames, names, aValues)
    #return handle, Info
    return handle
Esempio n. 4
0
from labjack import ljm
import time
import sys
from datetime import datetime

MAX_REQUESTS = 5  # The number of eStreamRead calls that will be performed.

# 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])
)


# 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
Esempio n. 5
0
write.  If you short MISO to GND, then you will read back zeros.  If you
short MISO to VS or leave it unconnected, you will read back 255s.

"""
from random import randrange

from labjack import ljm

# 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]))

deviceType = info[0]

if deviceType == ljm.constants.dtT4:
    # Configure FIO4 to FIO7 as digital I/O.
    ljm.eWriteName(handle, "DIO_INHIBIT", 0xFFF0F)
    ljm.eWriteName(handle, "DIO_ANALOG_ENABLE", 0x00000)

    # Setting CS, CLK, MISO, and MOSI lines for the T4. FIO0 to FIO3 are
    # reserved for analog inputs, and SPI requires digital lines.
    ljm.eWriteName(handle, "SPI_CS_DIONUM", 5)  # CS is FIO5
    ljm.eWriteName(handle, "SPI_CLK_DIONUM", 4)  # CLK is FIO4
Esempio n. 6
0
    def configureT7(self):

        with open('darkstar_t7.json', 'r') as f:
            config_data = f.read()
            config_dict = json.loads(config_data.decode('utf-8'),
                                     object_pairs_hook=OrderedDict)

        for sensor in config_dict['Analog Sensors']:
            self.analog_sensors[sensor['Name']] = AnalogLJSensor(
                sensor['Name'], sensor['PChannel'], sensor['NChannel'],
                sensor['range'], sensor['slope'], sensor['intercept'],
                sensor['ef_index'])
        for sensor in config_dict['Digital Sensors']:
            self.digital_sensors[sensor['Name']] = DigitalLJSensor(
                sensor['Name'], sensor['Address'])

        self.t7handle = ljm.openS("T7", "ANY", "ANY")
        info = ljm.getHandleInfo(self.t7handle)
        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]))

        # Stream Configuration
        # for sensorName, sensor in self.analog_sensors.items():
        #     if sensor is not None:
        #        self.t7readList.append(int(sensor.getPositiveChannel()))
        #        self.channelNames.append(str(sensor.getName()))
        #        print(int(sensor.getPositiveChannel()))
        #        print(str(sensor.getName()))

        # print "T7 Read list" , self.t7readList

        aWriteNames = []
        aWriteValues = []
        # print(type(analog_sensors))
        # Stream Configuration
        for sensor in self.analog_sensors:
            pChannel = str(self.analog_sensors[sensor].getPositiveChannel())
            nChannel = int(self.analog_sensors[sensor].getNegativeChannel())
            if (nChannel > 0):
                print("configuring negative channel")
                aWriteNames.append("AIN" + pChannel + "_NEGATIVE_CH")
                aWriteValues.append(nChannel)
            if (int(self.analog_sensors[sensor].getExtendedFeatures()) > 0):
                aWriteNames.append("AIN" + pChannel + "_EF_INDEX")
                aWriteValues.append(
                    int(self.analog_sensors[sensor].getExtendedFeatures()))

        print "Names written", aWriteNames
        print "Values written", aWriteValues

        ljm.eWriteNames(self.t7handle, len(aWriteNames), aWriteNames,
                        aWriteValues)

        results = ljm.eReadNames(self.t7handle, len(aWriteNames), aWriteNames)

        print("\neReadNames results: ")
        for i in range(len(aWriteNames)):
            print("    Name - %s, value : %d" % (aWriteNames[i], results[i]))

        self.t7readListNames = []
        self.t7channelNames = []

        # Read Configuration
        for sensorName, sensor in self.analog_sensors.items():
            if sensor is not None:
                self.t7channelNames.append(str(sensor.getName()))
                if (int(sensor.getExtendedFeatures()) > 0):
                    self.t7readListNames.append(
                        "AIN" + str(sensor.getPositiveChannel()) +
                        "_EF_READ_A")
                else:
                    self.t7readListNames.append(
                        "AIN" + str(sensor.getPositiveChannel()))
Esempio n. 7
0
# Data stream and record
results = {}
if __name__ == '__main__':

    # LJ setup
    # Connect to the labjack
    LJ_dict = {}
    LJ_dict['handle_1'] = ljm.openS(
        "any", "any",
        "470019751")  # [TC, K] device type, connection type, serial no.
    LJ_dict['handle_2'] = ljm.openS(
        "ANY", "ANY",
        "470019220")  # [RES, FRG] device type, connection type, serial no.
    # Get LJ handle
    LJ_dict['info_1'] = ljm.getHandleInfo(LJ_dict['handle_1'])
    LJ_dict['info_2'] = ljm.getHandleInfo(LJ_dict['handle_2'])
    # Create dictionaries to store channel/registry information
    aAddresses, aDataTypes, aValues = {}, {}, {}
    # Find the channel/registry information for each of the sensor suites
    aAddresses.update(thermocouple.main(LJ_dict['handle_1'])[0])
    aDataTypes.update(thermocouple.main(LJ_dict['handle_1'])[1])
    aValues.update(thermocouple.main(LJ_dict['handle_1'])[2])
    aAddresses.update(level.main(LJ_dict['handle_2'])[0])
    aDataTypes.update(level.main(LJ_dict['handle_2'])[1])
    aValues.update(level.main(LJ_dict['handle_2'])[2])
    aAddresses.update(frg.main(LJ_dict['handle_2'])[0])
    aDataTypes.update(frg.main(LJ_dict['handle_2'])[1])
    aValues.update(frg.main(LJ_dict['handle_2'])[2])

    # Find crashed data
Esempio n. 8
0
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.logData = False
        self.ventValveAddress = 2016  #CIO0
        self.mainValveAddress = 2017  #CIO1
        self.flowMeterAddress = 6  # AIN3
        self.tankPressureAddress = 2  # AIN1
        self.outletPressureAddress = 0  # AIN0
        self.clock40MHz = 61520
        self.clock20Hz = 61522
        self.actuatorsAddresses = [
            self.ventValveAddress, self.mainValveAddress
        ]
        self.actuatorsDataTypes = [ljm.constants.UINT16, ljm.constants.UINT16]
        self.sensorsAddresses = [
            self.clock40MHz, self.tankPressureAddress,
            self.outletPressureAddress, self.flowMeterAddress
        ]
        self.sensorDataTypes = [
            ljm.constants.UINT32, ljm.constants.FLOAT32, ljm.constants.FLOAT32,
            ljm.constants.FLOAT32
        ]
        self.sensorMScaling = np.array([1, 125, 75, 0.937191256342697])
        self.sensorBScaling = np.array([0, -62.5, -37.5, -1.02160240296171])
        self.ui = Ui_Dialog()
        self.ui.setupUi(self)
        self.openValveIcon = QtGui.QIcon("open.png")
        self.closedValveIcon = QtGui.QIcon("closed.png")
        self.ui.logButton.setIcon(self.closedValveIcon)
        self.ui.eStopButton.clicked.connect(self.eStop)
        self.ui.logButton.clicked.connect(self.log)
        self.dataLog = np.empty([0, 4])
        self.tankPressure = 0
        self.outletPressure = 0
        self.flowRate = 0
        self.dataLogPacketSize = 1000
        self.actuatorsUpdateIntervalMs = 600
        self.lcdUpdateIntervalMs = 700
        self.dataLogIntervalMs = 1
        self.fig, self.fig_axes = plt.subplots(ncols=1, nrows=3)
        self.tankPressureRingBuffer = np.zeros(200)
        self.outletPressureRingBuffer = np.zeros(200)
        self.flowRateRingBuffer = np.zeros(200)
        self.addmpl(self.fig)
        self.csvFile = None
        self.csvFileName = ""
        # self.ui.chartLayout.addWidget(self.toolbar)
        self.handle = ljm.openS(
            "T4", "ANY", "ANY")  # T4 device, Any connection, Any identifier

        info = ljm.getHandleInfo(self.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]))

        ret = ljm.eReadAddresses(self.handle, len(self.actuatorsAddresses),
                                 self.actuatorsAddresses,
                                 self.actuatorsDataTypes)
        self.ventValveState = bool(ret[0])
        self.mainValveState = bool(ret[1])
Esempio n. 9
0
def StreamCollection(max_requests=60, scanrate=1000, bKick=True, minSum=-1.0):
    #time will take about max_requests/2 in seconds

    MAX_REQUESTS = max_requests  # The number of eStreamRead calls that will be performed.
    FIRST_AIN_CHANNEL = 0  #AIN0
    NUMBER_OF_AINS = 3  # AIN0: L-R, AIN1: Sum, AIN2: T-B

    rawData = []

    # open the all ports and get the labjack handle
    handle = xyz.openPorts()

    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]))

    # Stream Configuration
    aScanListNames = [
        "AIN%i" % i
        for i in range(FIRST_AIN_CHANNEL, FIRST_AIN_CHANNEL + NUMBER_OF_AINS)
    ]  #Scan list names
    print("\nScan List = " + " ".join(aScanListNames))
    numAddresses = len(aScanListNames)
    aScanList = ljm.namesToAddresses(numAddresses, aScanListNames)[0]
    global scanRate
    scanRate = scanrate

    scansPerRead = int(scanRate / 2)

    try:
        # Configure the analog inputs' negative channel, range, settling time and
        # resolution.
        # Note when streaming, negative channels and ranges can be configured for
        # individual analog inputs, but the stream has only one settling time and
        # resolution.
        aNames = [
            "AIN_ALL_NEGATIVE_CH", "AIN_ALL_RANGE", "STREAM_SETTLING_US",
            "STREAM_RESOLUTION_INDEX"
        ]
        aValues = [ljm.constants.GND, 10.0, 0,
                   0]  #single-ended, +/-10V, 0 (default),
        #0 (default)
        ljm.eWriteNames(handle, len(aNames), aNames, aValues)

        eventNumber = 0  # keeps track of the event we make a new one each time the user resets the pendulum and hits enter
        input('start?')
        while True:

            if bKick:
                # kick the pendulum to drive it so we can take period data.
                print('Kicking')
                xr, yr, zr = kickUpAndWait(
                    0, 4.5e-6, 0,
                    10)  # kick the field and save the current values.
                #xr,yr,zr = kickUpAndWait(0, 2e-6, 0, 10) # seems like we maight want a bit less kick

            # Configure and start stream
            scanRate = ljm.eStreamStart(handle, scansPerRead, numAddresses,
                                        aScanList, scanRate)
            print("\nStream started with a scan rate of %0.0f Hz." % scanRate)

            print("\nPerforming %i stream reads." % MAX_REQUESTS)

            if bKick:
                kickDown(xr, yr,
                         zr)  # put the currents back to where they were
                print('Done Kicking!')

            # then do the stream.
            start = datetime.now()
            totScans = 0
            totSkip = 0  # Total skipped samples

            i = 1  # counter for number of stream requests

            while i <= MAX_REQUESTS:
                ret = ljm.eStreamRead(handle)

                data = ret[0]
                scans = len(data) / numAddresses
                totScans += scans

                # Count the skipped samples which are indicated by -9999 values. Missed
                # samples occur after a device's stream buffer overflows and are
                # reported after auto-recover mode ends.
                curSkip = data.count(-9999.0)
                totSkip += curSkip

                print("\neStreamRead %i" % i)
                ainStr = ""
                for j in range(0, numAddresses):
                    ainStr += "%s = %0.5f " % (aScanListNames[j], data[j])
                print("  1st scan out of %i: %s" % (scans, ainStr))
                print("  Scans Skipped = %0.0f, Scan Backlogs: Device = %i, LJM = " \
                      "%i" % (curSkip/numAddresses, ret[1], ret[2]))

                newDataChunk = np.reshape(
                    data, (-1, NUMBER_OF_AINS)
                )  # reshape the data to have each row be a different reading

                if i != 1:  # if we are not on the first run.
                    rawData = np.vstack((rawData, newDataChunk))
                else:
                    rawData = newDataChunk  # this should only run on the first time.
                    #print('FIRST RUN THROUGH')

                #print(rawData,'\n')

                i += 1

            end = datetime.now()

            print("\nTotal scans = %i" % (totScans))
            tt = (end - start).seconds + float(
                (end - start).microseconds) / 1000000
            print("Time taken = %f seconds" % (tt))
            print("LJM Scan Rate = %f scans/second" % (scanRate))
            print("Timed Scan Rate = %f scans/second" % (totScans / tt))
            print("Timed Sample Rate = %f samples/second" %
                  (totScans * numAddresses / tt))
            print("Skipped scans = %0.0f" % (totSkip / numAddresses))

            print("\nStop Stream")
            ljm.eStreamStop(handle)

            print('current querry!')
            # update the powersupply field readings so we can reference them later
            xyz.xCoil.getLargeCoilField()
            xyz.yCoil.getLargeCoilField()
            print('done with current querry!')

            # format data to include field values
            rawDataWithFieldValues = []
            print(rawData)
            first = True
            for j, row in enumerate(
                    rawData
            ):  # setp throuh and append the field values to each datapoint
                if row[1] >= minSum:
                    timestamp = j * (1.0 / scanRate)
                    rowWithFieldValues = np.append(
                        row,
                        np.array([
                            xyz.xCoil.largeCoilField, xyz.yCoil.largeCoilField,
                            timestamp, eventNumber
                        ]))  # for now we aren't using the adustment coils
                    if first:
                        first = False
                        rawDataWithFieldValues = rowWithFieldValues

                    else:  # not on the first loop
                        rawDataWithFieldValues = np.vstack(
                            (rawDataWithFieldValues, rowWithFieldValues))
            print(np.shape(rawDataWithFieldValues))

            # and add it to our master data array
            if eventNumber != 0:
                #print(np.shape(allTheData))
                #print('--------')
                #print(np.shape(rawDataWithFieldValues))
                allTheData = np.vstack((allTheData, rawDataWithFieldValues))
                #print(np.shape(allTheData))
            else:
                allTheData = rawDataWithFieldValues

            print(allTheData)
            print(np.shape(allTheData))

            input(
                "finished with eventNumber %s. Press enter to start a new data run."
                % eventNumber)
            eventNumber += 1  # increment the event number

    except ljm.LJMError:
        ljme = sys.exc_info()[1]
        print(ljme)
        #xyz.closePorts(handle)

    except KeyboardInterrupt:  # usefull to have a KeyboardInterrupt when your're debugging

        # save the data to a DataFrame
        print("saving dataFrame")
        dataFrame = package_my_data_into_a_dataframe_yay(allTheData)
        #dataFrame.to_csv("./data/frequencyVsField/testData.csv")

        # generate timestamp
        timeStamp1 = time.strftime('%y-%m-%d~%H-%M-%S')
        dataFrame.to_csv("./data/Calibrations/freqVsField%s.csv" % timeStamp1)

        xyz.closePorts(handle)

    except Exception as e:
        # helpful to close the ports on except when debugging the code.
        # it prevents the devices from thinking they are still conected and refusing the new connecton
        # on the next open ports call.

        print("saving dataFrame")
        dataFrame = package_my_data_into_a_dataframe_yay(allTheData)
        #dataFrame.to_csv("./data/frequencyVsField/testData.csv")

        # generate timestamp
        timeStamp1 = time.strftime('%y-%m-%d~%H-%M-%S')
        dataFrame.to_csv("./data/Calibrations/freqVsField%s.csv" % timeStamp1)

        xyz.closePorts(handle)
        print('closed all the ports\n')

        print(e)  # print the exception
        raise
Esempio n. 10
0
def main():
    try:
        openTime = datetime.utcnow()
        daqHandle = ljm.openS("T7", "TCP", "ANY")

        daqInfo = ljm.getHandleInfo(daqHandle)
        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"
            % (daqInfo[0], daqInfo[1], daqInfo[2], ljm.numberToIP(
                daqInfo[3]), daqInfo[4], daqInfo[5]))

        csvWriter, csvFile = generateCSV()
        timeHeader = ["TIME"]
        timeHeader.extend(aScanListNames)
        csvWriter.writerow(timeHeader)
        if (daqInfo[0] == ljm.constants.dtT7):

            # Disable triggered streaming
            ljm.eWriteName(daqHandle, "STREAM_TRIGGER_INDEX", 0)

            # Enabling internally-clocked stream.
            ljm.eWriteName(daqHandle, "STREAM_CLOCK_SOURCE", 0)

            # All negative channels are single-ended, AIN0 and AIN1 ranges are
            # +/-10 V, stream settling is 0 (default) and stream resolution index
            # is 0 (default).
            aNames = [
                "AIN_ALL_NEGATIVE_CH", "AIN_ALL_RANGE", "STREAM_SETTLING_US",
                "STREAM_RESOLUTION_INDEX"
            ]
            aValues = [ljm.constants.GND, 10.0, 0, 0]

            ljm.eWriteNames(daqHandle, len(aNames), aNames, aValues)

            # Configure and start stream
            scanStartTime = datetime_to_float(datetime.utcnow())
            lastScanStartTime = scanStartTime
            scanRate = ljm.eStreamStart(daqHandle, scansPerRead, numAddresses,
                                        aScanList, scanRate)
            print("\nStream started with a scan rate of %0.0f Hz." % scanRate)

            totScans = 0
            totSkip = 0  # Total skipped samples

            aScanClockNames = ["SYSTEM_TIMER_20HZ", "CORE_TIMER"]
            startClocks = ljm.eReadNames(daqHandle, len(aScanClockNames),
                                         aScanClockNames)
            start20HzClock = startClocks[0]
            start40MHzClock = startClocks[1]
            count40MHzRollover = 0

            # Stream Configuration
            aScanListNames = ["AIN0", "AIN1", "AIN2",
                              "AIN3"]  # Scan list names to stream
            aScanList = ljm.namesToAddresses(len(numAddresses),
                                             aScanListNames)[0]
            scanRate = 10
            scansPerRead = int(scanRate / 2)

            # while True:
            try:
                ret = ljm.eStreamRead(daqHandle)
                scanStopTime = datetime_to_float(datetime.utcnow())

                aData = ret[0]
                scans = len(aData) / numAddresses
                totScans += scans

                # Count the skipped samples which are indicated by -9999 values. Missed
                # samples occur after a device's stream buffer overflows and are
                # reported after auto-recover mode ends.
                curSkip = aData.count(-9999.0)
                totSkip += curSkip
                ainStr = ""
                for j in range(0, numAddresses):
                    ainStr += "%s = %0.5f, " % (aScanListNames[j], aData[j])
                print("  1st scan out of %i: %s" % (scans, ainStr))
                print(
                    "  Scans Skipped = %0.0f, Scan Backlogs: Device = %i, LJM = "
                    "%i" % (curSkip / numAddresses, ret[1], ret[2]))
                timeData = np.linspace(scanStartTime,
                                       scanStopTime,
                                       num=scansPerRead)
                print timeData
                print aData
                scanData = np.array(aData)
                print scanData
                print("Rows/Cols: ", scanData.shape)
                print("Num address: ", numAddresses)
                splitScanData = np.split(scanData, scansPerRead)
                print splitScanData
                print("Rows/Cols: ", splitScanData[0].shape)
                csvWriter.writerows(splitScanData)
                verticalStackedSplitScanData = np.vstack(splitScanData)
                print verticalStackedSplitScanData
                print "Test"
                # csvWriter.writerows(verticalStackedSplitScanData)   #use write rows once separated with numpy array
            except Exception as e:
                raise e
                # break
            except KeyboardInterrupt:  # Extend to save button interrupt
                pass
                # break
            # Close T7 Connection
            try:
                print("\nStop Stream")
                ljm.eStreamStop(daqHandle)
            except ljm.LJMError:
                ljme = sys.exc_info()[1]
                print(ljme)
            except Exception:
                e = sys.exc_info()[1]
                print(e)

    except ljm.LJMError:
        ljme = sys.exc_info()[1]
        print(ljme)
    except Exception:
        e = sys.exc_info()[1]
        print(e)

    csvFile.close()
    ljm.close(daqHandle)
Esempio n. 11
0
 def info(self):
     return ljm.getHandleInfo(self.handle)
Esempio n. 12
0
def generador_Frecuecia (f3, f4, nombre):

    fs = 50000
    # f = 500
    #ciclo1=f1/400.0000000
    #ciclo1=np.ceil(ciclo1)
    #ciclo2 = f2 / 400.0000000
    #ciclo2 = np.ceil(ciclo2)
    #duration1 = np.float32(ciclo1/f1)
    #duration2 = np.float32(ciclo2 / f2)
    #samples1 = (np.sin(2 * np.pi * np.arange(fs * duration1) * f1 / fs)).astype(np.float32)
    #samples1 = 2.0 * samples1 + 2.5
    #samples2 = (np.sin(2 * np.pi * np.arange(fs * duration2) * f2 / fs)).astype(np.float32)
    #samples2 = 2.0 * samples2 + 2.5
    #plt.plot(samples)
    #plt.show()

    # print(len(samples1))
    # MAX_REQUESTS = 1000  # The number of eStreamRead calls that will be performed.

    # Open first found LabJack

    # 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]))


    # Desactivacion de parlantes
    ljm.eWriteName(handle, "FIO1", 0)
    ljm.eWriteName(handle, "FIO4", 0)
    ljm.eWriteName(handle, "FIO2", 0)
    ljm.eWriteName(handle, "FIO0", 0)

    # Setup Stream Out
    #OUT_NAMES = ["DAC0", "DAC1"]
    #NUM_OUT_CHANNELS = len(OUT_NAMES)
    #outAddress1 = ljm.nameToAddress(OUT_NAMES[0])[0]
    #outAddress2 = ljm.nameToAddress(OUT_NAMES[0])[1]
    # Allocate memory for the stream-out buffer
    #ljm.eWriteName(handle, "STREAM_OUT0_TARGET", 1000)
    #ljm.eWriteName(handle, "STREAM_OUT0_BUFFER_SIZE", 2048)
    #ljm.eWriteName(handle, "STREAM_OUT0_ENABLE", 1)
    #ljm.eWriteName(handle, "STREAM_OUT0_LOOP_SIZE", len(samples1))
    #ljm.eWriteName(handle, "STREAM_OUT1_TARGET", 1002)
    #ljm.eWriteName(handle, "STREAM_OUT1_BUFFER_SIZE", 2048)
    #ljm.eWriteName(handle, "STREAM_OUT1_ENABLE", 1)
    #ljm.eWriteName(handle, "STREAM_OUT1_LOOP_SIZE", len(samples2))
    
    freq1=80000000.000000000000000000/32
    freq1=freq1/f3
    ljm.eWriteName(handle, "DIO_EF_CLOCK1_ENABLE", 0)
    ljm.eWriteName(handle, "DIO_EF_CLOCK1_DIVISOR", 32)
    ljm.eWriteName(handle, "DIO_EF_CLOCK1_ROLL_VALUE", freq1)
    ljm.eWriteName(handle, "DIO_EF_CLOCK1_ENABLE", 1)
    ljm.eWriteName(handle, "DIO3_EF_ENABLE", 0)
    ljm.eWriteName(handle, "DIO3_EF_INDEX", 0)
    ljm.eWriteName(handle, "DIO3_EF_OPTIONS", 1)
    ljm.eWriteName(handle, "DIO3_EF_CONFIG_A", freq1/2)
    ljm.eWriteName(handle, "DIO3_EF_ENABLE", 1)
    ljm.eWriteName(handle, "DIO_EF_CLOCK1_DIVISOR", 32)
    ljm.eWriteName(handle, "DIO_EF_CLOCK1_ROLL_VALUE", freq1)
    ljm.eWriteName(handle, "DIO3_EF_CONFIG_A", freq1/2)

    freq2=80000000.000000000000000000/32
    freq2=freq2/f4
    ljm.eWriteName(handle, "DIO_EF_CLOCK2_ENABLE", 0)
    ljm.eWriteName(handle, "DIO_EF_CLOCK2_DIVISOR", 32)
    ljm.eWriteName(handle, "DIO_EF_CLOCK2_ROLL_VALUE", freq2)
    ljm.eWriteName(handle, "DIO_EF_CLOCK2_ENABLE", 1)
    ljm.eWriteName(handle, "DIO5_EF_ENABLE", 0)
    ljm.eWriteName(handle, "DIO5_EF_INDEX", 0)
    ljm.eWriteName(handle, "DIO5_EF_OPTIONS", 2)
    ljm.eWriteName(handle, "DIO5_EF_CONFIG_A", freq2/2)
    ljm.eWriteName(handle, "DIO5_EF_ENABLE", 1)
    ljm.eWriteName(handle, "DIO_EF_CLOCK2_DIVISOR", 32)
    ljm.eWriteName(handle, "DIO_EF_CLOCK2_ROLL_VALUE", freq2)
    ljm.eWriteName(handle, "DIO5_EF_CONFIG_A", freq2/2)




    #for i in range(0, len(samples1)):
    #   ljm.eWriteName(handle, "STREAM_OUT0_BUFFER_F32", samples1[i])
    #for i in range(0, len(samples2)):
    #    ljm.eWriteName(handle, "STREAM_OUT1_BUFFER_F32", samples2[i])

    tm.sleep(1)
    #ljm.eWriteName(handle, "STREAM_OUT0_SET_LOOP", 1)
    #ljm.eWriteName(handle, "STREAM_OUT1_SET_LOOP", 1)
    #print("STREAM_OUT0_BUFFER_STATUS = %f" % (ljm.eReadName(handle, "STREAM_OUT0_BUFFER_STATUS")))
    #print("STREAM_OUT0_BUFFER_STATUS = %f" % (ljm.eReadName(handle, "STREAM_OUT1_BUFFER_STATUS")))
    # Stream Configuration
    aScanListNames = ["AIN2"]  # Scan list names to stream
    numAddresses = len(aScanListNames)
    aScanList = ljm.namesToAddresses(numAddresses, aScanListNames)[0]
    scanRate = fs
    scansPerRead = int(scanRate / 2000)

    # Datos de Transformada de FFT
    T = 1.00000/fs
    x = np.linspace(0.00, scansPerRead*T, scansPerRead)
    xf = np.linspace(0.00, 1.00/(2.00*T), scansPerRead/2)
    # fig, (ax, bx) = plt.subplots(2, 1)

    # plt.ion()
    # Add the scan list outputs to the end of the scan list.
    # STREAM_OUT0 = 4800, STREAM_OUT1 = 4801, etc.
    # aScanList.extend([4800])  # STREAM_OUT0
    # If we had more STREAM_OUTs
    # aScanList.extend([4801]) # STREAM_OUT1
    # aScanList.extend([4802]) # STREAM_OUT2
    # aScanList.extend([4803]) # STREAM_OUT3

    try:
        # Configure the analog inputs' negative channel, range, settling time and
        # resolution.
        # Note when streaming, negative channels and ranges can be configured for
        # individual analog inputs, but the stream has only one settling time and
        # resolution.
        aNames = ["AIN2_NEGATIVE_CH", "AIN_ALL_RANGE", "STREAM_SETTLING_US",
                  "STREAM_RESOLUTION_INDEX"]
        aValues = [3, 10.0, 0, 0]  # single-ended, +/-10V, 0 (default),
        # 0 (default)
        ljm.eWriteNames(handle, len(aNames), aNames, aValues)

        i = 1
	j = 0
	print("Empieza")
        scanRate = ljm.eStreamStart(handle, scansPerRead, 1, aScanList, scanRate)
	while j<1:
	    i = 1
	    k = 0
	    h = 0
	    print(j)
	    while(k < 1000):		
    	    	k=k+1
		ret = ljm.eStreamRead(handle)
	    # str=tm.time()
	    seleccionador (j)
	    # end=tm.time()
	    while i:  # i <= M9A;X_REQUESTS:
		# for g in range(0,2):	        
		ret = ljm.eStreamRead(handle)
		data = ret[0][0:scansPerRead]
	        # print("Hola")
		# start2 = datetime.now()
	        yf = ft.fft(data)
	        yf= 2.0 / scansPerRead * np.abs(yf[:scansPerRead // 2])
		# print("Hola2")
		    #(peaks, indexes) = octave.findpeaks(yf, 'DoubleSided', 'MinPeakHeight', 0.04, 'MinPeakDistance', 100, 'MinPeakWidth', 0)
		    # indexes = find_peaks_cwt(yf, np.arange(1, 2))
	        indexes = peakutils.indexes(yf, thres=0.01 / max(yf), min_dist=100)
		print (indexes)
	        i = silenciador (j, indexes)
		h = h + 1
		# end2 = datetime()

		# end = datetime.now
		# plt.close()
		# print("\nTotal scans = %i" % (totScans))
	    # tt = (end - start).seconds + float((end - start).microseconds) / 1000000
	    tt = h * 0.0002		
	    # tt2= end-str
	    print("Tiempo 1000Hz = %f seconds" % (tt))
	    # print("Tiempo 500Hz = %f seconds" % (tt2))
	    ANS[j]=(tt-OFFSET)*MULTIPLICITY
	    j=j+1
        # print("LJM Scan Rate = %f scans/second" % (scanRate))
        # print("Timed Scan Rate = %f scans/second" % (totScans / tt))
        # print("Timed Sample Rate = %f samples/second" % (totScans * numAddresses / tt))
        # print("Skipped scans = %0.0f" % (totSkip / numAddresses))
    except ljm.LJMError:
        ljme = sys.exc_info()[1]
        print(ljme)
    except Exception:
        e = sys.exc_info()[1]
        print(e)
    ljm.eWriteName(handle, "FIO1", 0)
    ljm.eWriteName(handle, "FIO4", 0)
    ljm.eWriteName(handle, "FIO2", 0)
    ljm.eWriteName(handle, "FIO0", 0)
    h = 1
    for dato in ANS:
	print ("Distancia %i : %f" % (h, dato))
	h=h+1
    print("\nStop Stream")
    ljm.eStreamStop(handle)

    # Close handle
    ljm.close(handle)
    print("Termino")
Esempio n. 13
0
    def __init__(self, time_offset, IP_address, sampling, channels):
        self.hv1_enable = 0
        self.hv2_enable = 0
        self.hv1 = 0
        self.hv2 = 0
        self.polarity1 = "POS"
        self.polarity2 = "NEG"
        self.running_ramp = False
        self.ramp_thread = None
        self.handle = openS("T7", "ETHERNET", IP_address)
        self.HV1Enable()
        self.HV2Enable()
        self.SetLJTickVoltage("TDAC0", 0)
        self.SetLJTickVoltage("TDAC1", 0)
        try:
            eStreamStop(self.handle)
        except ljm.LJMError as exception:
            if exception.errorString != "STREAM_NOT_RUNNING":
                raise

        self.time_offset = time_offset

        try:
            self.verification_string = str(getHandleInfo(self.handle)[0])
        except:
            self.verification_string = "False"

        # Ensure triggered stream is disabled.
        eWriteName(self.handle, "STREAM_TRIGGER_INDEX", 0)

        # Enabling internally-clocked stream.
        eWriteName(self.handle, "STREAM_CLOCK_SOURCE", 0)

        # Configure the analog input negative channels, ranges, stream settling
        # times and stream resolution index.
        aNames = [
            "AIN_ALL_NEGATIVE_CH", "AIN_ALL_RANGE", "STREAM_SETTLING_US",
            "STREAM_RESOLUTION_INDEX"
        ]
        aValues = [constants.GND, 10.0, 0,
                   0]  # single-ended, +/-10V, 0 (default), 0 (default)
        eWriteNames(self.handle, len(aNames), aNames, aValues)

        # start acquisition
        self.active_channels = []
        self.active_channel_names = []
        for ch in [0, 1, 2, 3, 4, 5]:
            if bool(int(channels[0][ch].get())):
                self.active_channel_names.append(channels[1][ch].get())
                self.active_channels.append("AIN{0}".format(ch))
        self.num_addresses = len(self.active_channels)
        self.scan_list = namesToAddresses(self.num_addresses,
                                          self.active_channels)[0]
        self.scans_rate = int(sampling["scans_rate"].get())
        self.scans_per_read = int(sampling["scans_per_read"].get())

        self.new_attributes = [
            ("column_names", ", ".join(self.active_channel_names)),
            ("units", ", ".join(["V"] * len(self.active_channels))),
            ("sampling", "{0} [S/s]".format(self.scans_rate))
        ]

        # shape and type of the array of returned data
        self.shape = (self.num_addresses, )
        self.dtype = 'f'

        self.scan_rate = eStreamStart(self.handle, self.scans_per_read,
                                      self.num_addresses, self.scan_list,
                                      self.scans_rate)