forked from labjack/LabJackPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathu3.py
More file actions
2908 lines (2317 loc) · 105 KB
/
Copy pathu3.py
File metadata and controls
2908 lines (2317 loc) · 105 KB
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
"""
Name: u3.py
Desc: Defines the U3 class, which makes working with a U3 much easier. All of
the low-level functions for the U3 are implemented as functions of the U3
class. There are also a handful additional functions which improve upon
the interface provided by the low-level functions.
To learn about the low-level functions, please see Section 5.2 of the U3 User's Guide:
http://labjack.com/support/u3/users-guide/5.2
Section Number Mapping:
1 = Object Functions
2 = User's Guide Functions
3 = Convenience Functions
4 = Private Helper Functions
"""
import collections
import sys
import warnings
try:
import ConfigParser
except ImportError: # Python 3
import configparser as ConfigParser
from struct import pack, unpack
from LabJackPython import (
Device,
deviceCount,
LabJackException,
LowlevelErrorException,
lowlevelErrorToString,
MAX_USB_PACKET_LENGTH,
setChecksum8,
toDouble,
)
FIO0, FIO1, FIO2, FIO3, FIO4, FIO5, FIO6, FIO7, \
EIO0, EIO1, EIO2, EIO3, EIO4, EIO5, EIO6, EIO7, \
CIO0, CIO1, CIO2, CIO3 = range(20)
def openAllU3():
"""
A helpful function which will open all the connected U3s. Returns a
dictionary where the keys are the serialNumber, and the value is the device
object.
"""
returnDict = dict()
for i in range(deviceCount(3)):
d = U3(firstFound = False, devNumber = i+1)
returnDict[str(d.serialNumber)] = d
return returnDict
class U3(Device):
"""
U3 Class for all U3 specific low-level commands.
Example:
>>> import u3
>>> d = u3.U3()
>>> print(d.configU3())
{'SerialNumber': 320032102, ... , 'FirmwareVersion': '1.26'}
"""
def __init__(self, debug = False, autoOpen = True, **kargs):
"""
Name: U3.__init__(debug = False, autoOpen = True, **openArgs)
Args: debug, enables debug output
autoOpen, if true, the class will try to open a U3 using openArgs
**openArgs, the arguments to pass to the open call. See U3.open()
Desc: Instantiates a new U3 object. If autoOpen == True, then it will
also open a U3.
Examples:
Simplest:
>>> import u3
>>> d = u3.U3()
For debug output:
>>> import u3
>>> d = u3.U3(debug = True)
To open a U3 with Local ID = 2:
>>> import u3
>>> d = u3.U3(firstFound = False, localId = 2)
"""
Device.__init__(self, None, devType = 3)
self.debug = debug
self.calData = None
self.ledState = True
if autoOpen:
self.open(**kargs)
__init__.section = 1
def open(self, firstFound = True, serial = None, localId = None, devNumber = None, handleOnly = False, LJSocket = None):
"""
Name: U3.open(firstFound = True, localId = None, devNumber = None,
handleOnly = False, LJSocket = None)
Args: firstFound, If True, use the first found U3
serial, open a U3 with the given serial number
localId, open a U3 with the given local id.
devNumber, open a U3 with the given devNumber
handleOnly, if True, LabJackPython will only open a handle
LJSocket, set to "<ip>:<port>" to connect to LJSocket
Desc: Use to open a U3. If handleOnly is false, it will call configU3
and save the resulting information to the object. This allows the
use of d.serialNumber, d.firmwareVersion, etc.
Examples:
Simplest:
>>> import u3
>>> d = u3.U3(autoOpen = False)
>>> d.open()
Handle-only, with a serial number = 320095789:
>>> import u3
>>> d = u3.U3(autoOpen = False)
>>> d.open(handleOnly = True, serial = 320095789)
Using LJSocket:
>>> import u3
>>> d = u3.U3(autoOpen = False)
>>> d.open(LJSocket = "localhost:6000")
"""
Device.open(self, 3, firstFound = firstFound, serial = serial, localId = localId, devNumber = devNumber, handleOnly = handleOnly, LJSocket = LJSocket )
open.section = 1
def configU3(self, LocalID = None, TimerCounterConfig = None, FIOAnalog = None, FIODirection = None, FIOState = None, EIOAnalog = None, EIODirection = None, EIOState = None, CIODirection = None, CIOState = None, DAC1Enable = None, DAC0 = None, DAC1 = None, TimerClockConfig = None, TimerClockDivisor = None, CompatibilityOptions = None):
"""
Name: U3.configU3(LocalID = None, TimerCounterConfig = None,
FIOAnalog = None, FIODirection = None,
FIOState = None, EIOAnalog = None,
EIODirection = None, EIOState = None,
CIODirection = None, CIOState = None,
DAC1Enable = None, DAC0 = None,
DAC1 = None, TimerClockConfig = None,
TimerClockDivisor = None, CompatibilityOptions = None)
Args: See section 5.2.2 of the users guide.
Desc: Sends the low-level configU3 command. Also saves relevant
information to the U3 object for later use.
Note: Analog, Direction, and State parameters are binary-encoded,
8-bit values where each bit corresponds to individual line
setting. The setting for FIO0/EIO0/CIO0 is on bit 0,
FIO1/EIO1/CIO1 is on bit 1, FIO2/EIO2/CIO2 is on bit 2, etc.
For example, to set FIO0 and FIO6 to outputs by default, the value
for FIODirection is 65 which in binary is b01000001. This can be
calculated with 2^6 + 2^0 = 65, where 2^6 = 64, and 2^0 = 1.
Example:
Simplest:
>>> import u3
>>> d = u3.U3()
>>> print(d.configU3())
{
'LocalID': 1,
'SerialNumber': 320035782,
'DeviceName': 'U3-LV',
'FIODirection': 0,
'FirmwareVersion': '1.24',
... ,
'ProductID': 3
}
Configure all FIOs and EI0s to analog on boot:
>>> import u3
>>> d = u3.U3()
>>> print(d.configU3(FIOAnalog = 255, EIOAnalog = 255))
{
'FIOAnalog': 255,
'EIOAnalog': 255,
... ,
'ProductID': 3
}
"""
writeMask = 0
if FIOAnalog is not None or FIODirection is not None or FIOState is not None or EIOAnalog is not None or EIODirection is not None or EIOState is not None or CIODirection is not None or CIOState is not None:
writeMask |= 2
if DAC1Enable is not None or DAC0 is not None or DAC1 is not None:
writeMask |= 4
if LocalID is not None:
writeMask |= 8
if TimerClockConfig is not None or TimerClockDivisor is not None:
writeMask |= 16
if CompatibilityOptions is not None:
writeMask |= 32
command = [ 0 ] * 26
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x0A
command[3] = 0x08
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
command[6] = writeMask
#command[7] = WriteMask1
if LocalID is not None:
command[8] = LocalID
if TimerCounterConfig is not None:
command[9] = TimerCounterConfig
if FIOAnalog is not None:
command[10] = FIOAnalog
if FIODirection is not None:
command[11] = FIODirection
if FIOState is not None:
command[12] = FIOState
if EIOAnalog is not None:
command[13] = EIOAnalog
if EIODirection is not None:
command[14] = EIODirection
if EIOState is not None:
command[15] = EIOState
if CIODirection is not None:
command[16] = CIODirection
if CIOState is not None:
command[17] = CIOState
if DAC1Enable is not None:
command[18] = DAC1Enable
if DAC0 is not None:
command[19] = DAC0
if DAC1 is not None:
command[20] = DAC1
if TimerClockConfig is not None:
command[21] = TimerClockConfig
if TimerClockDivisor is not None:
command[22] = TimerClockDivisor
if CompatibilityOptions is not None:
command[23] = CompatibilityOptions
result = self._writeRead(command, 38, [0xF8, 0x10, 0x08])
# Error-free, time to parse the response
self.firmwareVersion = "%d.%02d" % (result[10], result[9])
self.bootloaderVersion = "%d.%02d" % (result[12], result[11])
self.hardwareVersion = "%d.%02d" % (result[14], result[13])
self.serialNumber = unpack("<I", pack(">BBBB", *result[15:19]))[0]
self.productId = unpack("<H", pack(">BB", *result[19:21]))[0]
self.localId = result[21]
self.timerCounterMask = result[22]
self.fioAnalog = result[23]
self.fioDirection = result[24]
self.fioState = result[25]
self.eioAnalog = result[26]
self.eioDirection = result[27]
self.eioState = result[28]
self.cioDirection = result[29]
self.cioState = result[30]
self.dac1Enable = result[31]
self.dac0 = result[32]
self.dac1 = result[33]
self.timerClockConfig = result[34]
self.timerClockDivisor = result[35]
if result[35] == 0:
self.timerClockDivisor = 256
self.compatibilityOptions = result[36]
self.versionInfo = result[37]
self.deviceName = 'U3'
self.isHV = False
if self.versionInfo == 1:
self.deviceName += 'B'
elif self.versionInfo == 2:
self.deviceName += '-LV'
elif self.versionInfo == 18:
self.deviceName += '-HV'
self.isHV = True
return {'FirmwareVersion': self.firmwareVersion, 'BootloaderVersion': self.bootloaderVersion, 'HardwareVersion': self.hardwareVersion, 'SerialNumber': self.serialNumber, 'ProductID': self.productId, 'LocalID': self.localId, 'TimerCounterMask': self.timerCounterMask, 'FIOAnalog': self.fioAnalog, 'FIODirection': self.fioDirection, 'FIOState': self.fioState, 'EIOAnalog': self.eioAnalog, 'EIODirection': self.eioDirection, 'EIOState': self.eioState, 'CIODirection': self.cioDirection, 'CIOState': self.cioState, 'DAC1Enable': self.dac1Enable, 'DAC0': self.dac0, 'DAC1': self.dac1, 'TimerClockConfig': self.timerClockConfig, 'TimerClockDivisor': self.timerClockDivisor, 'CompatibilityOptions': self.compatibilityOptions, 'VersionInfo': self.versionInfo, 'DeviceName': self.deviceName}
configU3.section = 2
def configIO(self, TimerCounterPinOffset = None, EnableCounter1 = None, EnableCounter0 = None, NumberOfTimersEnabled = None, FIOAnalog = None, EIOAnalog = None, EnableUART = None):
"""
Name: U3.configIO(TimerCounterPinOffset = None, EnableCounter1 = None,
EnableCounter0 = None, NumberOfTimersEnabled = None,
FIOAnalog = None, EIOAnalog = None,
EnableUART = None)
Args: See section 5.2.3 of the user's guide.
Desc: The configIO command.
Examples:
Simplest:
>>> import u3
>>> d = u3.U3()
>>> print(d.configIO())
{
'NumberOfTimersEnabled': 0,
'TimerCounterPinOffset': 4,
'DAC1Enable': 0,
'FIOAnalog': 239,
'EIOAnalog': 0,
'TimerCounterConfig': 64,
'EnableCounter1': False,
'EnableCounter0': False
}
Set all FIOs and EIOs to digital (until power cycle):
>>> import u3
>>> d = u3.U3()
>>> print(d.configIO(FIOAnalog = 0, EIOAnalog = 0))
{
'NumberOfTimersEnabled': 0,
'TimerCounterPinOffset': 4,
'DAC1Enable': 0,
'FIOAnalog': 0,
'EIOAnalog': 0,
'TimerCounterConfig': 64,
'EnableCounter1': False,
'EnableCounter0': False
}
"""
writeMask = 0
if EIOAnalog is not None:
writeMask |= 1
writeMask |= 8
if FIOAnalog is not None:
writeMask |= 1
writeMask |= 4
if EnableUART is not None:
writeMask |= 1
writeMask |= (1 << 5)
if TimerCounterPinOffset is not None or EnableCounter1 is not None or EnableCounter0 is not None or NumberOfTimersEnabled is not None :
writeMask |= 1
command = [ 0 ] * 12
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x03
command[3] = 0x0B
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
command[6] = writeMask
#command[7] = Reserved
command[8] = 0
if EnableUART is not None and EnableUART:
command[9] = 1 << 2
if TimerCounterPinOffset is None:
command[8] |= ( 4 & 15 ) << 4
else:
command[8] |= ( TimerCounterPinOffset & 15 ) << 4
if EnableCounter1 is not None and EnableCounter1:
command[8] |= 1 << 3
if EnableCounter0 is not None and EnableCounter0:
command[8] |= 1 << 2
if NumberOfTimersEnabled is not None:
command[8] |= ( NumberOfTimersEnabled & 3 )
if FIOAnalog is not None:
command[10] = FIOAnalog
if EIOAnalog is not None:
command[11] = EIOAnalog
result = self._writeRead(command, 12, [0xF8, 0x03, 0x0B])
self.timerCounterConfig = result[8]
self.numberTimersEnabled = self.timerCounterConfig & 3
self.counter0Enabled = bool( (self.timerCounterConfig >> 2) & 1 )
self.counter1Enabled = bool( (self.timerCounterConfig >> 3) & 1 )
self.timerCounterPinOffset = ( self.timerCounterConfig >> 4 )
self.dac1Enable = result[9]
self.fioAnalog = result[10]
self.eioAnalog = result[11]
return { 'TimerCounterConfig' : self.timerCounterConfig, 'DAC1Enable' : self.dac1Enable, 'FIOAnalog' : self.fioAnalog, 'EIOAnalog' : self.eioAnalog, 'NumberOfTimersEnabled' : self.numberTimersEnabled, 'EnableCounter0' : self.counter0Enabled, 'EnableCounter1' : self.counter1Enabled, 'TimerCounterPinOffset' : self.timerCounterPinOffset }
configIO.section = 2
def configTimerClock(self, TimerClockBase = None, TimerClockDivisor = None):
"""
Name: U3.configTimerClock(TimerClockBase = None, TimerClockDivisor = None)
Args: TimeClockBase, the base for the timer clock.
TimerClockDivisor, the divisor for the clock.
Desc: Writes and reads the time clock configuration. See section 5.2.4
of the user's guide.
Note: TimerClockBase and TimerClockDivisor must be set at the same time.
"""
command = [ 0 ] * 10
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x02
command[3] = 0x0A
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
#command[6] = Reserved
#command[7] = Reserved
if TimerClockBase is not None:
command[8] = ( 1 << 7 ) + ( TimerClockBase & 7 )
if TimerClockDivisor is not None:
command[9] = TimerClockDivisor
elif TimerClockDivisor is not None:
raise LabJackException("You can't set just the divisor, must set both.")
result = self._writeRead(command, 10, [0xf8, 0x02, 0x0A])
self.timerClockBase = ( result[8] & 7 )
self.timerClockDivisor = result[9]
return { 'TimerClockBase' : self.timerClockBase, 'TimerClockDivisor' : self.timerClockDivisor }
configTimerClock.section = 2
def toggleLED(self):
"""
Name: U3.toggleLED()
Args: None
Desc: Toggles the state LED on and off.
Example:
>>> import u3
>>> d = u3.U3()
>>> d.toggleLED()
"""
self.getFeedback( LED( not self.ledState ) )
self.ledState = not self.ledState
toggleLED.section = 3
def setFIOState(self, fioNum, state = 1):
"""
Name: U3.setFIOState(fioNum, state = 1)
Args: fioNum, which FIO to change
state, 1 = High, 0 = Low
Desc: A convenience function to set the state of an FIO. Will also
set the direction to output. Note that this function can set
all digital I/O lines (FIO0 - CIO3), and is equivalent to using
the setDOState method.
Example:
>>> import u3
>>> d = u3.U3()
>>> d.setFIOState(4, state = 1)
"""
self.getFeedback(BitDirWrite(fioNum, 1), BitStateWrite(fioNum, state))
setFIOState.section = 3
def getFIOState(self, fioNum):
"""
Name: U3.getFIOState(fioNum)
Args: fioNum, which FIO to read
Desc: A convenience function to read the state of an FIO. Note that
this function can read all digital I/O lines (FIO0 - CIO3), and
is equivalent to using the getDIOState method.
Example:
>>> import u3
>>> d = u3.U3()
>>> print(d.getFIOState(4))
1
"""
return self.getFeedback(BitStateRead(fioNum))[0]
getFIOState.section = 3
def setDOState(self, ioNum, state = 1):
"""
Name: U3.setDOState(ioNum, state = 1)
Args: ioNum, which digital I/O to change
0 - 7 = FIO0 - FIO7
8 - 15 = EIO0 - EIO7
16 - 19 = CIO0 - CIO3
state, 1 = High, 0 = Low
Desc: A convenience function to set the state of a digital I/O. Will
also set the direction to output.
Example:
>>> import u3
>>> d = u3.U3()
>>> d.setDOState(4, state = 1)
"""
self.getFeedback(BitDirWrite(ioNum, 1), BitStateWrite(ioNum, state))
setDOState.section = 3
def getDIState(self, ioNum):
"""
Name: U3.getDIState(ioNum)
Args: ioNum, which digital I/O to read
0 - 7 = FIO0 - FIO7
8 - 15 = EIO0 - EIO7
16 - 19 = CIO0 - CIO3
Desc: A convenience function to read the state of a digital I/O. Will
also set the direction to input.
Example:
>>> import u3
>>> d = u3.U3()
>>> print(d.getDIState(4))
1
"""
return self.getFeedback(BitDirWrite(ioNum, 0), BitStateRead(ioNum))[1]
getDIState.section = 3
def getDIOState(self, ioNum):
"""
Name: U3.getDIOState(ioNum)
Args: ioNum, which digital I/O to read
0 - 7 = FIO0 - FIO7
8 - 15 = EIO0 - EIO7
16 - 19 = CIO0 - CIO3
Desc: A convenience function to read the state of a digital I/O. Will
not change the direction.
Example:
>>> import u3
>>> d = u3.U3()
>>> print(d.getDIOState(4))
1
"""
return self.getFeedback(BitStateRead(ioNum))[0]
getDIOState.section = 3
def getTemperature(self):
"""
Name: U3.getTemperature()
Args: None
Desc: Reads the internal temperature sensor on the U3. Returns the
temperature in Kelvin.
"""
# Get the calibration data first, otherwise the conversion is way off (10 degC on my U3)
if self.calData is None:
self.getCalibrationData()
bits, = self.getFeedback( AIN(30, 31) )
return self.binaryToCalibratedAnalogTemperature(bits)
def getAIN(self, posChannel, negChannel = 31, longSettle=False, quickSample=False):
"""
Name: U3.getAIN(posChannel, negChannel = 31, longSettle=False,
quickSample=False)
Args: posChannel, the positive channel to read from.
negChannel, the negitive channel to read from.
longSettle, set to True for longSettle
quickSample, set to True for quickSample
Desc: A convenience function to read an AIN.
Example:
>>> import u3
>>> d = u3.U3()
>>> print(d.getAIN(0))
0.0501680038869
"""
isSpecial = False
if negChannel == 32:
isSpecial = True
negChannel = 30
bits = self.getFeedback(AIN(posChannel, negChannel, longSettle, quickSample))[0]
singleEnded = True
if negChannel != 31:
singleEnded = False
lvChannel = True
try:
if self.isHV and posChannel < 4:
lvChannel = False
except AttributeError:
pass
if isSpecial:
negChannel = 32
return self.binaryToCalibratedAnalogVoltage(bits, isLowVoltage = lvChannel, isSingleEnded = singleEnded, isSpecialSetting = isSpecial, channelNumber = posChannel)
getAIN.section = 3
def configAnalog(self, *args):
"""
Convenience method to configIO() that adds the given input numbers
in the range FIO0-EIO7 (0-15) to the analog team. That is, it adds
the given bit positions to those already set in the FIOAnalog
and EIOAnalog bitfields.
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.configIO()
Sent: [0x47, 0xf8, 0x3, 0xb, 0x40, 0x0, 0x0, 0x0, 0x40, 0x0, 0x0, 0x0]
Result: [0x56, 0xf8, 0x3, 0xb, 0x4f, 0x0, 0x0, 0x0, 0x40, 0x0, 0xf, 0x0]
{'NumberOfTimersEnabled': 0, 'TimerCounterPinOffset': 4, 'DAC1Enable': 0, 'FIOAnalog': 15, 'EIOAnalog': 0, 'TimerCounterConfig': 64, 'EnableCounter1': False, 'EnableCounter0': False}
>>> d.configAnalog(u3.FIO4, u3.FIO5)
Sent: [0x47, 0xf8, 0x3, 0xb, 0x40, 0x0, 0x0, 0x0, 0x40, 0x0, 0x0, 0x0]
Result: [0x56, 0xf8, 0x3, 0xb, 0x4f, 0x0, 0x0, 0x0, 0x40, 0x0, 0xf, 0x0]
Sent: [0x93, 0xf8, 0x3, 0xb, 0x8c, 0x0, 0xd, 0x0, 0x40, 0x0, 0x3f, 0x0]
Result: [0x86, 0xf8, 0x3, 0xb, 0x7f, 0x0, 0x0, 0x0, 0x40, 0x0, 0x3f, 0x0]
{'NumberOfTimersEnabled': 0, 'TimerCounterPinOffset': 4, 'DAC1Enable': 0, 'FIOAnalog': 63, 'EIOAnalog': 0, 'TimerCounterConfig': 64, 'EnableCounter1': False, 'EnableCounter0': False}
"""
configIODict = self.configIO()
# Without args, return the same as configIO()
if len(args) == 0:
return configIODict
FIOAnalog, EIOAnalog = configIODict['FIOAnalog'], configIODict['EIOAnalog']
#
for i in args:
if i > EIO7:
pass # Invalid. Must be in the range FIO0-EIO7.
elif i < EIO0:
FIOAnalog |= 2**i
else:
EIOAnalog |= 2**(i-EIO0) # Start the EIO counting at 0, not 8
return self.configIO(FIOAnalog = FIOAnalog, EIOAnalog = EIOAnalog)
def configDigital(self, *args):
"""
The converse of configAnalog(). The convenience method to configIO,
adds the given input numbers in the range FIO0-EIO7 (0-15) to the
digital team. That is, it removes the given bit positions from those
already set in the FIOAnalog and EIOAnalog bitfields.
>>> import u3
>>> d = u3.U3()
>>> d.debug = True
>>> d.configIO()
Sent: [0x47, 0xf8, 0x3, 0xb, 0x40, 0x0, 0x0, 0x0, 0x40, 0x0, 0x0, 0x0]
Result: [0x56, 0xf8, 0x3, 0xb, 0x4f, 0x0, 0x0, 0x0, 0x40, 0x0, 0xf, 0x0]
{'NumberOfTimersEnabled': 0, 'TimerCounterPinOffset': 4, 'DAC1Enable': 0, 'FIOAnalog': 15, 'EIOAnalog': 0, 'TimerCounterConfig': 64, 'EnableCounter1': False, 'EnableCounter0': False}
>>> d.configAnalog(u3.FIO4, u3.FIO5, u3.EIO0)
Sent: [0x47, 0xf8, 0x3, 0xb, 0x40, 0x0, 0x0, 0x0, 0x40, 0x0, 0x0, 0x0]
Result: [0x56, 0xf8, 0x3, 0xb, 0x4f, 0x0, 0x0, 0x0, 0x40, 0x0, 0xf, 0x0]
Sent: [0x94, 0xf8, 0x3, 0xb, 0x8d, 0x0, 0xd, 0x0, 0x40, 0x0, 0x3f, 0x1]
Result: [0x87, 0xf8, 0x3, 0xb, 0x80, 0x0, 0x0, 0x0, 0x40, 0x0, 0x3f, 0x1]
{'NumberOfTimersEnabled': 0, 'TimerCounterPinOffset': 4, 'DAC1Enable': 0, 'FIOAnalog': 63, 'EIOAnalog': 1, 'TimerCounterConfig': 64, 'EnableCounter1': False, 'EnableCounter0': False}
>>> d.configDigital(u3.FIO4, u3.FIO5, u3.EIO0)
Sent: [0x47, 0xf8, 0x3, 0xb, 0x40, 0x0, 0x0, 0x0, 0x40, 0x0, 0x0, 0x0]
Result: [0x87, 0xf8, 0x3, 0xb, 0x80, 0x0, 0x0, 0x0, 0x40, 0x0, 0x3f, 0x1]
Sent: [0x63, 0xf8, 0x3, 0xb, 0x5c, 0x0, 0xd, 0x0, 0x40, 0x0, 0xf, 0x0]
Result: [0x56, 0xf8, 0x3, 0xb, 0x4f, 0x0, 0x0, 0x0, 0x40, 0x0, 0xf, 0x0]
{'NumberOfTimersEnabled': 0, 'TimerCounterPinOffset': 4, 'DAC1Enable': 0, 'FIOAnalog': 15, 'EIOAnalog': 0, 'TimerCounterConfig': 64, 'EnableCounter1': False, 'EnableCounter0': False}
"""
configIODict = self.configIO()
# Without args, return the same as configIO()
if len(args) == 0:
return configIODict
FIOAnalog, EIOAnalog = configIODict['FIOAnalog'], configIODict['EIOAnalog']
#
for i in args:
if i > EIO7:
pass # Invalid. Must be in the range FIO0-EIO7.
elif i < EIO0:
if FIOAnalog & 2**i: # If it is set
FIOAnalog ^= 2**i # Remove it
else:
if EIOAnalog & 2**(i-EIO0): # Start the EIO counting at 0, not 8
EIOAnalog ^= 2**(i-EIO0)
return self.configIO(FIOAnalog = FIOAnalog, EIOAnalog = EIOAnalog)
def _buildBuffer(self, sendBuffer, readLen, commandlist):
"""
Builds up the buffer to be written for getFeedback
"""
for cmd in commandlist:
if isinstance(cmd, FeedbackCommand):
sendBuffer += cmd.cmdBytes
readLen += cmd.readLen
elif isinstance(cmd, list):
sendBuffer, readLen = self._buildBuffer(sendBuffer, readLen, cmd)
return (sendBuffer, readLen)
_buildBuffer.section = 4
def _buildFeedbackResults(self, rcvBuffer, commandlist, results, i):
"""
Builds the result list from the results of getFeedback
"""
for cmd in commandlist:
if isinstance(cmd, FeedbackCommand):
results.append(cmd.handle(rcvBuffer[i:i+cmd.readLen]))
i += cmd.readLen
elif isinstance(cmd, list):
self._buildFeedbackResults(rcvBuffer, cmd, results, i)
return results
_buildFeedbackResults.section = 4
def getFeedback(self, *commandlist):
"""
Name: U3.getFeedback(commandlist)
Args: the FeedbackCommands to run
Desc: Forms the commandlist into a packet, sends it to the U3, and reads the response.
Examples:
>>> myU3 = u3.U3()
>>> ledCommand = u3.LED(False)
>>> ain0Command = u3.AIN(0, 31, True)
>>> myU3.getFeedback(ledCommand, ain0Command)
[None, 9376]
OR if you like the list version better:
>>> myU3 = U3()
>>> ledCommand = u3.LED(False)
>>> ain0Command = u3.AIN(30, 31, True)
>>> commandList = [ ledCommand, ain0Command ]
>>> myU3.getFeedback(commandList)
[None, 9376]
"""
sendBuffer = [0] * 7
sendBuffer[1] = 0xF8
readLen = 9
sendBuffer, readLen = self._buildBuffer(sendBuffer, readLen, commandlist)
if len(sendBuffer) % 2:
sendBuffer += [0]
sendBuffer[2] = len(sendBuffer) // 2 - 3
if readLen % 2:
readLen += 1
if len(sendBuffer) > MAX_USB_PACKET_LENGTH:
raise LabJackException("ERROR: The feedback command you are attempting to send is bigger than 64 bytes ( %s bytes ). Break your commands up into separate calls to getFeedback()." % len(sendBuffer))
if readLen > MAX_USB_PACKET_LENGTH:
raise LabJackException("ERROR: The feedback command you are attempting to send would yield a response that is greater than 64 bytes ( %s bytes ). Break your commands up into separate calls to getFeedback()." % readLen)
rcvBuffer = self._writeRead(sendBuffer, readLen, [], checkBytes = False, stream = False, checksum = True)
# Check the response for errors
try:
self._checkCommandBytes(rcvBuffer, [0xF8])
if rcvBuffer[3] != 0x00:
raise LabJackException("Got incorrect command bytes")
except LowlevelErrorException:
if isinstance(commandlist[0], list):
culprit = commandlist[0][ (rcvBuffer[7] -1) ]
else:
culprit = commandlist[ (rcvBuffer[7] -1) ]
raise LowlevelErrorException("\nThis Command\n %s\nreturned an error:\n %s" % (culprit , lowlevelErrorToString(rcvBuffer[6])))
results = []
i = 9
return self._buildFeedbackResults(rcvBuffer, commandlist, results, i)
getFeedback.section = 2
def readMem(self, blockNum, readCal=False):
"""
Name: U3.readMem(blockNum, readCal=False)
Args: blockNum, which block to read from
readCal, set to True to read from calibration instead.
Desc: Reads 1 block (32 bytes) from the non-volatile user or
calibration memory. Please read section 5.2.6 of the user's guide
before you do something you may regret.
NOTE: Do not call this function while streaming.
"""
command = [ 0 ] * 8
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x01
command[3] = 0x2A
if readCal:
command[3] = 0x2D
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
command[6] = 0x00
command[7] = blockNum
result = self._writeRead(command, 40, [0xF8, 0x11, command[3]])
return result[8:]
readMem.section = 2
def readCal(self, blockNum):
"""
Name: U3.readCal(blockNum)
Args: blockNum, which block to read
Desc: See the description of readMem and section 5.2.6 of the user's
guide.
Note: Do not call this function while streaming.
"""
return self.readMem(blockNum, readCal = True)
readCal.section = 2
def writeMem(self, blockNum, data, writeCal=False):
"""
Name: U3.writeMem(blockNum, data, writeCal=False)
Args: blockNum, which block to write
data, a list of bytes to write.
writeCal, set to True to write to calibration instead
Desc: Writes 1 block (32 bytes) from the non-volatile user or
calibration memory. Please read section 5.2.7 of the user's guide
before you do something you may regret. Memory must be erased
before writing.
Note: Do not call this function while streaming.
"""
if not isinstance(data, list):
raise LabJackException("Data must be a list of bytes")
command = [ 0 ] * 40
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x11
command[3] = 0x28
if writeCal:
command[3] = 0x2B
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
command[6] = 0x00
command[7] = blockNum
command[8:] = data
self._writeRead(command, 8, [0xF8, 0x01, command[3]])
writeMem.section = 2
def writeCal(self, blockNum, data):
"""
Name: U3.writeCal(blockNum, data)
Args: blockNum, which block to write
data, a list of bytes
Desc: See the description of writeMem and section 5.2.7 of the user's
guide.
Note: Do not call this function while streaming.
"""
return self.writeMem(blockNum, data, writeCal = True)
writeCal.section = 2
def eraseMem(self, eraseCal=False):
"""
Name: U3.eraseMem(eraseCal=False)
Args: eraseCal, set to True to erase the calibration memory instead
Desc: The U3 uses flash memory that must be erased before writing.
Please read section 5.2.8 of the user's guide before you do
something you may regret.
Note: Do not call this function while streaming.
"""
if not isinstance(eraseCal, bool):
raise LabJackException("eraseCal must be a Boolean value (True or False).")
if eraseCal:
command = [ 0 ] * 8
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x01
command[3] = 0x2C
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
command[6] = 0x4C
command[7] = 0x6C
else:
command = [ 0 ] * 6
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x00
command[3] = 0x29
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
self._writeRead(command, 8, [0xF8, 0x01, command[3]])
eraseMem.section = 2
def eraseCal(self):
"""
Name: U3.eraseCal()
Args: None
Desc: See the description of writeMem and section 5.2.8 of the user's
guide.
Note: Do not call this function while streaming.
"""
return self.eraseMem(eraseCal = True)
eraseCal.section = 2
def reset(self, hardReset = False):
"""
Name: U3.reset(hardReset = False)
Args: hardReset, set to True for a hard reset.
Desc: Causes a soft or hard reset. A soft reset consists of
re-initializing most variables without re-enumeration. A hard
reset is a reboot of the processor and does cause re-enumeration.
See section 5.2.9 of the User's guide.
"""
command = [ 0 ] * 4
#command[0] = Checksum8
command[1] = 0x99
command[2] = 1
if hardReset:
command[2] = 2
command[3] = 0x00
command = setChecksum8(command, 4)
self._writeRead(command, 4, [], False, False, False)
reset.section = 2
def streamConfig(self, NumChannels = 1, SamplesPerPacket = 25, InternalStreamClockFrequency = 0, DivideClockBy256 = False, Resolution = 3, ScanInterval = 1, PChannels = [30], NChannels = [31], ScanFrequency = None, SampleFrequency = None):
"""
Name: U3.streamConfig(NumChannels = 1, SamplesPerPacket = 25,
InternalStreamClockFrequency = 0, DivideClockBy256 = False,
Resolution = 3, ScanInterval = 1,
PChannels = [30], NChannels = [31],
ScanFrequency = None, SampleFrequency = None)
Args: NumChannels, the number of channels to stream
Resolution, the resolution of the samples (0 - 3)
PChannels, a list of channel numbers to stream
NChannels, a list of channel options bytes
Set Either:
ScanFrequency, the frequency in Hz to scan the channel list (PChannels).
sample rate (Hz) = ScanFrequency * NumChannels
-- OR --
SamplesPerPacket, how many samples make one packet
InternalStreamClockFrequency, 0 = 4 MHz, 1 = 48 MHz
DivideClockBy256, True = divide the clock by 256
ScanInterval, clock/ScanInterval = frequency.