-
Notifications
You must be signed in to change notification settings - Fork 1
/
eyesj.py
1491 lines (1365 loc) · 43.8 KB
/
eyesj.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
'''
EYES for Young Engineers and Scientists -Junior (EYES Junior 1.0)
Python library to communicate to the PIC24FV32KA302 uC running 'eyesj.c'
Author : Ajith Kumar B.P, bpajith@gmail.com, ajith@iuac.res.in
License : GNU GPL version 3
Started on 25-Mar-2012
Last edit : 25-Oct-2012, added storing calibration to EEPROM
*
The micro-controller pins used are mapped into 13 I/O channels (numbered 0 to 12)
and act like a kind of logical channels. The Python function calls refer to them
using the corresponding number, ie 0 => A0.
* 0 : A0, Analog Comaparator(A5) output.
* 1 : A1, -5V to +5V range Analog Input
* 2 : A2, -5V to +5V range Analog Input
* 3 : IN1 , Can function as Digital or 0 to 5V Analog Input
* 4 : IN2, Can function as Digital or 0 to 5V Analog Input
* 5 : SEN, Simial to A3 & A4, but has a 5K external pullup resistor (Comp input)
* 6 : SQR1-read, Input wired to SQR1 output
* 7 : SQR2-read, Input wired to SQR2 output
* 8 : SQR1 control, 0 to 5V programmable Squarewave. Setting Freq = 0 means 5V, Freq = -1 means 0V
* 9 : SQR2 control, 0 to 5V programmable Squarewave
* 10: Digital output OD1,
* 11: CCS, Controls the 1mA constant current source.
* A12: Analog Input AN0 / RA0 (dummy entry for RA0), special case
'''
import serial, struct, math, time, commands, sys, os, os.path
import __builtin__ # Need to do this since 'eyes.py' redefines 'open'
import gettext # For localization, inputs from Georges (georges.khaznadar@free.fr)
gettext.bindtextdomain('expeyes')
gettext.textdomain('expeyes')
_ = gettext.gettext
#Path to the calibration file
'''
if sys.platform.startswith('linux'):
calibrationDir=os.path.expanduser('~/.expeyes')
else:
calibrationDir="."
if not os.path.isdir(calibrationDir):
os.makedirs(calibrationDir)
calibrationFile=os.path.abspath(os.path.join(calibrationDir,'eyesj.cal'))
calibrationFileSEN=os.path.abspath(os.path.join(calibrationDir,'eyesj-sen.cal'))
calibrationFileCAP=os.path.abspath(os.path.join(calibrationDir,'eyesj-cap.cal'))
'''
#Commands with One byte argument (41 to 80)
GETVERSION = 1
READCMP = 2 # Status of comparator output
READTEMP = 3 # IC Temperature
GETPORTB = 4
#Commands with One byte argument (41 to 80)
READADC = 41 # Read the ADC channel
GETSTATE = 42 # Digital Input Status
NANODELAY = 43 # from IN2 to SEN, using CTMU, send current range
SETADCREF = 44 # non-zero value selects external +Vref option
READADCSM = 45 # Read the ADC channel, in Sleep Mode
IRSEND1 = 46 # Sends one byte over IR on SQR1
RDEEPROM = 47 # Read nwords starting from addr
# Commands with Two bytes argument (81 to 120)
R2RTIME = 81 # Time from rising edge to rising edge,arguments pin1 & pin2
R2FTIME = 82
F2RTIME = 83
F2FTIME = 84
MULTIR2R = 85 # Time between rising edges, arguments pin & skipcycles
SET2RTIME = 86 # From a Dout transition to the Din transition
SET2FTIME = 87 #
CLR2RTIME = 88 #
CLR2FTIME = 89 #
HTPUL2RTIME = 90 # High True Pulse to HIGH
HTPUL2FTIME = 91 # High True Pulse to LOW
LTPUL2RTIME = 92 #
LTPUL2FTIME = 93 #
SETPULWIDTH = 94 # Width setting for PULSE2* functions
SETSTATE = 95 # SQR1, SQR2, OD & CCS only
SETDAC = 96 # 12 bit DAC setting
SETCURRENT = 97 # ADC channel, CTMU Irange
SETACTION = 98 # capture modifiers, action, target pin
SETTRIGVAL = 99 # Analog trigger level, 2 bytes
SRFECHOTIME = 100 # Trigger to Echo time for SRF0x modules
# Commands with Three bytes argument (121 to 160)
SETSQR1 = 121 # Square wave on OSC2
SETSQR2 = 122 # Square wave on OSC3
WREEPROM = 123 # write 1 word to the address
#Commands with Four bytes argument (161 to 200)
MEASURECV = 163 # ch, irange, duration
SETPWM1 = 164 # PWM on SQR1 output. Send ocxrx and ocx
SETPWM2 = 165 # PWM on SQR1 output.
IRSEND4 = 166 # 4 byte IR
#Commands with Five bytes argument (201 to 240)
CAPTURE = 201 # Ch, 2 byte NS, 2 byte TG
CAPTURE_HR = 202 # Ch, 2 byte NS, 2 byte TG
SETSQRS = 203 # Set both square waves, with specified phase difference. scale, ocr, diff
#Commands with Six bytes argument (241 to 255)
CAPTURE2 = 241 # ch1, ch2, NS, TG (1, 1, 2, 2)bytes
CAPTURE2_HR = 242 # ch1, ch2, NS, TG (1, 1, 2, 2)bytes
CAPTURE3 = 243 # ch1&ch2, ch3, ns , tg
CAPTURE4 = 244 # ch1&ch2, ch3&ch4, ns , tg
# Actions before capturing waveforms
AANATRIG = 0 # Trigger on analog input level, set by SETRIGVAL
AWAITHI = 1
AWAITLO = 2
AWAITRISE = 3
AWAITFALL = 4
ASET = 5
ACLR = 6
APULSEHT = 7
APULSELT = 8
BUFSIZE = 1800 # status + adcinfo + 1800 data
#Serial devices to search for EYES hardware.
# MINRK: add glob-search for serial devices
import glob
linux_list = []
for g in ['/dev/ttyACM*', '/dev/ttyAMA*', '/dev/ttyusb*', '/dev/tty.usb*']:
linux_list.extend(glob.glob(g))
# linux_list = ['/dev/ttyACM0','/dev/ttyACM1','/dev/ttyACM2', '/dev/ttyACM3', '/dev/ttyAMA0']
def open(dev = None):
'''
If EYES hardware in found, returns an instance of 'Eyes', else returns None.
'''
obj = Eyesjun()
if obj.fd != None:
obj.disable_actions() # Disable capture modifiers
obj.load_calibration()
return obj
print _('Could not find EYES Junior hardware')
print _('Check the connections.')
BAUDRATE = 115200 # Serial communication
class Eyesjun:
fd = None # init should fill this
DACMAX = 5.000 # DAC upper limit
DACM = 4095.0/5
tgap = 0.004 # 0.004 ms shift between two channels of capture2
m12 = [5.0/4095] + [10.0/4095]*2 + [5.0/4095]*10
m8 = [5.0/255] + [10.0/255] *2 + [5.0/255] *10
c = [0.0] + [-5.0]*2 + [0.0]*10
sen_pullup = 5100.0
cap_calib = 1.0 # Default values, to be loaded from file.
socket_cap = 30.0 # Set by calibrate.py
msg = ''
def __init__(self, dev = None):
"""
Searches for EYES hardware on USB-to-Serial adapters. Presence of the
device is done by reading the version string. Timeout set to 4 sec
TODO : Supporting more than one EYES on a PC to be done. The question is how to find out
whether a port is already open or not, without doing any transactions to it.
"""
if os.name == 'nt': # for Windows machines, search COM1 to COM255
device_list = []
for k in range(1,255):
s = 'COM%d'%k
device_list.append(s)
for k in range(1,11):
device_list.append(k)
else:
device_list = [] # Gather unused devices from linux_list
for dev in linux_list:
res = commands.getoutput('lsof -t '+ str(dev))
if res == '':
device_list.append(dev)
for dev in device_list:
try:
handle = serial.Serial(dev, BAUDRATE, stopbits=1, timeout = 0.3) #8,1,no parity
except:
continue
self.msg = _('Port %s is existing ') %dev
if handle.isOpen() != True:
print _('but could not open')
continue
self.msg += _('and opened. ')
handle.flush()
time.sleep(.5)
while handle.inWaiting() > 0 :
handle.flushInput()
handle.write(chr(GETVERSION))
res = handle.read(1)
ver = handle.read(5) # 5 character version number
if ver[:2] == 'ej':
self.device = dev
self.fd = handle
self.version = ver
handle.timeout = 4.0 # r2rtime on .7 Hz require this
self.msg += 'Found EYES Junior version ' + ver
return # Successful return
else: # If it is not our device close the file
handle.close()
print self.msg
print _('No EYES Junior hardware detected')
self.fd = None
#------------------------------------------------------------------------------------
def sendByte(self,bval):
self.fd.write(chr(bval))
time.sleep(0.005) # This delay is for MCP2200 + uC
def sendInt(self,ival):
self.fd.write(chr(ival & 255))
time.sleep(0.005) # This delay is for MCP2200 + uC
self.fd.write(chr(ival >> 8))
time.sleep(0.005) # This delay is for MCP2200 + uC
def get_version(self):
self.sendByte(GETVERSION)
res = self.fd.read(1)
if res != 'D':
p.msg = _('GETVERSION ERROR') + res
return
ver = self.fd.read(5)
return ver
#-----------------------------------EEPROM----------------------------------
def eeprom_write(self, addr, data):
'''
Writes a 16 bit number to EEPROM. Returns None or 1
'''
self.sendByte(WREEPROM)
self.sendByte(addr)
self.sendInt(data)
res = self.fd.read(1)
if res != 'D':
self.msg = _('WREEPROM ERROR ') + res
print _('WREEPROM ERROR'), res
return None
return 1 # number of words written
def eeprom_read(self, addr):
'''
Reads a 16 bit word from EEPROM. Returns None on error
'''
self.sendByte(RDEEPROM)
self.sendByte(addr)
res = self.fd.read(1)
if res != 'D':
self.msg = _('RDEEPROM ERROR ') + res
return None
res = self.fd.read(2)
return ord(res[0]) | (ord(res[1]) << 8)
def store_float(self, addr, data): # store a floating point number to EEPROM
'''
Writes a floating point number to EEPROM. Returns None or 1
'''
ss = struct.pack('f', data)
lo = ord(ss[0]) | (ord(ss[1]) << 8)
hi = ord(ss[2]) | (ord(ss[3]) << 8)
if self.eeprom_write(addr, lo) == None:
return None
if self.eeprom_write(addr+1, hi) == None:
return None
return 1
def restore_float(self, addr): # restore a floating point number from EEPROM
'''
Reads a floating point number from EEPROM. Returns None on error
'''
lo = self.eeprom_read(addr)
if lo == None:
return None
hi = self.eeprom_read(addr+1)
data = (hi << 16) | lo
ss = struct.pack('I', data)
res = struct.unpack('f', ss)
return res[0] # return the float
AM1 = 0 # EEPROM location of the parameters, y = mx + c, for A1 and A2
AC1 = 2
AM2 = 4
AC2 = 6
ASOC = 8 # Socket cap IN1
ACCF = 10 # Capacitance error factor
ARP = 12 # Pullup Resistance
def storeCF_a1a2(self, m1,c1,m2,c2): # slope & intercept for A1 and A2
'''
Stores the four calibration factors, of A1&A2, to EEPROM. Returns None or 4
'''
if self.store_float(self.AM1, m1) == None:
return None
self.store_float(self.AC1, c1)
self.store_float(self.AM2, m2)
self.store_float(self.AC2, c2)
return 4 # Number of items written
def storeCF_cap(self, soc, ccf): #Socket capacitance and error factor
'''
Stores the two calibration factors of IN1 to EEPROM. Returns None or 2
'''
if self.store_float(self.ASOC, soc) == None:
return None
self.store_float(self.ACCF, ccf)
return 2
def storeCF_sen(self, r): # pullup resistor value
'''
Stores the calibration factor of SEN to EEPROM. Returns None or 1
'''
if self.store_float(self.ARP, r) == None:
return None
return 1
def load_calibration(self):
try:
m1 = self.restore_float(self.AM1)
c1 = self.restore_float(self.AC1)
m2 = self.restore_float(self.AM2)
c2 = self.restore_float(self.AC2)
m = 10.0/4095
c = -5.0
dm = m * 0.02 # maximum 2% deviation
dc = 5 * 0.02
#print m1,c1,m2,c2, dm, dc
if abs(m1-m) < dm and abs(m2-m) < dm and abs(c1-c) < dc and abs(c2-c) < dc:
self.m12[1] = m1
self.c[1] = c1
self.m12[2] = m2
self.c[2] = c2
self.m8[1] = m1 * 4095./255 # Scale factors for 8 bit read
self.m8[2] = m2 * 4095./255
#print _('Calibration Factors :'), m1,c1,m2,c2
else:
print _('Invalid Calibration factors for A1,A2'), m1,c1,m2,c2
except:
print _('Could not load A1 & A2 Calibration')
try:
soc = self.restore_float(self.ASOC)
ccf = self.restore_float(self.ACCF)
if (.8 < ccf < 1.2) and (20 < soc < 50):
self.cap_calib = ccf
self.socket_cap = soc
#print _('IN1 Calibration :'), ccf, soc
else:
print _('Invalid Calibration factors for IN1'), soc, ccf
except:
print _('Could not load IN1 Capacitor Calibration')
try:
r = self.restore_float(self.ARP)
if 4950 < r < 5250:
self.sen_pullup = r
#print _('SEN Pullup :'), r
else:
print _('Invalid Pullup resistor value'), r
except:
print _('Could not load SEN Pullup calibration')
#------------------------- Infrared comm. ----------------
def irsend1(self, d1):
'''
Sends one byte of data over SQR1, using Infrared transmission protocol
Reception tested using a program running on ATmega32.(refer to microHOPE)
'''
self.sendByte(IRSEND1)
self.sendByte(d1)
res = self.fd.read(1)
if res != 'D':
self.msg = _('IRSEND1 ERROR ') + res
print _('IRSEND1 ERROR'), res
return
return 1
def irsend4(self, d1,d2,d3,d4):
'''
Sends 4 bytes over SQR1, using Infrared transmission protocol used in TVs etc.
Need to be tested properly.
'''
self.sendByte(IRSEND4)
self.sendByte(d1)
self.sendByte(d2)
self.sendByte(d3)
self.sendByte(d4)
res = self.fd.read(1)
if res != 'D':
self.msg = _('IRSEND4 ERROR ')+ res
print _('IRSEND4 ERROR'), res
return
return 1
#--------------------------------------CTMU -------------
ctmui = [550, 0.55, 5.5, 55.0]
def nano_delay(self, i):
'''
Using the CTMU of PIC, measure r2r from IN2 or SEN. uses cap of IN1. Incomplete
ch = 3
self.sendByte(NANODELAY)
self.sendByte(self.rval[i])
res = self.fd.read(1)
if res != 'D':
print _('MEASUREDELAY ERROR'), res
return
res = self.fd.read(2)
iv = ord(res[0]) | (ord(res[1]) << 8)
print iv
v = self.m12[ch] * iv + self.c[ch]
return v
'''
return
def measure_cv(self, ch, ctime, i = 5.5):
'''
Using the CTMU of PIC, charges a capacitor connected to IN1, IN2 or SEN,
for 'ctime' microseconds and then mesures the voltage across it.
The value of current can be set to .55uA, 5.5 uA, 55uA or 550 uA
'''
if i > 500: # 550 uA
irange = 0
elif i > 50: #55 uA
irange = 3
elif i > 5: #5.5 uA, default value
irange = 2
else: # 0.55 uA
irange = 1
if ch not in [3,4]:
self.msg = _('Current to be set only on IN1(3) or IN2(4)')
print _('Current to be set only on IN1 or IN2')
return
self.sendByte(MEASURECV)
self.sendByte(ch)
self.sendByte(irange)
self.sendInt(ctime)
res = self.fd.read(1)
if res != 'D':
self.msg = _('MEASURECV ERROR ') + res
print _('MEASURECV ERROR'), res
return
res = self.fd.read(2)
iv = ord(res[0]) | (ord(res[1]) << 8)
v = self.m12[ch] * iv + self.c[ch]
return v
def measure_cap_raw(self, ctmin = 10):
'''
Measures the capacitance connected between IN1 and GND. Stray capacitance
should be subtracted from the measured value. Measurement is done by charging
the capacitor with 5.5 uA for a given time interval. Any error in the value of
current is corrected by calibrating.
'''
for ctime in range(ctmin, 1000, 10):
v = self.measure_cv(3, ctime, 5.5) # 5.5 uA range is chosen
if v > 2.0: break
if (v > 4) or (v == 0):
self.msg = _('Error measuring capacitance %5.3f') %v
print _('Error measuring capacitance'), v
return None
return 5.5 * ctime / v # returns value in pF
def measure_cap(self, ctmin = 10):
'''
Measures the capacitance connected between IN1 and GND.
Returns the value after applying corrections.
'''
cap = self.measure_cap_raw()
if cap != None:
return (cap - self.socket_cap) * self.cap_calib
else:
return None
def measure_res(self):
'''
Measures the resistance connected between SEN and GND.
'''
v = self.get_voltage(5)
if .1 < v < 4.9:
return self.sen_pullup * v /(5-v)
else:
self.msg = _('Resistance NOT in 100 Ohm to 100 kOhm range')
print _('Resistance NOT in 100 Ohm to 100 kOhm range')
return
def set_current(self, ch, i): # channel 3 or 4, 0 means stop CTMU
'''
Sets CTMU current 'i' on a channel 'ch' and returns the voltage measured
across the load. Allowed values of current are .55, 5.5, 55 and 550 uAmps.
'''
if i > 500: # 550 uA
irange = 0
elif i > 50: #55 uA
irange = 3
elif i > 5: #5.5 uA, default value
irange = 2
else: # 0.55 uA
irange = 1
if i == 0 : # indication to stop CTMU
ch = 0
if ch not in [0,3,4]: # 0 means stopping CTMU
self.msg = _('Current to be set only on IN1 or IN2')
print _('Current to be set only on IN1 or IN2')
return
self.sendByte(SETCURRENT)
self.sendByte(ch)
self.sendByte(irange)
res = self.fd.read(1)
if res != 'D':
self.msg = _('SETCURRENT ERROR') + res
print _('SETCURRENT ERROR'), res
return
res = self.fd.read(2)
iv = ord(res[0]) | (ord(res[1]) << 8)
v = self.m12[ch] * iv + self.c[ch]
return v
def read_temp(self):
'''
Reads the temperature of uC, currently of no use.
Have to see whether this can be used for correcting
the drift of the 5V regulator with temeperature.
'''
self.sendByte(READTEMP)
res = self.fd.read(1)
if res != 'D':
print _('READTEMP error '), res
self.msg = _('READTEMP error') + res
return
res = self.fd.read(2)
iv = ord(res[0]) | (ord(res[1]) << 8)
return iv
#---------- Time Interval Measurements ----------------------
def tim_helper(self, cmd, src, dst):
'''
Helper function for all Time measurement calls. Command,
Source and destination pins are imputs.
Returns time in microseconds, -1 on error.
'''
if cmd == MULTIR2R:
if src not in [0,3,4,5,6,7]:
print _('Pin should be digital input capable: 0,3,4,5,6 or 7')
self.msg = _('Pin should be digital input capable: 0,3,4,5,6 or 7')
return -1
if dst > 249:
self.msg = _('skip exceeded 249 edges')
print _('skip exceeded 249 edges')
return -1
if cmd in [R2RTIME, R2FTIME, F2RTIME, F2FTIME]:
if src not in [0,3,4,5,6,7] or dst not in [0,3,4,5,6,7]:
self.msg = _('Both pins should be digital input capable: 0,3,4,5,6 or 7')
print _('Both pins should be digital input capable: 0,3,4,5,6 or 7')
return -1
if cmd in [SET2RTIME, SET2FTIME, CLR2RTIME, CLR2FTIME, HTPUL2RTIME, HTPUL2FTIME, LTPUL2RTIME, LTPUL2FTIME]:
if src not in [8,9,10,11]:
self.msg = _('Starting pin should be digital output capable: 8,9,10 or 11')
print _('Starting pin should be digital output capable: 8,9,10 or 11')
return -1
if dst not in [0,3,4,5,6,7]:
self.msg = _('Destination pin should be digital input capable: 0,3,4,5,6 or 7')
print _('Destination pin should be digital input capable: 0,3,4,5,6 or 7')
return -1
self.sendByte(cmd)
self.sendByte(src)
self.sendByte(dst)
res = self.fd.read(1)
if res != 'D':
self.msg = _('Time measurement command error')
print _('Time measurement command %d error ') %cmd, res
return -1.0
res = self.fd.read(1)
data = self.fd.read(4)
raw = struct.unpack('I'* 1, data) # 32 bit data from T4/T5 counter, 0.125us cycles
ncycle = raw[0] + 0 # .25 usec correction
return round(float(ncycle)*0.125) # returns in microseconds
#-------------------- Passive Time Interval Measurements ----------------------------------
def r2rtime(self, pin1, pin2):
'''
Time between two rising edges. The pins must be distinct. For same pin, use multi_r2rtime
'''
return self.tim_helper(R2RTIME, pin1, pin2)
def f2ftime(self, pin1, pin2):
'''
Time between two falling edges. The pins must be distinct.
For same pin, use multi_r2rtime
'''
return self.tim_helper(F2FTIME, pin1, pin2)
def r2ftime(self, pin1, pin2):
'''
Time between a rising edge to a falling edge.
The pins could be same or distinct.
'''
return self.tim_helper(R2FTIME, pin1, pin2)
def f2rtime(self, pin1, pin2):
'''
Time between a falling edge to a rising edge.
The pins could be same or distinct.
'''
return self.tim_helper(F2RTIME, pin1, pin2)
def multi_r2rtime(self, pin, skip=0):
'''
Time between rising edges, could skip desired number of edges in between.
(pin, 9) will give time required for
10 cycles of a squarewave, increases resolution.
'''
return self.tim_helper(MULTIR2R, pin, skip)
def get_frequency(self, pin):
'''
This function measures the frequency of an external 0 to 5V PULSE
on digital inputs, by calling multi_r2rtime().
'''
t = self.multi_r2rtime(pin)
if t < 0:
return t
if 0 < t < 10000:
t = self.multi_r2rtime(pin,9)
return 1.0e7/t
return 1.0e6 / t
# Active time interval measurements
def set2rtime(self, pin1, pin2):
'''
Time from setting pin1 to a rising edge on pin2.
'''
return self.tim_helper(SET2RTIME, pin1, pin2)
def set2ftime(self, pin1, pin2):
'''
Time from setting pin1 to a falling edge on pin2.
'''
return self.tim_helper(SET2FTIME, pin1, pin2)
def clr2rtime(self, pin1, pin2):
'''
Time from clearin pin1 to a rising edge on pin2.
'''
return self.tim_helper(CLR2RTIME, pin1, pin2)
def clr2ftime(self, pin1, pin2):
'''
Time from clearing pin1 to a falling edge on pin2.
'''
return self.tim_helper(CLR2FTIME, pin1, pin2)
def htpulse2rtime(self, pin1, pin2):
'''
Time from a HIGH True pulse on pin1 to a rising edge on pin2.
'''
return self.tim_helper(HTPUL2RTIME, pin1, pin2)
def htpulse2ftime(self, pin1, pin2):
'''
Time from HIGH True pulse on pin1 to a falling edge on pin2.
'''
return self.tim_helper(HTPUL2FTIME, pin1, pin2)
def ltpulse2rtime(self, pin1, pin2):
'''
Time from a LOW True pulse on pin1 to a rising edge on pin2.
'''
return self.tim_helper(LTPUL2RTIME, pin1, pin2)
def ltpulse2ftime(self, pin1, pin2):
'''
Time from LOW True pulse on pin1 to a falling edge on pin2.
'''
return self.tim_helper(LTPUL2FTIME, pin1, pin2)
def srfechotime(self, pin1, pin2):
'''
Time from Trigger on Echo for SRF0x module. Trig on pin1 and Echo on pin2.
'''
return self.tim_helper(SRFECHOTIME, pin1, pin2)
#------------------------- Digital I/O-----------------------------
def set_state(self, pin, state):
'''
Sets the status of Digital outputs SQR1, SQR2, OD1 or CCS.
It will work on SQR1 & SQR2 only if the frequency is set to zero.
'''
self.sendByte(SETSTATE)
self.sendByte(pin)
self.sendByte(state)
res = self.fd.read(1)
if res != 'D':
self.msg = _('SETSTATE error ')
print _('SETSTATE error '), res
return
return state
def get_state(self, pin):
'''
gets the status of the digital input pin. IN1, IN2 & SEN are set to digital mode before sensing input level.
'''
self.sendByte(GETSTATE)
self.sendByte(pin)
res = self.fd.read(1)
if res != 'D':
self.msg = _('GETSTATE error ')
print _('GETSTATE error '), res
return
res = self.fd.read(1)
return ord(res)
def get_portb(self):
'''
Reads portB, returns 16 bits of data.
'''
self.sendByte(GETPORTB)
res = self.fd.read(1)
if res != 'D':
self.msg = _('GETPORTB error ')
print _('GETPORTB error '), res
return
res = self.fd.read(2)
raw = struct.unpack('H', res) # 16 bit data in byte array
print '%x'%raw
return raw[0]
#---------------- Square Wave Generation & Measuring the Frequency ------------------
def set_pwm(self, osc, ds, resol=14): # osc and duty cycle, resolution 14 bits byn default
'''
Sets PWM on SQR1 / SQR2. The frequency is decided by the resolution in bits.
'''
if resol < 4 or resol > 16 or ds < 0 or ds > 100:
return
ocxrs = 2**resol
ocx = int(0.01 * ds * ocxrs + 0.5)
#print ocxrs, ocx
if osc == 0:
self.sendByte(SETPWM1)
else:
self.sendByte(SETPWM2)
self.sendInt(ocxrs-1) # ocxrs
self.sendInt(ocx) # ocx
res = self.fd.read(1)
if res != 'D':
self.msg = _('SETPWM error ')
print _('SETPWM error '), res
return
return ds
def set_sqr1_pwm(self, dc, resol=14): # Duty cycle, resolution 14 bits (f = 488Hz) by default
'''
Sets 488 Hz PWM on SQR1. Duty cycle is specified in percentage.
The third argument, PWM resolution, is
14 bits by default. Decreasing this by one doubles the frequency.
'''
return self.set_pwm(0,dc,resol)
def set_sqr2_pwm(self, dc, resol = 14):
'''
Sets 488 Hz PWM on SQR2. Duty cycle is specified in percentage.
The third argument, PWM resolution, is
14 bits by default. Decreasing this by one doubles the frequency.
'''
return self.set_pwm(1,dc,resol)
def set_sqr1_dc(self, volt):
'''
PWM DAC on SQR1. Resolution is 10 bits (f = 7.8 kHz) by default.
External Filter is required to get the DC
The voltage can be set from 0 to 5 volts.
'''
return self.set_pwm(0, volt * 20.0, 10)/20 # 100% => 5V, 10 bit res, 8kHz
def set_sqr2_dc(self, volt):
'''
PWM DAC on SQR2. Resolution is 10 bits (f = 7.8 kHz) by default.
External Filter is required to get the DC
The voltage can be set from 0 to 5 volts.
'''
return self.set_pwm(1, volt * 20.0, 10)/20 #5V correspods to 100%
def set_osc(self, chan, freq): # Freq in Hertz, osc 1 or 2
'''
Sets the output frequency of the SQR1 (chan=8) or SQR2 (chan = 9).
The function returns actual freqency set.
'''
if chan != 8 and chan != 9:
self.msg = _('Invalid channel number')
print _('Invalid Channel')
return
OCRS = 0
TCKPS = 0
if freq < 0: # Disable Timer and Set Output LOW
TCKPS = 254
elif freq == 0:
TCKPS = 255
else:
T = 0.125e-6 # Fosc = 16MHz
mtvals = [T, T*8, T*64, T*256] # Possible Timer period values
per = 1.0/freq # T requested
for k in range(4): # Find the optimum scaling, OCR value
if per < mtvals[k]*50000:
TCKPS = k
OCRS = per/mtvals[k]
OCRS = int(OCRS+0.5)
freq = 1./(mtvals[k]*OCRS)
#print freq,'--', k, OCRS, 1./(mtvals[k]*OCRS), TCKPS
break
if TCKPS < 4 and OCRS == 0:
print _('Invalid Freqency')
return
if chan == 8:
self.sendByte(SETSQR1)
elif chan == 9:
self.sendByte(SETSQR2)
self.sendByte(TCKPS) # prescaling for timer
self.sendInt(OCRS) # OCRS value
res = self.fd.read(1)
if res != 'D':
print _('SETSQR error '), res
return 'Error: '+res
return freq
def set_sqr1(self, freq):
'''
Sets the frequency of SQR1 (between .7Hz and 200kHz).
All intermediate values are not possible.
Returns the actual value set.
'''
return self.set_osc(8, freq)
def set_sqr2(self, freq):
'''
Sets the frequency of SQR2 (between .7Hz and 200kHz).
All intermediate values are not possible.
Returns the actual value set.
'''
return self.set_osc(9, freq)
def set_sqrs(self, freq, diff=0): # Freq in Hertz, phase difference in % of T
'''
Sets the output frequency of both SQR1 & SQR2.
The function returns actual value set. The second argument is the
phase difference between them in percentage.
'''
if freq == 0: # Disable both Square waves
self.set_sqr1(0)
self.set_sqr2(0)
return 0
elif freq < 0: # Disable both Square waves
self.set_sqr1(-1)
self.set_sqr2(-1)
return 0
if diff < 0 or diff >= 100.0:
self.msg = _('Invalid phase difference')
print _('Invalid phase difference')
return
OCRS = 0
TCKPS = 0
T = 0.125e-6 # Fosc = 16MHz
mtvals = [T, T*8, T*64, T*256] # Possible Timer period values
per = 1.0/freq # T requested
for k in range(4): # Find the optimum scaling, OCR value
if per < mtvals[k]*50000:
TCKPS = k
OCRS = per/mtvals[k]
OCRS = int(OCRS+0.5)
freq = 1./(mtvals[k]*OCRS)
#print freq,'--', k, OCRS, 1./(mtvals[k]*OCRS)
break
if TCKPS < 4 and OCRS == 0:
self.msg = _('Invalid Freqency')
print _('Invalid Freqency')
return
TG = int(diff*OCRS/100 +0.5)
if TG == 0: TG = 1 # Need to examine this
#print 'TCKPS ', TCKPS, 'ocrs ', OCRS, TG
self.sendByte(SETSQRS)
self.sendByte(TCKPS) # prescaling for timer
self.sendInt(OCRS) # OCRS value
self.sendInt(TG) # time difference
res = self.fd.read(1)
if res != 'D':
self.msg = _('SETSQRS error ')
print _('SETSQRS error '), res
return
return freq
#--------------------------------- ADC & DAC ----------------------------------------------
def write_dac(self, iv):
'''
Writes the 12 bit I2C DAC to the desired value.
'''
if iv < 0: iv = 0 # Force within limits
if iv > 4095: iv = 4095
self.sendByte(SETDAC)
self.sendInt(iv)
res = self.fd.read(1)
if res != 'D':
self.msg = _('SETDAC error ')
print _('SETDAC error '), res
return
def read_adc(self, ch): # Sleep mode conversion
'''
Reads the specified ADC channel, returns a number from 0 to 4095. Low level routine.
'''
if ch < 0 or ch > 31:
print _('Argument error')
return
self.sendByte(READADCSM)
self.sendByte(ch)
res = self.fd.read(1)
if res != 'D':
self.msg = _('READADC error ')
print _('READADC error '), res
return
res = self.fd.read(2)
iv = ord(res[0]) | (ord(res[1]) << 8)
return iv
def set_voltage(self, v):
'''
Sets the PVS output. range is from -5 to + 5 volts. Reads the actual value to apply correction.
Returns the voltage readback of the voltage at PVS.
'''
if v < 0 or v > 5.0:
self.msg = _('invalid voltage')
print _('invalid voltage')
return
goal = int(v * self.DACM + 0.5)
iv = goal
for k in range(10):
self.write_dac(iv)
isv = self.read_adc(12) # actual value
err = goal - isv
#print 'iv & isv err', iv, isv, err , k
if abs(err) <= 1: break
iv = iv + err/2 # Even if it exceeds 4095, write_dac() will fix it
sv = self.get_voltage(12) # The voltage actually set
return sv
def set_adcref(self, option): # 0 => Vdd, else external +Vref option
'''
Sets the ADC reference option. Vdd ot external +Vref
'''
self.sendByte(SETADCREF)
self.sendByte(option)
res = self.fd.read(1)
if res != 'D':
self.msg = _('SETADCREF error ')
print _('SETADCREF error '), res
return
return option
def read_adcNS(self, ch): # No Sleep mode conversion
'''
Reads the specified ADC channel, returns a number from 0 to 4095. Low level routine.
'''
if ch < 0 or ch > 31:
self.msg = _('READADC: Argument error')
print _('Argument error')
return
self.sendByte(READADC)
self.sendByte(ch)
res = self.fd.read(1)
if res != 'D':
self.msg = _('READADC error')
print _('READADC error'), res
return
res = self.fd.read(2)
iv = ord(res[0]) | (ord(res[1]) << 8)
return iv
def get_voltage(self, ch): # Sleep mode
'''
Reads the specified channel of the ADC. Returns -5V to 5V for channels 0 and 1
0V to 5V for other channels.
'''
if (ch > 31):
self.msg = _('get_voltage: Argument error')
print _('Argument error')
return
iv = self.read_adc(ch)
#print 'get_v: iv = ', iv
v = self.m12[ch] * iv + self.c[ch]
return v
def get_voltageNS(self, ch): # No Sleep Mode
'''
Reads the specified channel of the ADC. Returns -5V to 5V for channels 0 and 1