-
Notifications
You must be signed in to change notification settings - Fork 0
/
devices.py
3389 lines (2695 loc) · 119 KB
/
devices.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
devices.py contains unified LabJack classes for the U3, U6 and T7.
A common set of methods is implemented, simplifying writing code for any
of the devices listed above.
The classes are built using the existing LabJack python packages:
- LabJackPython
- labjack-ljm-python
Note: Use code folding at the method level to improve readability.
Author: Eduardo Nigro
rev 0.0.3
2021-12-13
"""
import re
import time
import numpy as np
# Importing LJM and LJM classes used in
# the LabJackT7 class
from labjack.ljm import ljm, LJMError
# Importing LabJackPython classes and functions used in
# the LabJackU3 and LabJackU6 classes
import u3, u6
import ctypes
from LabJackPython import (
LabJackException,
_loadLibrary,
ePut,
eGet,
AddRequest,
GoOne
)
# Importing constants used in the LabJackU3 and LabJackU6 classes
# See LabJackPython.py for more details on each constant
from LabJackPython import (
LJ_chALL_CHANNELS,
LJ_chNUMBER_TIMERS_ENABLED,
LJ_chSTREAM_BACKLOG_COMM,
LJ_chSTREAM_BACKLOG_UD,
LJ_chSTREAM_BUFFER_SIZE,
LJ_chSTREAM_SCAN_FREQUENCY,
LJ_chSTREAM_WAIT_MODE,
LJ_chTIMER_CLOCK_BASE,
LJ_chTIMER_CLOCK_DIVISOR,
LJ_chTIMER_COUNTER_PIN_OFFSET,
LJ_ioADD_STREAM_CHANNEL,
LJ_ioCLEAR_STREAM_CHANNELS,
LJ_ioGET_AIN,
LJ_ioGET_AIN_DIFF,
LJ_ioGET_ANALOG_ENABLE_PORT,
LJ_ioGET_CONFIG,
LJ_ioGET_DIGITAL_BIT,
LJ_ioGET_DIGITAL_BIT_DIR,
LJ_ioGET_STREAM_DATA,
LJ_ioGET_TIMER,
LJ_ioPIN_CONFIGURATION_RESET,
LJ_ioPUT_AIN_RANGE,
LJ_ioPUT_ANALOG_ENABLE_BIT,
LJ_ioPUT_ANALOG_ENABLE_PORT,
LJ_ioPUT_CONFIG,
LJ_ioPUT_DAC,
LJ_ioPUT_DIGITAL_BIT,
LJ_ioPUT_TIMER_MODE,
LJ_ioPUT_TIMER_VALUE,
LJ_ioSTART_STREAM,
LJ_ioSTOP_STREAM,
LJ_rgBIP10V,
LJ_rgBIP1V,
LJ_rgBIPP1V,
LJ_rgBIPP01V,
LJ_swNONE,
LJ_tc48MHZ,
LJ_tc48MHZ_DIV,
LJ_tmPWM16,
LJ_tmQUAD,
)
class LabJackU3:
"""
The class to represent the LabJack U3.
:param serialnum: The device serial number.
:type serialnum: int
Ports that are made available with this class are listed below.
The port names assume a U3-HV.
* Analog Output: ``'DAC0'``, ``'DAC1'``
* Analog Input: ``'AIN0'``, ``'AIN1'``, ``'AIN2'``, ``'AIN3'``
* Flexible I/O: ``'FIO4'``, ``'FIO5'``, ``'FIO6'``, ``'FIO7'``,
* Flexible I/O: ``'EIO0'``, ``'EIO1'``, ... , ``'EIO7'``
Device-specific methods:
* `get_config` - Gets port configuration
* `reset_config` - Resets port configuration to factory defaults
* `get_bitdir` - Gets digital port bit direction
Connect to the first found U3:
>>> from labjack_unified.devices import LabJackU3
>>> lju3 = LabJackU3()
>>> lju3.display_info()
>>> lju3.close()
You can also connect to a specific device using its serial number:
>>> lju3 = LabJackU3(320012345)
"""
# CONSTRUCTOR METHODS
def __init__(self, serialnum=None):
"""
Class constructor
"""
self._staticlib = _loadLibrary()
# Attempting to open the device
try:
if serialnum:
# Opens LabJack with specific serial number
self._commhandle = u3.U3(autoOpen=False)
self._commhandle.open(serial=serialnum)
else:
# Opens first available LabJack
self._commhandle = u3.U3(autoOpen=False)
self._commhandle.open()
except LabJackException as error:
print(error)
else:
self._numports = 16
self._assign_info(self._commhandle.configU3())
self._assign_ports()
self.reset_config()
print('Opened LabJack', self._serialnum)
def close(self):
"""
Close the U3 device connection.
>>> lju3.close()
"""
self._staticlib.Close(self._commhandle.handle)
print('Closed LabJack', self._serialnum)
def display_info(self):
"""
Display a summary with the U3 device information.
"""
print('____________________________________________________________')
print('Device Name........', self._type)
print('Serial Number......', self._serialnum)
print('Hardware Version...', self._hardware)
print('Firmware Version...', self._firmware)
print('Connection Type....', self._connection)
print('____________________________________________________________')
# I/O METHODS
def set_config(self, name, config):
"""
Set the LabJack flexible IO port configuration.
:param name: The port name to configure.
:type name: str
:param config: The configuration option.
If `name` is ``'ALL'`` a string of mask bits for all 16 ports
is used. For single port, `config` can be either a string
``'analog'`` or ``'digital'``. Alternativelly, 1 or 0 can be used.
:type config: str, int
Configure flexible ports ``'FIO4'`` and ``'FIO5'`` as analog:
>>> lju3.set_config('FIO4', 'analog')
>>> lju3.set_config('FIO5', 1)
Configure flexible ports ``'EIO0'`` and ``'EIO1'`` as digital:
>>> lju3.set_config('EIO0', 'digital')
>>> lju3.set_config('EIO1', 0)
Configure flexible ports ``'EI01'`` and ``'EI03'`` as analog and
ports ``'AIN0'`` to ``'AIN3'`` to analog (if a U3-LV is used):
>>> lju3.set_config('ALL', '0000101000001111')
.. note::
1. LSB (Least Significant Bit) is port ``'AIN0'``.
2. On a U3-HV, the first 4 ports are always analog and the first 4 LSB settings are ignored.
"""
if name.lower() == 'all':
# Checking for correct mask string length
if len(config) == self._numports:
ePut(self._commhandle.handle, LJ_ioPUT_ANALOG_ENABLE_PORT,
0, int(config, 2), self._numports)
else:
raise Exception("'ALL' ports CONFIG must be 16-bit string.")
else:
# Checking for valid input port names
if not self._check_port(name, "AIN"):
raise Exception('Invalid flexible IO port name.')
# Checking for valid configuration options
if type(config) == str:
if config.lower() == 'analog':
config = 1
elif config.lower() == 'digital':
config = 0
else:
raise Exception(
"Port configuration must be either 'DIGITAL' or 'ANALOG'.")
else:
if (config != 0) and (config != 1):
raise Exception('Port configuration must be either 0 or 1')
ePut(self._commhandle.handle, LJ_ioPUT_ANALOG_ENABLE_BIT,
self._get_AINnumber(name), config, 0)
def get_config(self, name='ALL'):
"""
Get the LabJack flexible IO port configuration.
:param name: The port name to get the configuration.
If `name` is ``'ALL'`` a dictionary with keys `EIOAnalog` and
`FIOAnalog` is returned.
:type name: str
:returns: For single port `name`, an integer is returned, where
`1=Analog` and `0=Digital`. If `name` is ``'ALL'`` a dictionary
containing the bit mask string for the `EIO` and `FIO` ports is
returned. The least significant bit (LSB) of the `EIO` and `FIO`
bit strings correspond respectively to ports ``'EIO0'`` and
``'FIO0'``.
:rtype: int, dict
Get flexible port configuration:
>>> lju3.get_config()
.. note::
In the case of a LabJack U3-HV, the four LSBs of the `FIO` ports
are always `1s`. They correspond to the always analog ports
``'AIN0'`` to ``'AIN3'``.
"""
mask = eGet(self._commhandle.handle, LJ_ioGET_ANALOG_ENABLE_PORT,
0, 0, self._numports)
mask = '{:016b}'.format(int(mask))
if name.lower() == 'all':
config = {
'EIOAnalog': mask[0:8],
'FIOAnalog': mask[8::]
}
else:
if not self._check_port(name, "AIN"):
raise Exception('Invalid flexible IO port name.')
config = int(mask[self._numports - self._get_AINnumber(name) - 1])
return config
def reset_config(self):
"""
Reset the flexible IO ports to default all digital.
>>> lju3.reset_config()
.. note::
On the LabJack U3-HV the first 4 ports ``'AIN0'`` to ``'AIN3'``
are always analog.
"""
ePut(self._commhandle.handle, LJ_ioPIN_CONFIGURATION_RESET, 0, 0, 0)
def set_digital(self, name, state):
"""
Write the digital state to an output port.
It also sets the port direction to output.
:param name: The port name to set the state.
:type name: str
:param state: The digital state `0 = Low`, `1 = High`.
:type state: int
Set port ``'FIO4'`` output to high and port ``'FIO5'`` to low:
>>> lju3.set_digital('FIO4', 1)
>>> lju3.set_digital('FIO5', 0)
"""
# Checking for valid inputs
if not self._check_port(name, "AIN"):
raise Exception('Invalid flexible IO port name.')
if (state != 0) and (state != 1):
raise Exception('Port state must be either 1 or 0')
# Setting port state by port number
ePut(self._commhandle.handle, LJ_ioPUT_DIGITAL_BIT,
self._get_AINnumber(name), state, 0)
def get_digital(self, name):
"""
Read the digital state from an input port.
It also sets the port direction to input.
:param name: The port name to get the state.
:type name: str
:returns: The state of the digital port. `0 = Low`, `1 = High`.
:rtype: int
Get port ``'FIO6'`` input state:
>>> lju3.get_digital('FIO6')
"""
# Checking for valid inputs
if not self._check_port(name, "AIN"):
raise Exception('Invalid flexible IO port name.')
# Getting port state by port number
state = int(eGet(self._commhandle.handle, LJ_ioGET_DIGITAL_BIT,
self._get_AINnumber(name), 0, 0))
return state
def get_bitdir(self, name):
"""
Read the direction of the digital port.
:param name: The port name to get the direction.
:type name: str
:returns: The direction of the digital port. `Input` or `Output`.
:rtype: str
Get the direction of port ``'FIO6'``:
>>> lju3.get_bitdir('FIO6')
"""
# Checking for valid input port names
if not self._check_port(name, "AIN"):
raise Exception('Invalid analog input port name.')
# Getting digital port bit direction
value = eGet(self._commhandle.handle, LJ_ioGET_DIGITAL_BIT_DIR,
self._get_AINnumber(name), 0, 0)
if value == 0:
bitdir = 'input'
else:
bitdir = 'output'
return bitdir
def set_analog(self, name, value):
"""
Set analog output voltage.
:param name: The port name to set the output voltage.
Available ports are ``'DAC0'`` and ``'DAC1'``.
:type name: str
:param value: The output voltage between ``0`` and ``5`` V.
:type value: float
Set port ``'DAC1'`` output voltage to ``2.2`` V:
>>> lju3.set_analog('DAC1', 2.2)
"""
# Checking for valid input port names
if not self._check_port(name, "DAC"):
raise Exception('Invalid analog output port name.')
# Getting corresponding port number
DACnumber = self._get_DACnumber(name)
# Limiting analog values
if value > 5: value = 5
if value < 0: value = 0
# Setting analog port output voltage
ePut(self._commhandle.handle, LJ_ioPUT_DAC, DACnumber, value, 0)
def get_analog(self, namepos, *args):
"""
Get analog input voltage.
:param name: The positive port name to get the voltage.
:type name: str
:param args: Can be one of the three options:
* ``'single-ended'`` (default value)
* The negative port name to get a differential voltage.
* ``'special'`` to get increased range on the voltage reading.
:type args: str
:returns: The input voltage value.
* On a U3-HV, the range for ports ``'AIN0'`` to ``'AIN3'`` is +/-10 V
* On a U3-HV, ``'special'`` enables a range of -10 to +20 V
* `FIO` ports have a range of +/- 2.4 V
* `FIO` ports using ``'special'`` have a range of 0 to 3.6 V
:rtype: float
Get single-ended voltage on port ``'FIO2'``:
>>> lju3.get_analog('FIO2')
Get differential voltage betweens ports ``'AIN0'`` and ``'AIN1'``:
>>> lju3.get_analog('AIN0', 'AIN1')
Get special range voltage on port ``'FIO3'``:
>>> lju3.get_analog('FIO3', 'special')
"""
# Checking for differential measurement
if len(args) > 0:
nameneg = args[0]
else:
nameneg = 'single-ended'
# Checking for valid input port names
if not self._check_port([namepos, nameneg], "AIN"):
raise Exception('Invalid analog input port name.')
# Getting corresponding port numbers
AINpos = self._get_AINnumber(namepos)
if nameneg.lower() == 'single-ended':
AINneg = 31
elif nameneg.lower() == 'special':
AINneg = 32
else:
AINneg = self._get_AINnumber(nameneg)
# Getting analog input voltage
value = eGet(self._commhandle.handle,
LJ_ioGET_AIN_DIFF, AINpos, 0, AINneg)
return value
# STREAMING METHODS
def set_stream(self, names, scanrate=50000, readrate=0.5):
"""
Set and start data streaming.
:param name: The port name (or list of names) to be streamed.
:type name: str, list(str)
:param scanrate: The scan rate (Hz) of the data streaming.
The default (and maximum) value is ``50000`` Hz. The effective scan
frequency of each port is the scan rate divided by the number of
scanned ports.
:type scanrate: int
:param readrate:
The rate in seconds at which blocks of data are retrieved from the
data buffer. The default value is ``0.5`` seconds.
:type readrate: float
Set data streaming on port ``'AIN0'`` at ``25000`` Hz, every ``0.5`` s:
>>> lju3.set_stream('AIN0', scanrate=25000, readrate=0.5)
Set data streaming on ports ``'AIN0'`` and ``'AIN1'`` at ``50000`` Hz,
every ``1.0`` s:
>>> lju3.set_stream(['AIN0', 'AIN1'], scanrate=50000, readrate=1.0)
.. note::
Only analog input ports ``'AIN0'`` to ``'AIN3'`` can be
streamed. Hence, a Labjack U3-HV has to be used. While it's
possible to stream digital ports, that hasn't been implemented
in this release.
"""
# Assigning streamed data block read-in rate (s)
self._streamreadrate = readrate
# Assigning buffer size as 2 times block length (s)
self._streambuffersize = 2*self._streamreadrate
# Assigning data block scan rate (Hz)
self._scanrate = scanrate
# Checking for valid input port names
if not self._check_port(names, "AIN"):
raise Exception('Invalid input port name.')
# Getting port numbers
if type(names) != list:
names = [names]
portnum = []
for name in names:
portnum.append(self._get_AINnumber(name))
# Assigning number of streaming ports
self._streamnumchannels = len(portnum)
# Updating scan frequency per port (Hz)
self._streamscanfreq = int(self._scanrate/self._streamnumchannels)
# Clearing streaming ports
ePut(self._commhandle.handle, LJ_ioCLEAR_STREAM_CHANNELS, 0, 0, 0)
# Adding ports to scan list
for num in portnum:
ePut(self._commhandle.handle, LJ_ioADD_STREAM_CHANNEL, num, 0, 0)
# Assigning scanning frequency
ePut(self._commhandle.handle, LJ_ioPUT_CONFIG,
LJ_chSTREAM_SCAN_FREQUENCY, self._streamscanfreq, 0)
# Assigning buffer size
ePut(self._commhandle.handle, LJ_ioPUT_CONFIG, LJ_chSTREAM_BUFFER_SIZE,
self._scanrate*self._streambuffersize, 0)
# Configuring reads to retrieve whatever data is available without waiting
ePut(self._commhandle.handle, LJ_ioPUT_CONFIG,
LJ_chSTREAM_WAIT_MODE, LJ_swNONE, 0)
# Starting streaming
ePut(self._commhandle.handle, LJ_ioSTART_STREAM, 0, 0, 0)
def stop_stream(self):
"""
Stop data streaming.
>>> lju3.stop_stream()
"""
ePut(self._commhandle.handle, LJ_ioSTOP_STREAM, 0, 0, 0)
def get_stream(self):
"""
Get streaming data block.
:returns: 5-tuple
* dt
The sampling period (s) between each data point.
* data
The numpy `m-by-n` array containing the streamed data where
`m` is the number of samples per port in the block and `n`
is the number of ports defined in `set_stream`
* numscans
The actual number of scans per port in the data block.
* commbacklog
The communication backlog in % (increasing values indicate that
the computer cannot keep up with the data download from the U3
driver)
* devbacklog
The U3 device backlog in % (increasing values indicate that the
device cannot keep up with the data streaming - usually not
the case)
:rtype: (float, ndarray, int, float, float)
Retrieve scan period, data, and scan info:
>>> dt, datablock, numscans, commbacklog, U3backlog = lju3.get_stream()
"""
# Defining initial number of samples per channnel
# (double the size for safety)
numscans = 2 * self._streamreadrate * self._streamscanfreq
# Preallocating output array
datasamples = np.zeros(int(numscans)*self._streamnumchannels)
numscansactual, datalong = self._eGetArray(
self._commhandle.handle, LJ_ioGET_STREAM_DATA,
LJ_chALL_CHANNELS, numscans, datasamples)
# Separating ports
numscansactual = int(numscansactual)
nrow = numscansactual
ncol = self._streamnumchannels
data = np.array(datalong)
data = data[0:nrow*ncol].reshape(nrow, ncol)
# Calculating sample period (s)
dt = 1/self._streamscanfreq
# Calculating communication backlog (%)
commbacklog = eGet(self._commhandle.handle,
LJ_ioGET_CONFIG, LJ_chSTREAM_BACKLOG_COMM, 0, 0)
commbacklog = 100 * commbacklog/numscansactual
# Calculating LabJack device backlog (%)
devbacklog = eGet(self._commhandle.handle,
LJ_ioGET_CONFIG, LJ_chSTREAM_BACKLOG_UD, 0, 0)
devbacklog = 100 * devbacklog/numscansactual
# Returning streamed data block parameters
return dt, data, numscansactual, commbacklog, devbacklog
# PWM METHODS
def set_pwm(self, pwmnum=1, dirport1=None, dirport2=None, frequency=366):
"""
Configure PWM output.
:param pwmnum: The number of PWM output signals.
``1`` or ``2`` PWMs can be used. For one PWM, the output port is
``'FIO4'``. For two PWMs, the output ports are ``'FIO4'`` and
``'FIO5'``.
:type pwmnum: int
:param dirport1: The type of ports that control the PWM `direction`
for electric motor control. There are three options:
* ``None`` - Default value (no direction ports are used)
* ``'DAC'`` - Uses analog ports ``'DAC0'`` and ``'DAC1'``
* ``'DIO'`` - Uses digital ports ``'FIO6'`` and ``'FIO7'``
:type dirport1: None, str
:param dirport2: Same as `dirport1`.
It's used when two PWM outputs are enabled. The ``'DAC'`` option
can only be used for one set of direction ports, unless the two
motors are running synchronously. For the ``'DIO'`` option,
digital ports ``'EIO0'`` and ``'EIO1'`` are used.
:type dirport2: None, str
:param frequency: The PWM signal frequency in Hz.
In the case of two PWMs, both will have the same frequency. Valid
values are ``183``, ``366`` or ``732``.
:type frequency: int
Set 1 PWM for motor control on ``'FIO4'`` with direction ports on
``'DAC0'`` and ``'DAC1'``. The PWM frequency is the default ``366`` Hz:
>>> lju3.set_pwm(dirport1='DAC')
Set 2 PWMs on ports ``'FIO4'`` and ``'FIO5'`` with a frequency of
``183`` Hz:
>>> lju3.set_pwm(pwmnum=2, frequency=183)
Set 2 PWMs for motor control on ports ``'FIO4'`` and ``'FIO5'``, using
the digital ports ``'FIO6'`` and ``'FIO7'`` for motor 1 direction, and
``'EIO0'`` and ``'EIO1'`` for motor 2 direction. The PWM frequency is
``732`` Hz:
>>> lju3.set_pwm(pwmnum=2, dirport1='DIO', dirport2='DIO', frequency=732)
.. note::
When using digital ports, a 10 kOhm resistor has to be connected from
the LabJack `VS` port to each one of the `DIO` ports to ensure true
`high` and `low` states.
"""
# Defining PWM frequency divisors and checking input
pwmfreq = {
'183': 4,
'366': 2,
'732': 1
}
if str(frequency) not in list(pwmfreq.keys()):
raise Exception(
"Valid PWM frequencies are 183, 366, and 732 Hz.")
# Checking number of PWM outputs and direction ports
dirport = [dirport1, dirport2]
pwmname = ['FIO4']
pwmdir = [None]
self._pwmtype = [1]
if dirport[0] == 'DAC':
pwmdir[0] = ['DAC0', 'DAC1']
self._pwmtype[0] = 0
elif dirport[0] == 'DIO':
pwmdir[0] = ['FIO6', 'FIO7']
if pwmnum == 2:
self._pwmtype.append(1)
pwmname.append('FIO5')
if dirport[1] is None:
pwmdir.append(None)
if dirport[1] == 'DAC':
pwmdir.append(['DAC0', 'DAC1'])
self._pwmtype[1] = 0
elif dirport[1] == 'DIO':
pwmdir.append(['EIO0', 'EIO1'])
# Assigning PWM attributes
self._pwmnum = pwmnum
self._pwmname = pwmname
self._pwmdir = pwmdir
self._pwmfreq = frequency
# Assinging frequency divisor
divisor = pwmfreq[str(frequency)]
# Assigning PWM pin offset
# (always 4 since the timers always start on FIO4)
pinoffset = 4
# Resetting pin configuration
ePut(self._commhandle.handle, LJ_ioPIN_CONFIGURATION_RESET, 0, 0, 0)
# Setting the pin offset for the timers
AddRequest(self._commhandle.handle, LJ_ioPUT_CONFIG,
LJ_chTIMER_COUNTER_PIN_OFFSET, pinoffset, 0, 0)
# Configuring the timer clock to 48 MHz
AddRequest(self._commhandle.handle, LJ_ioPUT_CONFIG,
LJ_chTIMER_CLOCK_BASE, LJ_tc48MHZ_DIV, 0, 0)
# Setting clock Divisor
AddRequest(self._commhandle.handle, LJ_ioPUT_CONFIG,
LJ_chTIMER_CLOCK_DIVISOR, divisor, 0, 0)
# Enabling 1 or 2 timers
AddRequest(self._commhandle.handle, LJ_ioPUT_CONFIG,
LJ_chNUMBER_TIMERS_ENABLED, pwmnum, 0, 0)
for num in range(pwmnum):
# Setting timer to 16 bits
# Frequency = (48MHz/Divisor ) / 2^16 Hz
AddRequest(self._commhandle.handle, LJ_ioPUT_TIMER_MODE,
num, LJ_tmPWM16, 0, 0)
# Setting timer duty cycle to 0%
AddRequest(self._commhandle.handle, LJ_ioPUT_TIMER_VALUE,
num, 0, 0, 0)
# Sending command sequence
GoOne(self._commhandle.handle)
def set_dutycycle(self, value1=None, value2=None, brake1=False, brake2=False):
"""
Set PWM duty cycle value.
:param value1: The PWM 1 duty cycle percent value between ``-100``
and ``100``.
:type value1: float
:param value2: The PWM 2 duty cycle percent value between ``-100``
and ``100``.
:type value2: float
:param brake1: The motor 1 brake option used when dutycycle is zero.
Brake is applied when ``True``. Motor is floating when ``False``.
:type brake1: bool
:param brake2: The motor 2 brake option used when dutycycle is zero.
Brake is applied when ``True``. Motor is floating when ``False``.
:type brake2: bool
Set duty cycle to ``50`` % on PWM 1:
>>> lju3.set_dutycycle(value1=50)
Set duty cycle to ``25`` % (reverse rotation) on PWM 2:
>>> lju3.set_dutycycle(value2=-25)
Set duty cycle to ``20`` % and ``40`` % on PWMs 1 and 2:
>>> lju3.set_dutycycle(value1=20, value2=40)
Stop motor 2 and apply brake:
>>> lju3.set_dutycycle(value2=0, brake2=True)
.. note::
1. Avoid suddenly switching the direction of rotation to avoid damaging the motor.
2. You can use the brake option True to hold the motor in position.
"""
values = [value1, value2]
brakes = [brake1, brake2]
for pwmnum, (value, brake, pwmdir, pwmtype) in enumerate(zip(
values, brakes, self._pwmdir, self._pwmtype)):
if value is not None:
# Applying bounds to inputs
if value > 100:
value = 100
if value < -100:
value = -100
# Applying PWM direction
if pwmdir:
if value > 0:
# Forward rotation
if pwmtype == 0:
self.set_analog(pwmdir[0], 4.5)
self.set_analog(pwmdir[1], 0)
else:
self.set_digital(pwmdir[0], 0)
self.get_digital(pwmdir[1])
elif value < 0:
# Reverse rotation
if pwmtype == 0:
self.set_analog(pwmdir[0], 0)
self.set_analog(pwmdir[1], 4.5)
else:
self.get_digital(pwmdir[0])
self.set_digital(pwmdir[1], 0)
elif value == 0:
# Brake stop
if brake:
if pwmtype == 0:
self.set_analog(pwmdir[0], 0)
self.set_analog(pwmdir[1], 0)
else:
self.set_digital(pwmdir[0], 0)
self.set_digital(pwmdir[1], 0)
else:
if pwmtype == 0:
self.set_analog(pwmdir[0], 4.5)
self.set_analog(pwmdir[1], 4.5)
else:
self.get_digital(pwmdir[0])
self.get_digital(pwmdir[1])
# Calculating duty cycle
dutycycle = np.ceil(65535*(1-np.abs(value)/100))
# Setting timer duty cycle to desired value
AddRequest(self._commhandle.handle, LJ_ioPUT_TIMER_VALUE,
pwmnum, dutycycle, 0, 0)
# Sending command sequence
GoOne(self._commhandle.handle)
# QUADRATURE ENCODER METHODS
def set_quadrature(self, zphase1=False):
"""
Configure quadrature encoder input on ports ``'FIO4'`` and ``'FIO5'``.
:param zphase1: The logic value indicating if a `Z` phase reference
pulse is used on port ``'FIO6'``.
:type zphase1: bool
Set ports ``'FIO4'`` and ``'FIO5'`` for encoder phase `A` and `B`
signals:
>>> lju3.set_quadrature()
Set ports ``'FIO4'`` and ``'FIO5'`` for encoder phase `A` and `B`
signals and port ``'FIO6'`` for the reference `Z` phase:
>>> lju3.set_quadrature(zphase1=True)
"""
# Checking input arguments
quadnameAB = ['FIO4', 'FIO5']
portnumZ = 0
if zphase1:
portnumZ = 32768 + self._get_AINnumber('FIO6')
# Assigning A-B port names
self._zphase1 = zphase1
self._quadnameAB = quadnameAB
# Assigning quadrature port pin offset
pinoffset = self._get_AINnumber(quadnameAB[0])
# Resetting pin configuration
ePut(self._commhandle.handle, LJ_ioPIN_CONFIGURATION_RESET, 0, 0, 0)
# Setting the pin offset for the timers
AddRequest(self._commhandle.handle, LJ_ioPUT_CONFIG,
LJ_chTIMER_COUNTER_PIN_OFFSET, pinoffset, 0, 0)
# Configuring the timer clock to 48 MHz
AddRequest(self._commhandle.handle, LJ_ioPUT_CONFIG,
LJ_chTIMER_CLOCK_BASE, LJ_tc48MHZ, 0, 0)
# Enabling 2 timers
AddRequest(self._commhandle.handle, LJ_ioPUT_CONFIG,
LJ_chNUMBER_TIMERS_ENABLED, 2, 0, 0)
# Setting quadrature mode
AddRequest(self._commhandle.handle, LJ_ioPUT_TIMER_MODE,
0, LJ_tmQUAD, 0, 0)
AddRequest(self._commhandle.handle, LJ_ioPUT_TIMER_MODE,
1, LJ_tmQUAD, 0, 0)
# Setting timer values to add Z port (or reset in case there's no Z)
AddRequest(self._commhandle.handle, LJ_ioPUT_TIMER_VALUE,
0, portnumZ, 0, 0)
AddRequest(self._commhandle.handle, LJ_ioPUT_TIMER_VALUE,
1, portnumZ, 0, 0)
# Sending command sequence
GoOne(self._commhandle.handle)
def get_counter(self):
"""
Get current quadrature counter value.
:returns: The counter value.
:rtype: int
>>> lju3.get_counter()
.. note::
Because the qudrature counter counts rising and falling edges
of phases `A` and `B`, a 1024 pulse/rev encoder will generate 4096
counts for a full shaft turn.
"""
value = int(eGet(self._commhandle.handle, LJ_ioGET_TIMER, 0, 0, 0))
return value
def reset_counter(self):
"""
Reset quadrature counter value.
>>> lju3.reset_counter()
.. note::
The count is only reset when a `Z` phase isn't being used.
"""
if not self._zphase1:
AddRequest(self._commhandle.handle, LJ_ioPUT_TIMER_VALUE,
0, 0, 0, 0)
AddRequest(self._commhandle.handle, LJ_ioPUT_TIMER_VALUE,
1, 0, 0, 0)
# Sending command sequence
GoOne(self._commhandle.handle)
# OTHER METHODS
def get_labjacktemp(self, unit='C'):
"""
Get ambient temperature from LabJack's internal sensor.
:param unit: The temperature measurement unit.
Valid values are ``'C'`` or ``'F'``. Default unit is ``'C'``.
:type unit: str
:returns: The internal sensor temperature reading.
:rtype: float
Get temperature reading in `Celsius`:
>>> lju3.get_labjacktemp()
Get temperature reading in `Fahrenheit`:
>>> lju3.get_labjacktemp(unit='F')
"""
tempabs = eGet(self._commhandle.handle, LJ_ioGET_AIN, 30, 0, 0)
if unit == 'C':
temp = tempabs - 273.15
elif unit == 'F':
temp = 9/5*(tempabs-273.15) + 32
else:
raise Exception(
"Temperature units must be either 'degC' or 'degF'.")
return temp
# HELPER METHODS (PRIVATE)
def _eGetArray(self, Handle, IOType, Port, pValue, x1):
"""
Perform one call to the LabJack Device returning a data array.
This method was created to complement the eGet() function in
LabJackPyhon. It's used primarily in data streaming and like all
the other C library functions, it is limited to a Windows platform.
"""
pv = ctypes.c_double(pValue)
xv = (ctypes.c_double * len(x1))()
ec = self._staticlib.eGet_DblArray(
Handle, IOType, Port, ctypes.byref(pv), ctypes.byref(xv))
if ec != 0:
raise LabJackException(ec)
return pv.value, xv
def _assign_info(self, info):
# Assigning info collected from LabJack handle to private attributes
self._type = info['DeviceName']
self._serialnum = info['SerialNumber']
self._connection = 'USB'
self._hardware = info['HardwareVersion']
self._firmware = info['FirmwareVersion']
def _assign_ports(self):
"""
Creates lists with valid LabJack U3 port names
"""
# Assigning analog output port names
self._portDAC = [
'DAC0', 'DAC1']
# Assigning analog / FIO inout port names
self._portAIN = [
'AIN0', 'AIN1', 'AIN2', 'AIN3', 'FIO4', 'FIO5', 'FIO6', 'FIO7',
'EIO0', 'EIO1', 'EIO2', 'EIO3', 'EIO4', 'EIO5', 'EIO6', 'EIO7']
self._portAINalt = [
'FIO0', 'FIO1', 'FIO2', 'FIO3', 'AIN4', 'AIN5', 'AIN6', 'AIN7',
'AIN8', 'AIN9', 'AIN10', 'AIN11', 'AIN12', 'AIN13', 'AIN14', 'AIN15']
self._portAINsp = ['SINGLE-ENDED', 'SPECIAL']
def _check_port(self, namelist, porttype, *args):