forked from labjack/LabJackPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathu12.py
More file actions
3021 lines (2346 loc) · 108 KB
/
Copy pathu12.py
File metadata and controls
3021 lines (2346 loc) · 108 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: u12.py
Desc: Defines the U12 class, which makes working with a U12 much easier. The
functions of the U12 class are divided into two categories: UW and
low-level.
Most of the UW functions are exposed as functions of the U12 class. With
the exception of the "e" functions, UW functions are Windows only. The "e"
functions will work with both the UW and the Exodriver. Therefore, people
wishing to write cross-platform code should restrict themselves to using
only the "e" functions. The UW functions are described in Section 4 of the
U12 User's Guide:
http://labjack.com/support/u12/users-guide/4
All low-level functions of the U12 class begin with the word
raw. For example, the low-level function Counter can be called with
U12.rawCounter(). Currently, low-level functions are limited to the
Exodriver (Linux and Mac OS X). You can find descriptions of the low-level
functions in Section 5 of the U12 User's Guide:
http://labjack.com/support/u12/users-guide/5
"""
import atexit
import ctypes
import math
import sys
import time
from struct import pack, unpack
_os_name = "" #Set to "nt" or "posix" in _loadLibrary
class U12Exception(Exception):
"""Custom Exception meant for dealing specifically with U12 Exceptions.
Error codes are either going to be a LabJackUD error code or a -1. The -1 implies
a python wrapper specific error.
def __init__(self, ec = 0, errorString = ''):
self.errorCode = ec
self.errorString = errorString
if not self.errorString:
#try:
self.errorString = getErrorString(ec)
#except:
# self.errorString = str(self.errorCode)
def __str__(self):
return self.errorString
"""
pass
class BitField(object):
"""
Provides a method for working with bit fields.
>>> bf = BitField()
>>> print(bf)
[ bit7 = 0, bit6 = 0, bit5 = 0, bit4 = 0, bit3 = 0, bit2 = 0, bit1 = 0, bit0 = 0 ]
You can use attribute accessing for easy bit flipping:
>>> bf.bit4 = 1
>>> bf.bit7 = 1
>>> print(bf)
[ bit7 = 1, bit6 = 0, bit5 = 0, bit4 = 1, bit3 = 0, bit2 = 0, bit1 = 0, bit0 = 0 ]
You can also use list-style accessing. Counting starts on the left:
>>> print(bf[0]) # List index 0 is bit7
1
>>> print(bf[3]) # List index 3 is bit4
1
List-style slicing:
>>> print(bf[3:])
[1, 0, 0, 0, 0]
List-style setting bits works as you would expect:
>>> bf[1] = 1
>>> print(bf)
[ bit7 = 1, bit6 = 1, bit5 = 0, bit4 = 1, bit3 = 0, bit2 = 0, bit1 = 0, bit0 = 0 ]
It provides methods for going to and from bytes:
>>> bf = BitField(123)
>>> print(bf)
[ bit7 = 0, bit6 = 1, bit5 = 1, bit4 = 1, bit3 = 1, bit2 = 0, bit1 = 1, bit0 = 1 ]
>>> bf = BitField()
>>> bf.fromByte(123) # Modifies bf in place
>>> print(bf)
[ bit7 = 0, bit6 = 1, bit5 = 1, bit4 = 1, bit3 = 1, bit2 = 0, bit1 = 1, bit0 = 1 ]
>>> bf.bit4 = 0
>>> print(bf.asByte())
107
You can iterate of the raw bits ( 1 and 0 Vs. '1' and '0') easily:
>>> for i in bf:
... print(i)
0
1
1
0
1
0
1
1
You can also iterate over the labels and their data values using items():
>>> for label, data in bf.items():
... print("%s %s" % (label, data))
bit7 0
bit6 1
bit5 1
bit4 0
bit3 1
bit2 0
bit1 1
bit0 1
As an added bonus, it can also be cast as an int or hex:
>>> int(bf)
107
>>> hex(bf)
'0x6b'
See the description of the __init__ method for setting the label parameters. """
def __init__(self, rawByte = None, labelPrefix = "bit", labelList = None, zeroLabel = "0", oneLabel = "1"):
"""
Name: BitField.__init__(rawByte = None, labelPrefix = "bit",
labelList = None, zeroLabel = "0",
oneLabel = "1")
Args: rawByte, a value to set the bit field values to.
labelPrefix, what should go before the labels in labelList
labelList, a list of labels to apply to each bit. If None, it
gets set to range(7,-1,-1).
zeroLabel, bits with a value of 0 will have this label
oneLabel, bits with a value of 1 will have this label
Desc: Creates a new bitfield and sets up the labels.
With out any arguments, you get a bit field that looks like this:
>>> bf = BitField()
>>> print(bf)
[ bit7 = 0, bit6 = 0, bit5 = 0, bit4 = 0, bit3 = 0, bit2 = 0, bit1 = 0,
bit0 = 0 ]
To make the labels, it iterates over all the labelList and adds the
labelPrefix to them. If you have less than 8 labels, then your bit field
will only work up to that many bits.
To make a BitField with labels for FIO0-7 you can do the following:
>>> bf = BitField(labelPrefix = "FIO")
>>> print(bf)
[ FIO7 = 0, FIO6 = 0, FIO5 = 0, FIO4 = 0, FIO3 = 0, FIO2 = 0, FIO1 = 0,
FIO0 = 0 ]
The labels don't have to be numbers, for example:
>>> names = [ "Goodreau", "Jerri", "Selena", "Allan", "Tania",
"Kathrine", "Jessie", "Zelma" ]
>>> bf = BitField( labelPrefix = "", labelList = names)
>>> print(bf)
[ Goodreau = 0, Jerri = 0, Selena = 0, Allan = 0, Tania = 0,
Kathrine = 0, Jessie = 0, Zelma = 0 ]
You can change the display value of zero and one to be whatever you
want. For example, if you have a BitField that represents FIO0-7
directions:
>>> dirs = BitField(rawByte = 5, labelPrefix = "FIO",
zeroLabel = "Output", oneLabel = "Input")
>>> print(dirs)
[ FIO7 = Output, FIO6 = Output, FIO5 = Output, FIO4 = Output,
FIO3 = Output, FIO2 = Input, FIO1 = Output, FIO0 = Input ]
Note, that when you access the value, you will get 1 or 0, not "Input"
or "Output. For example:
>>> print(dirs.FIO3)
0
"""
# Do labels first, so that self.something = something works.
self.__dict__['labels'] = []
self.labelPrefix = labelPrefix
if labelList is None:
self.labelList = list(range(8))
else:
self.labelList = list(reversed(labelList))
self.zeroLabel = zeroLabel
self.oneLabel = oneLabel
self.rawValue = 0
self.rawBits = [ 0 ] * 8
self.data = [ self.zeroLabel ] * 8
items = min(8, len(self.labelList))
for i in reversed(range(items)):
self.labels.append("%s%s" % (self.labelPrefix, self.labelList[i]))
if rawByte is not None:
self.fromByte(rawByte)
def fromByte(self, raw):
"""
Name: BitField.fromByte(raw)
Args: raw, the raw byte to make the BitField.
Desc: Takes a byte, and modifies self to match.
>>> bf = BitField()
>>> bf.fromByte(123) # Modifies bf in place
>>> print(bf)
[ bit7 = 0, bit6 = 1, bit5 = 1, bit4 = 1, bit3 = 1, bit2 = 0, bit1 = 1,
bit0 = 1 ]
"""
self.rawValue = raw
self.rawBits = []
self.data = []
items = min(8, len(self.labelList))
for i in reversed(range(items)):
self.rawBits.append( ((raw >> (i)) & 1) )
self.data.append(self.oneLabel if bool(((raw >> (i)) & 1)) else self.zeroLabel)
def asByte(self):
"""
Name: BitField.asByte()
Args: None
Desc: Returns the value of the bitfield as a byte.
>>> bf = BitField()
>>> bf.fromByte(123) # Modifies bf in place
>>> bf.bit4 = 0
>>> print(bf.asByte())
107
"""
byteVal = 0
for i, v in enumerate(reversed(self.rawBits)):
byteVal += ( 1 << i ) * v
return byteVal
def asBin(self):
result = "0b"
for i in self.rawBits:
result += "%s" % i
return result
def __len__(self):
return len(self.data)
def __repr__(self):
result = "["
for i in range(len(self.data)):
result += " %s = %s (%s)," % (self.labels[i], self.data[i], self.rawBits[i])
result = result.rstrip(',')
result += " ]"
return "<BitField object: %s >" % result
def __str__(self):
result = "["
for i in range(len(self.data)):
result += " %s = %s," % (self.labels[i], self.data[i])
result = result.rstrip(',')
result += " ]"
return result
def __getattr__(self, label):
try:
i = self.labels.index(label)
return self.rawBits[i]
except ValueError:
raise AttributeError(label)
def __setattr__(self, label, value):
try:
i = self.labels.index(label)
self.rawBits[i] = int(bool(value))
self.data[i] = self.oneLabel if bool(value) else self.zeroLabel
except ValueError:
self.__dict__[label] = value
def __getitem__(self, key):
return self.rawBits[key]
def __setitem__(self, key, value):
self.rawBits[key] = int(bool(value))
self.data[key] = self.oneLabel if bool(value) else self.zeroLabel
def __iter__(self):
return iter(self.rawBits)
def items(self):
"""
Name: BitField.items()
Args: None
Desc: Returns a list of tuples where the first item is the label and the
second is the string value, like "High" or "Input"
>>> dirs = BitField(rawByte = 5, labelPrefix = "FIO",
zeroLabel = "Output", oneLabel = "Input")
>>> print(dirs)
[ FIO7 = Output, FIO6 = Output, FIO5 = Output, FIO4 = Output,
FIO3 = Output, FIO2 = Input, FIO1 = Output, FIO0 = Input ]
>>> for label, data in dirs.items():
... print("%s %s" % (label, data))
...
FIO7 Output
FIO6 Output
FIO5 Output
FIO4 Output
FIO3 Output
FIO2 Input
FIO1 Output
FIO0 Input
"""
return list(zip(self.labels, self.data))
def __int__(self):
return self.asByte()
def __hex__(self):
return hex(self.asByte())
def __add__(self, other):
"""
A helper to prevent having to test if a variable is a bitfield or int.
"""
return other + self.asByte()
def errcheck(ret, func, args):
if ret == -1:
try:
ec = ctypes.get_errno()
raise U12Exception("Exodriver returned error number %s" % ec)
except AttributeError:
raise U12Exception("Exodriver returned an error, but LabJackPython is unable to read the error code. Upgrade to Python 2.6 for this functionality.")
else:
return ret
def _loadLinuxSo():
l = ctypes.CDLL("liblabjackusb.so", use_errno=True)
l.LJUSB_Stream.errcheck = errcheck
l.LJUSB_Read.errcheck = errcheck
return l
def _loadMacDylib():
try:
l = ctypes.CDLL("liblabjackusb.dylib", use_errno=True)
except:
#Try to load with full path.
l = ctypes.CDLL("/usr/local/lib/liblabjackusb.dylib", use_errno=True)
l.LJUSB_Stream.errcheck = errcheck
l.LJUSB_Read.errcheck = errcheck
return l
def _loadLibrary():
"""_loadLibrary()
Returns a ctypes dll pointer to the library.
"""
global _os_name
_os_name = "nt"
try:
if sys.platform.startswith("win32"):
#Windows detected
return ctypes.WinDLL("ljackuw")
if sys.platform.startswith("cygwin"):
#Cygwin detected. WinDLL not available, but CDLL seems to work.
return ctypes.CDLL("ljackuw")
except Exception:
e = sys.exc_info()[1]
raise U12Exception("Could not load LabJack UW driver.\n\n The error was: %s" % e)
_os_name = "posix"
addStr = "Exodriver"
try:
if sys.platform.startswith("linux"):
#Linux detected
addStr = "Linux SO"
return _loadLinuxSo()
if sys.platform.startswith("darwin"):
#Mac detected
addStr = "Mac Dylib"
return _loadMacDylib()
#Other OS? Just try to load the Exodriver like a Linux SO
addStr = "Other SO"
return _loadLinuxSo()
except OSError:
e = sys.exc_info()[1]
raise U12Exception("Could not load the Exodriver driver.\n\nCheck that the Exodriver is installed, and the permissions are set correctly.\nThe error message was: %s" % e)
except Exception:
e = sys.exc_info()[1]
raise U12Exception("Could not load the %s for some reason other than it not being installed.\n\n The error was: %s" % (addStr, e))
try:
staticLib = _loadLibrary()
except U12Exception:
e = sys.exc_info()[1]
print("%s: %s" % (type(e), e))
staticLib = None
class U12(object):
"""
U12 Class for all U12 specific commands.
u12 = U12()
"""
def __init__(self, id = -1, serialNumber = None, debug = False):
self.id = id
self.serialNumber = serialNumber
self.deviceName = "U12"
self.streaming = False
self.handle = None
self.debug = debug
self._autoCloseSetup = False
if _os_name != "nt":
# Save some variables to save state.
self.pwmAVoltage = 0
self.pwmBVoltage = 0
self.open(id, serialNumber)
def open(self, id = -1, serialNumber = None):
"""
Opens the U12.
The Windows UW driver opens the device every time a function is called.
The Exodriver, however, works like the UD family of devices and returns
a handle. On Windows, this method does nothing. On Mac OS X and Linux,
this method acquires a device handle and saves it to the U12 object.
"""
if _os_name == "nt":
pass
else:
if self.debug:
print("open called")
devType = ctypes.c_ulong(1)
openDev = staticLib.LJUSB_OpenDevice
openDev.restype = ctypes.c_void_p
if serialNumber is not None:
numDevices = staticLib.LJUSB_GetDevCount(devType)
for i in range(numDevices):
handle = openDev(i+1, 0, devType)
if handle != 0 and handle is not None:
self.handle = ctypes.c_void_p(handle)
try:
serial = self.rawReadSerial()
except Exception:
serial = self.rawReadSerial()
if serial == int(serialNumber):
break
else:
self.close()
if self.handle is None:
raise U12Exception("Couldn't find a U12 with a serial number matching %s" % serialNumber)
elif id != -1:
numDevices = staticLib.LJUSB_GetDevCount(devType)
for i in range(numDevices):
handle = openDev(i+1, 0, devType)
if handle != 0 and handle is not None:
self.handle = ctypes.c_void_p(handle)
try:
unitId = self.rawReadLocalId()
except Exception:
unitId = self.rawReadLocalId()
if unitId == int(id):
break
else:
self.close()
if self.handle is None:
raise U12Exception("Couldn't find a U12 with a local ID matching %s" % id)
elif id == -1:
handle = openDev(1, 0, devType)
if handle == 0 or handle is None:
raise Exception("Couldn't open a U12. Check that one is connected and try again.")
else:
self.handle = ctypes.c_void_p(handle)
# U12 ignores first command, so let's write a command.
command = [ 0 ] * 8
command[5] = 0x57 # 0b01010111
try:
self.write(command)
self.read()
except:
pass
self.id = self.rawReadLocalId()
else:
raise Exception("Invalid combination of parameters.")
if not self._autoCloseSetup:
# Only need to register auto-close once per device.
atexit.register(self.close)
self._autoCloseSetup = True
def close(self):
if _os_name == "nt":
pass
else:
staticLib.LJUSB_CloseDevice(self.handle)
self.handle = None
def write(self, writeBuffer):
if _os_name == "nt":
pass
else:
if self.handle is None:
raise U12Exception("The U12's handle is None. Please open a U12 with open()")
if self.debug:
print("Writing: " + hexWithoutQuotes(writeBuffer))
newA = (ctypes.c_byte*len(writeBuffer))(0)
for i in range(len(writeBuffer)):
newA[i] = ctypes.c_byte(writeBuffer[i])
writeBytes = staticLib.LJUSB_Write(self.handle, ctypes.byref(newA), len(writeBuffer))
if writeBytes != len(writeBuffer):
raise U12Exception( "Could only write %s of %s bytes." % (writeBytes, len(writeBuffer) ) )
return writeBuffer
def read(self, numBytes=8, timeout=1000):
if _os_name == "nt":
pass
else:
if self.handle is None:
raise U12Exception("The U12's handle is None. Please open a U12 with open()")
newA = (ctypes.c_byte*numBytes)()
readBytes = staticLib.LJUSB_ReadTO(self.handle, ctypes.byref(newA), numBytes, timeout)
# Return a list of integers in command-response mode
result = [(newA[i] & 0xff) for i in range(readBytes)]
if self.debug:
print("Received: " + hexWithoutQuotes(result))
return result
# Low-level helpers
def rawReadSerial(self):
"""
Name: U12.rawReadSerial()
Args: None
Desc: Reads the serial number from internal memory.
Returns: The U12's serial number as an integer.
Example:
>>> import u12
>>> d = u12.U12()
>>> print(d.rawReadSerial())
10004XXXX
"""
results = self.rawReadRAM()
return unpack(">I", pack("BBBB", results['DataByte3'], results['DataByte2'], results['DataByte1'], results['DataByte0']))[0]
def rawReadLocalId(self):
"""
Name: U12.rawReadLocalId()
Args: None
Desc: Reads the Local ID from internal memory.
Returns: The U12's Local ID as an integer.
Example:
>>> import u12
>>> d = u12.U12()
>>> print(d.rawReadLocalId())
0
"""
results = self.rawReadRAM(0x08)
return results['DataByte0']
# Begin Section 5 Functions
def rawAISample(self, channel0PGAMUX = 8, channel1PGAMUX = 9, channel2PGAMUX = 10, channel3PGAMUX = 11, UpdateIO = False, LEDState = True, IO3toIO0States = 0, EchoValue = 0):
"""
Name: U12.rawAISample(channel0PGAMUX = 8, channel1PGAMUX = 9,
channel2PGAMUX = 10, channel3PGAMUX = 11,
UpdateIO = False, LEDState = True,
IO3toIO0States = 0, EchoValue = 0)
Args: channel0PGAMUX, A byte that contains channel0 information
channel1PGAMUX, A byte that contains channel1 information
channel2PGAMUX, A byte that contains channel2 information
channel3PGAMUX, A byte that contains channel3 information
IO3toIO0States, A byte that represents the states of IO0 to IO3
UpdateIO, If true, set IO0 to IO 3 to match IO3toIO0States
LEDState, Turns the status LED on or off.
EchoValue, Sometimes, you want what you put in.
Desc: Collects readings from 4 analog inputs. It can also toggle the
status LED and update the state of the IOs. See Section 5.1 of
the User's Guide.
By default it will read AI0-3 (single-ended).
Returns: A dictionary with the following keys:
PGAOvervoltage, A bool representing if the U12 detected overvoltage
IO3toIO0States, a BitField representing the state of IO0 to IO3
Channel0-3, the analog voltage for the channel
EchoValue, a repeat of the value passed in.
Example:
>>> import u12
>>> d = u12.U12()
>>> d.rawAISample()
{
'IO3toIO0States':
<BitField object: [ IO3 = Low (0), IO2 = Low (0),
IO1 = Low (0), IO0 = Low (0) ] >,
'Channel0': 1.46484375,
'Channel1': 1.4501953125,
'Channel2': 1.4599609375,
'Channel3': 1.4306640625,
'PGAOvervoltage': False,
'EchoValue': 0
}
"""
command = [ 0 ] * 8
# Bits 6-4: PGA for 1st Channel
# Bits 3-0: MUX command for 1st Channel
command[0] = int(channel0PGAMUX)
tempNum = command[0] & 7 # 7 = 0b111
channel0Number = tempNum if (command[0] & 0xf) > 7 else tempNum+8
channel0Gain = (command[0] >> 4) & 7 # 7 = 0b111
command[1] = int(channel1PGAMUX)
tempNum = command[1] & 7 # 7 = 0b111
channel1Number = tempNum if (command[1] & 0xf) > 7 else tempNum+8
channel1Gain = (command[1] >> 4) & 7 # 7 = 0b111
command[2] = int(channel2PGAMUX)
tempNum = command[2] & 7 # 7 = 0b111
channel2Number = tempNum if (command[2] & 0xf) > 7 else tempNum+8
channel2Gain = (command[2] >> 4) & 7 # 7 = 0b111
command[3] = int(channel3PGAMUX)
tempNum = command[3] & 7 # 7 = 0b111
channel3Number = tempNum if (command[3] & 0xf) > 7 else tempNum+8
channel3Gain = (command[3] >> 4) & 7 # 7 = 0b111
# Bit 1: Update IO
# Bit 0: LED State
bf = BitField()
bf.bit1 = int(UpdateIO)
bf.bit0 = int(LEDState)
command[4] = int(bf)
# Bit 7-4: 1100 (Command/Response)
# Bit 3-0: Bits for IO3 through IO0 States
bf.fromByte(0)
bf.bit7 = 1
bf.bit6 = 1
bf.fromByte( int(bf) | int(IO3toIO0States) )
command[5] = int(bf)
command[7] = EchoValue
self.write(command)
results = self.read()
bf = BitField()
bf.fromByte(results[0])
if bf.bit7 != 1 or bf.bit6 != 0:
raise U12Exception("Expected a AIStream response, got %s instead." % results[0])
returnDict = {}
returnDict['EchoValue'] = results[1]
returnDict['PGAOvervoltage'] = bool(bf.bit4)
returnDict['IO3toIO0States'] = BitField(results[0], "IO", list(range(3, -1, -1)), "Low", "High")
channel0 = (results[2] >> 4) & 0xf
channel1 = (results[2] & 0xf)
channel2 = (results[5] >> 4) & 0xf
channel3 = (results[5] & 0xf)
channel0 = (channel0 << 8) + results[3]
returnDict['Channel0'] = self.bitsToVolts(channel0Number, channel0Gain, channel0)
channel1 = (channel1 << 8) + results[4]
returnDict['Channel1'] = self.bitsToVolts(channel1Number, channel1Gain, channel1)
channel2 = (channel2 << 8) + results[6]
returnDict['Channel2'] = self.bitsToVolts(channel2Number, channel2Gain, channel2)
channel3 = (channel3 << 8) + results[7]
returnDict['Channel3'] = self.bitsToVolts(channel3Number, channel3Gain, channel3)
return returnDict
def rawDIO(self, D15toD8Directions = 0, D7toD0Directions = 0, D15toD8States = 0, D7toD0States = 0, IO3toIO0DirectionsAndStates = 0, UpdateDigital = False):
"""
Name: U12.rawDIO(D15toD8Directions = 0, D7toD0Directions = 0,
D15toD8States = 0, D7toD0States = 0,
IO3toIO0DirectionsAndStates = 0, UpdateDigital = 1)
Args: D15toD8Directions, A byte where 0 = Output, 1 = Input for D15-8
D7toD0Directions, A byte where 0 = Output, 1 = Input for D7-0
D15toD8States, A byte where 0 = Low, 1 = High for D15-8
D7toD0States, A byte where 0 = Low, 1 = High for D7-0
IO3toIO0DirectionsAndStates, Bits 7-4: Direction, 3-0: State
UpdateDigital, True if you want to update the IO/D line. False to
False to just read their values.
Desc: This commands reads the direction and state of all the digital
I/O. See Section 5.2 of the U12 User's Guide.
By default, it just reads the directions and states.
Returns: A dictionary with the following keys:
D15toD8Directions, a BitField representing the directions of D15-D8
D7toD0Directions, a BitField representing the directions of D7-D0.
D15toD8States, a BitField representing the states of D15-D8.
D7toD0States, a BitField representing the states of D7-D0.
IO3toIO0States, a BitField representing the states of IO3-IO0.
D15toD8OutputLatchStates, BitField of output latch states for D15-8
D7toD0OutputLatchStates, BitField of output latch states for D7-0
Example:
>>> import u12
>>> d = u12.U12()
>>> d.rawDIO()
{
'D15toD8Directions':
<BitField object: [ D15 = Input (1), D14 = Input (1),
D13 = Input (1), D12 = Input (1),
D11 = Input (1), D10 = Input (1),
D9 = Input (1), D8 = Input (1) ] >,
'D7toD0Directions':
<BitField object: [ D7 = Input (1), D6 = Input (1), D5 = Input (1),
D4 = Input (1), D3 = Input (1), D2 = Input (1),
D1 = Input (1), D0 = Input (1) ] >,
'D15toD8States':
<BitField object: [ D15 = Low (0), D14 = Low (0), D13 = Low (0),
D12 = Low (0), D11 = Low (0), D10 = Low (0),
D9 = Low (0), D8 = Low (0) ] >,
'D7toD0States':
<BitField object: [ D7 = Low (0), D6 = Low (0), D5 = Low (0),
D4 = Low (0), D3 = Low (0), D2 = Low (0),
D1 = Low (0), D0 = Low (0) ] >,
'IO3toIO0States':
<BitField object: [ IO3 = Low (0), IO2 = Low (0), IO1 = Low (0),
IO0 = Low (0) ] >,
'D15toD8OutputLatchStates':
<BitField object: [ D15 = 0 (0), D14 = 0 (0), D13 = 0 (0),
D12 = 0 (0), D11 = 0 (0), D10 = 0 (0),
D9 = 0 (0), D8 = 0 (0) ] >,
'D7toD0OutputLatchStates':
<BitField object: [ D7 = 0 (0), D6 = 0 (0), D5 = 0 (0), D4 = 0 (0),
D3 = 0 (0), D2 = 0 (0), D1 = 0 (0),
D0 = 0 (0) ] >
}
"""
command = [ 0 ] * 8
# Bits for D15 through D8 Direction
command[0] = int(D15toD8Directions)
# Bits for D7 through D0 Direction ( 0 = Output, 1 = Input)
command[1] = int(D7toD0Directions)
# Bits for D15 through D8 State ( 0 = Low, 1 = High)
command[2] = int(D15toD8States)
# Bits for D7 through D0 State ( 0 = Low, 1 = High)
command[3] = int(D7toD0States)
# Bits 7-4: Bits for IO3 through IO0 Direction
# Bits 3-0: Bits for IO3 through IO0 State
command[4] = int(IO3toIO0DirectionsAndStates)
# 01X10111 (DIO)
command[5] = 0x57 # 0b01010111
# Bit 0: Update Digital
command[6] = int(bool(UpdateDigital))
#XXXXXXXX
# command[7] = XXXXXXXX
self.write(command)
results = self.read()
returnDict = {}
if results[0] != 87:
raise U12Exception("Expected a DIO response, got %s instead." % results[0])
returnDict['D15toD8States'] = BitField(results[1], "D", list(range(15, 7, -1)), "Low", "High")
returnDict['D7toD0States'] = BitField(results[2], "D", list(range(7, -1, -1)), "Low", "High")
returnDict['D15toD8Directions'] = BitField(results[4], "D", list(range(15, 7, -1)), "Output", "Input")
returnDict['D7toD0Directions'] = BitField(results[5], "D", list(range(7, -1, -1)), "Output", "Input")
returnDict['D15toD8OutputLatchStates'] = BitField(results[6], "D", list(range(15, 7, -1)))
returnDict['D7toD0OutputLatchStates'] = BitField(results[7], "D", list(range(7, -1, -1)))
returnDict['IO3toIO0States'] = BitField((results[3] >> 4), "IO", list(range(3, -1, -1)), "Low", "High")
return returnDict
def rawCounter(self, StrobeEnabled = False, ResetCounter = False):
"""
Name: U12.rawCounter(StrobeEnabled = False, ResetCounter = False)
Args: StrobeEnable, set to True to enable strobe.
ResetCounter, set to True to reset the counter AFTER reading.
Desc: This command controls and reads the 32-bit counter. See
Section 5.3 of the User's Guide.
Returns: A dictionary with the following keys:
D15toD8States, a BitField representing the states of D15-D8.
D7toD0States, a BitField representing the states of D7-D0.
IO3toIO0States, a BitField representing the states of IO3-IO0.
Counter, the value of the counter
Example:
>>> import u12
>>> d = u12.U12()
>>> d.rawCounter()
{
'D15toD8States':
<BitField object: [ D15 = Low (0), D14 = Low (0), D13 = Low (0),
D12 = Low (0), D11 = Low (0), D10 = Low (0),
D9 = Low (0), D8 = Low (0) ] >,
'D7toD0States':
<BitField object: [ D7 = Low (0), D6 = Low (0), D5 = Low (0),
D4 = Low (0), D3 = Low (0), D2 = Low (0),
D1 = Low (0), D0 = Low (0) ] >,
'IO3toIO0States':
<BitField object: [ IO3 = Low (0), IO2 = Low (0), IO1 = Low (0),
IO0 = Low (0) ] >,
'Counter': 0
}
"""
command = [ 0 ] * 8
bf = BitField()
bf.bit1 = int(StrobeEnabled)
bf.bit0 = int(ResetCounter)
command[0] = int(bf)
bf.fromByte(0)
bf.bit6 = 1
bf.bit4 = 1
bf.bit1 = 1
command[5] = int(bf)
self.write(command)
results = self.read()
returnDict = {}
if results[0] != command[5]:
raise U12Exception("Expected a Counter response, got %s instead." % results[0])
returnDict['D15toD8States'] = BitField(results[1], "D", list(range(15, 7, -1)), "Low", "High")
returnDict['D7toD0States'] = BitField(results[2], "D", list(range(7, -1, -1)), "Low", "High")
returnDict['IO3toIO0States'] = BitField((results[3] >> 4), "IO", list(range(3, -1, -1)), "Low", "High")
counter = results[7]
counter += results[6] << 8
counter += results[5] << 16
counter += results[4] << 24
returnDict['Counter'] = counter
return returnDict
def rawCounterPWMDIO(self, D15toD8Directions = 0, D7toD0Directions = 0, D15toD8States = 0, D7toD0States = 0, IO3toIO0DirectionsAndStates = 0, ResetCounter = False, UpdateDigital = 0, PWMA = 0, PWMB = 0):
"""
Name: U12.rawCounterPWMDIO( D15toD8Directions = 0, D7toD0Directions = 0,
D15toD8States = 0, D7toD0States = 0,
IO3toIO0DirectionsAndStates = 0,
ResetCounter = False, UpdateDigital = 0,
PWMA = 0, PWMB = 0)
Args: D15toD8Directions, A byte where 0 = Output, 1 = Input for D15-8
D7toD0Directions, A byte where 0 = Output, 1 = Input for D7-0
D15toD8States, A byte where 0 = Low, 1 = High for D15-8
D7toD0States, A byte where 0 = Low, 1 = High for D7-0
IO3toIO0DirectionsAndStates, Bits 7-4: Direction, 3-0: State
ResetCounter, If True, reset the counter after reading.
UpdateDigital, True if you want to update the IO/D line. False to
False to just read their values.
PWMA, Voltage to set AO0 to output.
PWMB, Voltage to set AO1 to output.
Desc: This command controls all 20 digital I/O, and the 2 PWM outputs.
The response provides the state of all I/O and the current count.
See Section 5.4 of the User's Guide.
By default, sets the AOs to 0 and reads the states and counters.
Returns: A dictionary with the following keys:
D15toD8States, a BitField representing the states of D15-D8.
D7toD0States, a BitField representing the states of D7-D0.
IO3toIO0States, a BitField representing the states of IO3-IO0.
Counter, the value of the counter
Example:
>>> import u12
>>> d = u12.U12()
>>> d.rawCounterPWMDIO()
{
'D15toD8States':
<BitField object: [ D15 = Low (0), D14 = Low (0), D13 = Low (0),
D12 = Low (0), D11 = Low (0), D10 = Low (0),
D9 = Low (0), D8 = Low (0) ] >,
'D7toD0States':
<BitField object: [ D7 = Low (0), D6 = Low (0), D5 = Low (0),
D4 = Low (0), D3 = Low (0), D2 = Low (0),
D1 = Low (0), D0 = Low (0) ] >,
'IO3toIO0States':
<BitField object: [ IO3 = Low (0), IO2 = Low (0),
IO1 = Low (0), IO0 = Low (0) ] >,
'Counter': 0
}
"""
command = [ 0 ] * 8
# Bits for D15 through D8 Direction
command[0] = int(D15toD8Directions)
# Bits for D7 through D0 Direction ( 0 = Output, 1 = Input)
command[1] = int(D7toD0Directions)
# Bits for D15 through D8 State ( 0 = Low, 1 = High)
command[2] = int(D15toD8States)
# Bits for D7 through D0 State ( 0 = Low, 1 = High)
command[3] = int(D7toD0States)
# Bits 7-4: Bits for IO3 through IO0 Direction
# Bits 3-0: Bits for IO3 through IO0 State
command[4] = int(IO3toIO0DirectionsAndStates)
bf = BitField()
bf.bit5 = int(ResetCounter)
bf.bit4 = int(UpdateDigital)
binPWMA = int((1023 * (float(PWMA)/5.0)))
binPWMB = int((1023 * (float(PWMB)/5.0)))