Jump to content

As of July 17, 2015, the LabJack forums here at forums.labjack.com are shut down. New registrations, topics, and replies are disabled. All forums are in a read-only state for archive purposes.

Please visit our current forums at labjack.com/forums to view and make new posts. To post on the current forums, use your labjack.com login account. Your old LabJack forums login credentials have been retired. There are no longer separate logins for labjack.com and LabJack forums.


Stream mode with LabJack U3

streaming u3

  • Please log in to reply
1 reply to this topic

#1 steve6540

  • Members
  • 1 posts

Posted 13 July 2015 - 08:43 AM


This is my first time working with the u3. I am trying to write a streaming program in Python that gets analog readings from FIO4 (called AIN4 when configured to be analog, I believe) and convert them to voltages. I am going to then plot those voltages versus time, and eventually frequency.


My goal is to be able to continuously stream data and plot it versus time. I am only reading one channel, so I believe I can read at 50k/sec. I have tried to use the low level command d.getFeedback(u3.AIN(4)), but I get an error that the stream has already been started.

I chose to convert all of the unsigned values outside the loop in order to minimize the number of packets lost.

I am having trouble appending an array with the readings. With the current code, I get a KeyError: 



Traceback (most recent call last):

  File "C:/Users/_____/PycharmProjects/New1/src/Streaming Program.py", line 59, in <module>
KeyError: 'AIN4'

Below is my code, with remnants of old code now commented just in case. 




# We need the date and time in order to plot our data
import traceback
from datetime import datetime

#importing matplotlib in order to plot what we get
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy

#import the u3
import u3

# Open the U3
d = u3.U3()

# Set the FIO4 to analog (and all channels below) which is AIN4 later for low level commands.

# MAX_REQUESTS is the number of packets to be read.

# For applying the proper calibration for readings from unsigned values to voltages

# Set the steam parameters. 1 channel, positive channel #4, negative channel #31 = singled ended, resolution 3 -> higher noise but faster sampling
# Sample rate = scanrate * numchannels, max ~50k samples/s. Samples per packet = 25 for data transfer efficiency. packetsPerRequest =48
print "Configuring U3 Stream..."
d.streamConfig(NumChannels=1PChannels=[4], NChannels=[31], Resolution ScanFrequency 51000SamplesPerPacket 25)

# To prevent the program from crashing when encountering an exception, we use a try statement
rawDataList =[]
start = datetime.now() # print the scan start time
print "Started stream at " , datetime.now(), '\n'
missed = # initialize counters
dataCount = 0
packetCount = 0

for in d.streamData(convert=False):
if is not None:
#packetStartTime = datetime.now()
#miniRuntime = (packetStartTime - start).seconds + float((packetStartTime - start).microseconds) / 1000000

# Our stop condition
if dataCount >= MAX_REQUESTS:

if r['errors'] != 0:
print "Error: %s ; " % r['errors'], datetime.now()

if r['numPackets'] != d.packetsPerRequest:
print "----- UNDERFLOW : %s : " % r['numPackets'], datetime.now()

if r['missed'] != 0:
missed += r['missed']
print "+++ Missed ", r['missed']

#ain4bits = r['AIN4']

#Comment out these prints and do something with r
#print "Average of", (r['AIN4'])
#print 8*sum(r['AIN4'])/len(r['AIN4']), ",", miniruntime

# h1, = plt.plot([],[])

#def update_line(h1, new_data):
#h1.set_xdata(numpy.append(h1.get_xdata(), new_data))
#h1.set_xdata(numpy.append(h1.get_ydata(), new_data))

dataCount += 1
packetCount += r['numPackets']
# Got no data back from our read.
# This only happens if your stream isn't faster than the
# the USB read timeout, ~1 sec.
print "No data, timeout", datetime.now()

print "".join(i for in traceback.format_exc())


processedDataList = d.processStreamData(rawDataList)
averageVoltage = sum(processedDataList)/len(processedDataList)
stop = datetime.now()
print '\n"Stream stopped at", datetime.now(), '\n'

sampleTotal = packetCount * d.streamSamplesPerPacket

scanTotal = sampleTotal / # sampleTotal / NumChannels

print "%s requests with %s packets per request with %s samples per packet = %s samples total." % (
dataCount, (float(packetCount) / dataCount), d.streamSamplesPerPacket, sampleTotal)
print "%s samples were lost due to errors." % missed
print "%f percent of total samples were lost" % (float(missed) * 100 / sampleTotal)

sampleTotal -= missed
print "Adjusted number of samples = %s" % sampleTotal
print '\n'

runTime = (stop - start).seconds + float((stop - start).microseconds) / 1000000
print "The experiment took %s seconds." % runTime
print "Scan Rate : %s scans / %s seconds = %s Hz" % (scanTotal, runTime, float(scanTotal) / runTime)
print "Sample Rate : %s samples / %s seconds = %s Hz" % (sampleTotal, runTime, float(sampleTotal) / runTime)
print "The average voltage was %s volts over the scan period" % (averageVoltage)


Thank you in advance for your time. 


#2 LabJack Support

LabJack Support
  • Admin
  • 8677 posts

Posted 13 July 2015 - 12:49 PM


I have tried to use the low level command d.getFeedback(u3.AIN(4)), but I get an error that the stream has already been started.

When stream mode is running, you cannot read analog inputs using command/response mode (getFeedback with AIN).


As for your code, since you are not converting sample data in the streamData method it will not return AIN4 key with a list of samples. You will be processing data from r["result"] instead which is the string representation of the raw stream data packets/bytes. So instead:

#Before streamRead loop
#rawDataList =[] #Not using a list
rawDataStr = "" #Initialize an empty string for our raw StreamData bytes. Raw data bytes returned from streamData are in string format.
    #In streamRead loop
    #rawDataList.append(r['AIN4']) #r['AIN4'] not available in the d.streamData(convert=False) return
    rawDataStr += r['result'] #Add the current raw bytes
#After streamData loop
#processedDataList = d.processStreamData(rawDataList)
processedDataList = d.processStreamData(rawDataStr)['AIN4'] #Convert all raw data bytes to calibrated voltage samples

Also tagged with one or more of these keywords: streaming, u3

0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users