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.


Photo

Labjack Python "quick-start"?


  • Please log in to reply
15 replies to this topic

#1 cme

cme
  • Members
  • 4 posts

Posted 09 February 2011 - 10:09 AM

Hi,

I'm trying to get started with Python for Labjack. I have not used Python before (or have only very little), but I am familiar with Matlab and would like to use Python in a similar way as I have Matlab. Now I am using a UE9 with MacOSx. Previously I have used (and really liked using) a U12 with Matlab.

For Matlab, I have on my hard-drive a library of files (not sure if that was provided by Jabjack or whom) that made it very easy to get going. Particularly, there is a PDF called "MATLAB Function Calls.pdf" that has a good definition of the function calls and examples of them in use (I've attached that file here). Is there a similar document for Python?

Are there examples of the use of python with a UE9 for doing something simple. Here's the first script I put together in Matlab (analog_sample(), below), starting with something I think I picked up in the aforementioned file. This is the type of script I'd like to get running in Python now, to get going. Help "translating" this to Python would be appreciated.

%*******************************************************************
function data = analog_sample()
%I modified the original example file.
%this records the approximate real time data was taken, not just desired.
%feb2008cme

clc;
timestep=0.20; %200msec seems about as good as I can do with this program.
numsteps=100;
tic

for (i = 1:numsteps);
start = cputime;
time = toc; %(i-1)*timestep;
% real_time=toc;

% if abs(real_time - time)>timestep
% disp(['Real Time is ',num2str(real_time),', Expected Time is ',num2str(time),' seconds']);
% % error('Use a larger timestep - not keeping up.');
% end
volts = EAnalogIn(-1,0,1,0); % Sample analog signal using AI1
data(i,:) = [time volts]; % Data array for plotting
elapsed = start-cputime; % Calculate the time elapsed during funciton call
if (i==1);
fig1=figure;
plot(time,volts,'o');
xlim([0 2*numsteps*timestep]);
hold
end
plot(time,volts,'o');
pause(timestep-elapsed); % Pause for remainder of timestep
end

toc
disp(['meant to have ',num2str(numsteps*timestep),' seconds']);
for i=1:size(data,1)-1 dt(i,1)=data(i+1,1); dt(i,2)=data(i+1,1)-data(i,1); end


% Plot data
if exist('fig1') close(fig1); end
figure
subplot(2,1,1)
plot(data(:,1),data(:,2),'-or');
title('Analog Input Channel 1');
xlabel('Time (s)');
ylabel('AI1 Input (V)');
grid on;
subplot(2,1,2)
plot(dt(:,1),dt(:,2),'b',dt(:,1),dt(:,2)*0+timestep,'r');
%*******************************************************************


Best Regards.

Attached Files



#2 LabJack Support

LabJack Support
  • Admin
  • 8677 posts

Posted 09 February 2011 - 03:41 PM

Particularly, there is a PDF called "MATLAB Function Calls.pdf" that has a good definition of the function calls and examples of them in use (I've attached that file here). Is there a similar document for Python?

Not exactly. The documentation (class and methods) is in the source code itself located in the LabJackPython download and online: . On the LabJackPython page, http://labjack.com/s...t/labjackpython, we provide a Quickstart section. It shows U3 examples, but much of it can apply to the UE9 by replacing U3 names. Note that Modbus examples are fairly interchangeable codewise, but the Feedback function is different between the U3 and UE9. Please reference the UE9 class source code on using the Feedback method. If you get stuck feel free to ask us questions for clarification. In the LabJackPython download itself there are some code examples as well.

Looking at your Matlab code, on the LabJack side of things an easy way to read one analog input would be to use the getAIN method in the UE9 class. For example, to open a UE9 and do a simple read on AIN1 try this:
import ue9

d = ue9.UE9()  #open first found UE9
volts = d.getAIN(1) #read AIN1

For timing related documentation look at on Python's website: http://docs.python.o...rary/time.html. Plotting and GUI work itself you will need to look up online as it is not built into Python. On my first search result for plotting though, it looks like the [url="http://www.scipy.org/SciPy"]http://www.scipy.org/SciPy site has some useful packages.

#3 cme

cme
  • Members
  • 4 posts

Posted 10 February 2011 - 03:15 PM

Thank you for your reply.
Those references gave me a good starting point.

Another question... do you know if anyone has posted a python script for general data logging (where one could perhaps select a sample rate, the inputs to scan, file to write to...)? I haven't seen anything like that yet on the forum. If that exists already, I'd like to start with it. Also, if you (or anyone here) know of any other published python scripts for performing common tasks (as the Legacy U12 Sample applications did - there was a logger, scope, ...), please post a link.

Thanks for your help.

_cme.

#4 cme

cme
  • Members
  • 4 posts

Posted 13 February 2011 - 11:01 AM

I've begun constructing the script I need and have a couple more questions.
  • Is it possible for me to modify the getAIN() and similar functions to return not just the voltage, but the exact time at which the sample was taken? I dug back through the references (getAIN()->singleIO()->_writeRead()->read()...) but couldn't see a way to do that starting at getAIN(). Can the feedback() function be used to do that?
  • Also, I'd like to read multiple channels as close to the same time as possible (each with time read reported back with reading). Again, assuming it is possible, is feedback() the function to use to do that.
Here's what I have so far:
#lj.py: Python Functions for labjack.
def sample(numsamples = 100):    #note, if no argument, 100 samples are read.
	#at the python prompt, type: "import lj", then: "lj.sample(10)"
	import ue9
	import time
	d = ue9.UE9()
	i = 0
	t0 = time.time()
	while i < numsamples:
		volts = d.getAIN(1)    #would be nice if this function would return time too.
		t = time.time() - t0    #note, approximate - will be just after voltage was read.
		print(i,t,volts)
		i += 1
	d.close()    #close the labjack
	print "end"
Best Regards,
_cme

#5 LabJack Support

LabJack Support
  • Admin
  • 8677 posts

Posted 14 February 2011 - 11:48 AM

1. If you want you can modify getAIN to return the time along with voltage. For example, the getAIN return could be something like "return voltage, time.time()" and call of the function would look like "volts, t1 = d.getAIN(1)". You could put the time.time() call after the singleIO in getAIN() if you want to be a little more exact. That should be about when you get the reading back. Note that there are USB communications delay, and both the SingleIO and Feedback low-level functions do not have a time stamp.

2. If you would like to read multiple channels in one call (USB command/response), yes you will want to use feedback.

#6 cme

cme
  • Members
  • 4 posts

Posted 14 February 2011 - 12:43 PM

Thanks for your reply. Is there any low level function that does return a time stamp along with the measurement? Does stream mode do this? Speaking of stream mode, how would I go about replacing my little script here with it? Is there an "easy" stream function? If not, would you mind supplying or pointing me to an example? _cme.

#7 LabJack Support

LabJack Support
  • Admin
  • 8677 posts

Posted 14 February 2011 - 01:21 PM

Another person from here will need to respond on the stream time stamps as I am not 100% sure on those when regarding the UE9.

As for an "easy" function, unfortunately at this time there is not one, so you will need to implement the low-level function commands/responses. Also, I do not see a UE9 example for this in Python, but there is a C example which you can use as a guide here: https://github.com/l...UE9/ue9Stream.c. If you look at the Python UE9 singleIO/feedback examples they should show how to send/read USB commands in Python. The C examples will demonstrate how to stream. It is basically the use of the StreamConfig (configures the channels and scan clock), StrreamStart(starts stream mode), StreamData(read the data) and StreamStop(stop stream mode) low-level functions. Note that for StreamData you only need to read data (no command), so use the read function like this: "result = self.read(readLen, stream=True)". Also, the read, _writeRead methods are in the LabJackPython.py file as the UE9 class inherits these functions from the Device class.

#8 LabJack Support

LabJack Support
  • Admin
  • 8677 posts

Posted 14 February 2011 - 01:55 PM

I would set a timer to system-timer mode and read that timer in the same feedback packet as your AIN. The delay between the two IO types in firmware is about 5us. Feedback performs the actions that you specify in the order that you specify them. So, If you read the timer before your AIN then the time reported is 5us before the AIN reading was started. If you read the time after your AIN then the time reported is 5us after the AIN reading completed. Keep in mind that the time reported is just a counter relative to the when the LabJack booted up.

Here is some more information on the timer mode: http://labjack.com/s...guide/2.10.1.10

#9 Tom Lawton

Tom Lawton
  • Members
  • 14 posts

Posted 14 February 2011 - 02:03 PM

Assuming "Stream Mode" in Python is the same as under LabVIEW, then "timestamps" aren't really necessary- the data is acquired against the UE9's hardware clock, so is spaced at your requested frequency, to within the accuracy of the UE9's clock. Since the UE9 doesn't (AFAIK?) have a real-time clock on board, it can't report the start time of the data either. If you need a precise start, synchronised with something else, then you should do that with hardware triggering. For the purposes of my application- sampling at 20Hz- I found that multiple UE9s, told to in parallel, started "soon enough" after telling them to- though thinking about it, I think it's non-trivial to measure the (almost certainly variable) absolute delay between telling one to start, and its starting.... With regards to clock accuracy, thanks to help from LabJack support regarding clock drift, i calculated that I had to restart my 20Hz streams (from multiple UE9s) every 30 minutes to ensure they wouldn't "slip" relative to each other by 1 sample- and this indeed proved to be the case. (Incidentally, I was working over ethernet, not USB. Which way that might (or might not) affect startup delay, I couldn't say...!)

#10 LabJack Support

LabJack Support
  • Admin
  • 8677 posts

Posted 14 February 2011 - 03:04 PM

Is there any low level function that does return a time stamp along with the measurement? Does stream mode do this?

Realize that the UE9 does not have a real-time clock, just a relative clock. For absolute time stamps you need to read your system time.

Read Section 3.0 for a discussion of command/response versus stream mode:

http://labjack.com/s...9/users-guide/3

If you are using command/response mode, but want samples from different channels to be as close together as possible, then yes use the Feedback function so they occur in the same low-level packet.

If you want to timestamp command/response data, just use the system time from your computer. If you want to try and fine tune that, note the time before and after the call and take half of that.

#11 TrentG

TrentG
  • Members
  • 2 posts

Posted 18 November 2013 - 02:24 AM

CME has probably well and truly found a solution now but CME could always use the following steps: 

  1. Locate the "streamTest.py" file that comes with LabJackPython
  2. Add an extra line start = datetime.now() just before the data stream starts. As pointed out by LabJackSupport in the last post this will make an absolute measure of time from the PC system clock (we'll also need an import line from datetime import datetime)
  3. Set  "convert" equal to "False" in the d.streamData(convert=True) line,
  4. concatenate the streamed packets in a new variable (string) called, say, str_raw at the end of the for loop,
  5. process the data later using a processed_data = d.processStreamData(str_raw) call in the "finally" part of the try-except-finally statement. 
  6. Convert the processed data to a numpy array (another import needed) with the line data = numpy.array(processed_data[‘AIN0’]) assuming that we want to measure AIN0
  7. The timestamps can be made up after the stream is stopped because (correct me if I'm wrong) the labjack hardware clock should take care of the timing so that the relative time difference between each sampled data point is equal to 1.0/ScanFrequency where ScanFrequency is a variable that sets the scan frequency in the line d.streamConfig(....ScanFrequency = ScanFrequency).
  8. Use the arange function to construct an appropriate list of times that correspond to the sampled data. This can be done after the data stream has been stopped. Use the three variables start, len(data) and 1.0/ScanFrequency to create the appropriate list of timestamps.

Now for my question which I think fits into this thread. I have just bought myself a Labjack UE9 Pro and I’ve been experimenting with it and LabJackPython. I have experimented with calling the hardware clock and it doesn’t produce the values that I expect. I’ve written a snippet of code to demonstrate and isolate this discrepancy only (see Python code below). Perhaps I don’t understand LabJackPython properly or how the LabJack hardware clock works. The real elapsed time (measured by my PC clock as called by Python) seems to be consistently 25% greater than the elapsed time measured by the hardware clock.

 

I gather that the reported hardware times are supposed to be in micro-seconds elapsed since Labjack boot-up. Is this correct in timer mode 10?

 

The Python sleep time is so long in my code that the interchannel delay of 5us is insignificant.

 

Does anybody have any idea why there is a discrepancy between the elapsed time measured by the system PC clock (called by Python) and the hardware clock?

 

Cheers.

 

Output from the code is:

 

Start time (hardware clock): 1806.2895 seconds.
Stop time (hardware clock): 1807.790692 seconds.
Sleep time measured by hardware clock: 1.501192 s?
Sleep time set by Python: 2 seconds.
Relative time difference between hardware and Python time differences: 0.249404
 
 
Start time (hardware clock): 1807.825932 seconds.
Stop time (hardware clock): 1811.57708 seconds.
Sleep time measured by hardware clock: 3.751148 s?
Sleep time set by Python: 5 seconds.
Relative time difference between hardware and Python time differences: 0.2497704
import ue9
from time import sleep
import time
from datetime import datetime
import traceback

d = ue9.UE9( ethernet = True, ipAddress = "192.168.1.149") # use Ethernet instead of USB.
# I am using a UE9 pro.

# For applying the proper calibration to readings.
d.getCalibrationData()

def timeSleep(wait):
    # wait is specified in seconds
    t_start = d.timerCounter(UpdateConfig = True, NumTimersEnabled = 1, Timer0Mode = 10, Timer0Value = 0 ) # Timer0Mode = 10 , Timer0Value = 0
    time.sleep(wait)
    t_stop =  d.timerCounter(UpdateConfig = True, NumTimersEnabled = 1, Timer0Mode = 10, Timer0Value = 0 )
    one_mil = 1000000.0

    print 'Start time (hardware clock): ' + str(t_start['Timer0']/one_mil) + ' seconds.'
    print 'Stop time (hardware clock): ' + str(t_stop['Timer0']/one_mil) + ' seconds.'
    t_difference_hardware = (t_stop['Timer0'] - t_start['Timer0'])/one_mil # seconds. Difference between hardware start and stop times.
    print 'Sleep time measured by hardware clock: ' + str(t_difference_hardware) + ' s?'
    print 'Sleep time set by Python: ' + str(wait) + ' seconds.'
    t_discrepancy_absolute = wait - t_difference_hardware # time difference (seconds) between Python sleep time and time difference measured by hardware clock.
    t_discrepancy_relative = t_discrepancy_absolute/wait
    print 'Relative time difference between hardware and Python time differences: ' + str(t_discrepancy_relative)
    print '\n'
    return t_discrepancy_relative

timeSleep(2) # measure sleep time of 2 seconds
timeSleep(5) # measure sleep time of 5 seconds


#12 LabJack Support

LabJack Support
  • Admin
  • 8677 posts

Posted 18 November 2013 - 06:31 PM

It looks like the timer's time is calculated incorrectly in your Python code. The system timer on the UE9 has a frequency of 750 kHz (~1.33 microseconds per cycle or system timer count), which I believe starts at 0 when the UE9 boots. Divide the system timer by 750,000 instead of 1,000,000 to properly convert the timer's value to seconds. Timer modes 10/11 (System Timer Low/High) are documented here:

 

http://labjack.com/s...guide/2.10.1.10



#13 TrentG

TrentG
  • Members
  • 2 posts

Posted 18 November 2013 - 09:34 PM

Thank you LabJack Support. I didn't realise that the internal clock ran at 750kHz. I understand my mistake, I've corrected it and it all works now!

Many thanks!



#14 Lingue

Lingue
  • Members
  • 27 posts

Posted 11 February 2014 - 12:37 AM

Hi every one, I'm a newbie . 

I'm buy Labjack UE9.. and i will try this. but i dont know to start 1st step?

i'm using Ubuntu 13.10 to acces this ue9

can anyone help me to teach me how to learn this ue9 for beginer? 

i dont know how to use this ue9 , please



#15 Lingue

Lingue
  • Members
  • 27 posts

Posted 11 February 2014 - 01:06 AM

hi.. i have a question . how to turn on or turn off led in ue9 im using python 



#16 LabJack Support

LabJack Support
  • Admin
  • 8677 posts

Posted 11 February 2014 - 02:35 PM

Lingue, I'll respond to your posts in the topic you started with the same question.

 

https://forums.labja...?showtopic=6624




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users