-
Notifications
You must be signed in to change notification settings - Fork 222
/
Copy pathsciencelab.py
3824 lines (3116 loc) · 152 KB
/
sciencelab.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
# -*- coding: utf-8 -*-
# Communication Library for Pocket Science Lab from FOSSASIA
#
# License : GNU GPL
from __future__ import print_function
import time
import PSL.commands_proto as CP
import PSL.packet_handler as packet_handler
from PSL.achan import *
from PSL.digital_channel import *
def connect(**kwargs):
'''
If hardware is found, returns an instance of 'ScienceLab', else returns None.
'''
obj = ScienceLab(**kwargs)
if obj.H.fd is not None:
return obj
else:
print('Err')
raise RuntimeError('Could Not Connect')
class ScienceLab():
"""
**Communications library.**
This class contains methods that can be used to interact with the FOSSASIA PSLab
Initialization does the following
* connects to tty device
* loads calibration values.
.. tabularcolumns:: |p{3cm}|p{11cm}|
+----------+-----------------------------------------------------------------+
|Arguments |Description |
+==========+=================================================================+
|timeout | serial port read timeout. default = 1s |
+----------+-----------------------------------------------------------------+
>>> from PSL import sciencelab
>>> I = sciencelab.connect()
>>> self.__print__(I)
<sciencelab.ScienceLab instance at 0xb6c0cac>
Once you have initiated this class, its various methods will allow access to all the features built
into the device.
"""
CAP_AND_PCS = 0
ADC_SHIFTS_LOCATION1 = 1
ADC_SHIFTS_LOCATION2 = 2
ADC_POLYNOMIALS_LOCATION = 3
# DAC_POLYNOMIALS_LOCATION=1
DAC_SHIFTS_PV1A = 4
DAC_SHIFTS_PV1B = 5
DAC_SHIFTS_PV2A = 6
DAC_SHIFTS_PV2B = 7
DAC_SHIFTS_PV3A = 8
DAC_SHIFTS_PV3B = 9
LOC_DICT = {'PV1': [4, 5], 'PV2': [6, 7], 'PV3': [8, 9]}
BAUD = 1000000
WType = {'W1': 'sine', 'W2': 'sine'}
def __init__(self, timeout=1.0, **kwargs):
self.verbose = kwargs.get('verbose', False)
self.initialArgs = kwargs
self.generic_name = 'PSLab'
self.DDS_CLOCK = 0
self.timebase = 40
self.MAX_SAMPLES = CP.MAX_SAMPLES
self.samples = self.MAX_SAMPLES
self.triggerLevel = 550
self.triggerChannel = 0
self.error_count = 0
self.channels_in_buffer = 0
self.digital_channels_in_buffer = 0
self.currents = [0.55e-3, 0.55e-6, 0.55e-5, 0.55e-4]
self.currentScalers = [1.0, 1.0, 1.0, 1.0]
self.data_splitting = kwargs.get('data_splitting', CP.DATA_SPLITTING)
self.allAnalogChannels = allAnalogChannels
self.analogInputSources = {}
for a in allAnalogChannels: self.analogInputSources[a] = analogInputSource(a)
self.sine1freq = None
self.sine2freq = None
self.sqrfreq = {'SQR1': None, 'SQR2': None, 'SQR3': None, 'SQR4': None}
self.aboutArray = []
self.errmsg = ''
# --------------------------Initialize communication handler, and subclasses-----------------
self.H = packet_handler.Handler(**kwargs)
self.__runInitSequence__(**kwargs)
def __runInitSequence__(self, **kwargs):
self.aboutArray = []
from PSL.Peripherals import I2C, SPI, NRF24L01, MCP4728
self.connected = self.H.connected
if not self.H.connected:
self.__print__('Check hardware connections. Not connected')
self.streaming = False
self.achans = [analogAcquisitionChannel(a) for a in ['CH1', 'CH2', 'CH3', 'MIC']]
self.gain_values = gains
self.buff = np.zeros(10000)
self.SOCKET_CAPACITANCE = 42e-12 # 42e-12 is typical for the FOSSASIA PSLab. Actual values will be updated during calibration loading
self.resistanceScaling = 1.
self.digital_channel_names = digital_channel_names
self.allDigitalChannels = self.digital_channel_names
self.gains = {'CH1': 0, 'CH2': 0}
# This array of four instances of digital_channel is used to store data retrieved from the
# logic analyzer section of the device. It also contains methods to generate plottable data
# from the original timestamp arrays.
self.dchans = [digital_channel(a) for a in range(4)]
self.I2C = I2C(self.H)
# self.I2C.pullSCLLow(5000)
self.SPI = SPI(self.H)
self.hexid = ''
if self.H.connected:
for a in ['CH1', 'CH2']: self.set_gain(a, 0, True) # Force load gain
for a in ['W1', 'W2']: self.load_equation(a, 'sine')
self.SPI.set_parameters(1, 7, 1, 0)
self.hexid = hex(self.device_id())
self.NRF = NRF24L01(self.H)
self.aboutArray.append(['Radio Transceiver is :', 'Installed' if self.NRF.ready else 'Not Installed'])
self.DAC = MCP4728(self.H, 3.3, 0)
self.calibrated = False
# -------Check for calibration data if connected. And process them if found---------------
if kwargs.get('load_calibration', True) and self.H.connected:
import struct
# Load constants for CTMU and PCS
cap_and_pcs = self.read_bulk_flash(self.CAP_AND_PCS, 8 * 4 + 5) # READY+calibration_string
if cap_and_pcs[:5] == 'READY':
scalers = list(struct.unpack('8f', cap_and_pcs[5:]))
self.SOCKET_CAPACITANCE = scalers[0]
self.DAC.CHANS['PCS'].load_calibration_twopoint(scalers[1],
scalers[2]) # Slope and offset for current source
self.__calibrate_ctmu__(scalers[4:])
self.resistanceScaling = scalers[3] # SEN
self.aboutArray.append(['Capacitance[sock,550uA,55uA,5.5uA,.55uA]'] + scalers[:1] + scalers[4:])
self.aboutArray.append(['PCS slope,offset'] + scalers[1:3])
self.aboutArray.append(['SEN'] + [scalers[3]])
else:
self.SOCKET_CAPACITANCE = 42e-12 # approx
self.__print__('Cap and PCS calibration invalid') # ,cap_and_pcs[:10],'...')
# Load constants for ADC and DAC
polynomials = self.read_bulk_flash(self.ADC_POLYNOMIALS_LOCATION, 2048)
polyDict = {}
if polynomials[:9] == 'PSLab':
self.__print__('ADC calibration found...')
self.aboutArray.append(['Calibration Found'])
self.aboutArray.append([])
self.calibrated = True
adc_shifts = self.read_bulk_flash(self.ADC_SHIFTS_LOCATION1, 2048) + self.read_bulk_flash(
self.ADC_SHIFTS_LOCATION2, 2048)
adc_shifts = [CP.Byte.unpack(a)[0] for a in adc_shifts]
# print(adc_shifts)
self.__print__('ADC INL correction table loaded.')
self.aboutArray.append(['ADC INL Correction found', adc_shifts[0], adc_shifts[1], adc_shifts[2], '...'])
poly_sections = polynomials.split(
'STOP') # The 2K array is split into sections containing data for ADC_INL fit, ADC_CHANNEL fit, DAC_CHANNEL fit, PCS, CAP ...
adc_slopes_offsets = poly_sections[0]
dac_slope_intercept = poly_sections[1]
inl_slope_intercept = poly_sections[2]
# print('COMMON#########',self.__stoa__(slopes_offsets))
# print('DAC#########',self.__stoa__(dac_slope_intercept))
# print('ADC INL ############',self.__stoa__(inl_slope_intercept),len(inl_slope_intercept))
# Load calibration data for ADC channels into an array that'll be evaluated in the next code block
for a in adc_slopes_offsets.split('>|')[1:]:
self.__print__('\n', '>' * 20, a[:3], '<' * 20)
self.aboutArray.append([])
self.aboutArray.append(['ADC Channel', a[:3]])
self.aboutArray.append(['Gain', 'X^3', 'X^2', 'X', 'C'])
cals = a[5:]
polyDict[a[:3]] = []
for b in range(len(cals) // 16):
try:
poly = struct.unpack('4f', cals[b * 16:(b + 1) * 16])
except:
self.__print__(a[:3], ' not calibrated')
self.__print__(b, poly)
self.aboutArray.append([b] + ['%.3e' % v for v in poly])
polyDict[a[:3]].append(poly)
# Load calibration data (slopes and offsets) for ADC channels
inl_slope_intercept = struct.unpack('2f', inl_slope_intercept)
for a in self.analogInputSources:
self.analogInputSources[a].loadCalibrationTable(adc_shifts, inl_slope_intercept[0],
inl_slope_intercept[1])
if a in polyDict:
self.__print__('loading polynomials for ', a, polyDict[a])
self.analogInputSources[a].loadPolynomials(polyDict[a])
self.analogInputSources[a].calibrationReady = True
self.analogInputSources[a].regenerateCalibration()
# Load calibration data for DAC channels
for a in dac_slope_intercept.split('>|')[1:]:
NAME = a[:3] # Name of the DAC channel . PV1, PV2 ...
self.aboutArray.append([])
self.aboutArray.append(['Calibrated :', NAME])
try:
fits = struct.unpack('6f', a[5:])
self.__print__(NAME, ' calibrated', a[5:])
except:
self.__print__(NAME, ' not calibrated', a[5:], len(a[5:]), a)
continue
slope = fits[0]
intercept = fits[1]
fitvals = fits[2:]
if NAME in ['PV1', 'PV2', 'PV3']:
'''
DACs have inherent non-linear behaviour, and the following algorithm generates a correction
array from the calibration data that contains information about the offset(in codes) of each DAC code.
The correction array defines for each DAC code, the number of codes to skip forwards or backwards
in order to output the most accurate voltage value.
E.g. if Code 1024 was found to output a voltage corresponding to code 1030 , and code 1020 was found to output a voltage corresponding to code 1024,
then correction array[1024] = -4 , correction_array[1030]=-6. Adding -4 to the code 1024 will give code 1020 which will output the
correct voltage value expected from code 1024.
The variables LOOKAHEAD and LOOKBEHIND define the range of codes to search around a particular DAC code in order to
find the code with the minimum deviation from the expected value.
'''
DACX = np.linspace(self.DAC.CHANS[NAME].range[0], self.DAC.CHANS[NAME].range[1], 4096)
if NAME == 'PV1':
OFF = self.read_bulk_flash(self.DAC_SHIFTS_PV1A, 2048) + self.read_bulk_flash(
self.DAC_SHIFTS_PV1B, 2048)
elif NAME == 'PV2':
OFF = self.read_bulk_flash(self.DAC_SHIFTS_PV2A, 2048) + self.read_bulk_flash(
self.DAC_SHIFTS_PV2B, 2048)
elif NAME == 'PV3':
OFF = self.read_bulk_flash(self.DAC_SHIFTS_PV3A, 2048) + self.read_bulk_flash(
self.DAC_SHIFTS_PV3B, 2048)
OFF = np.array([ord(data) for data in OFF])
self.__print__('\n', '>' * 20, NAME, '<' * 20)
self.__print__('Offsets :', OFF[:20], '...')
fitfn = np.poly1d(fitvals)
YDATA = fitfn(DACX) - (OFF * slope + intercept)
LOOKBEHIND = 100
LOOKAHEAD = 100
OFF = np.array([np.argmin(
np.fabs(YDATA[max(B - LOOKBEHIND, 0):min(4095, B + LOOKAHEAD)] - DACX[B])) - (
B - max(B - LOOKBEHIND, 0)) for B in range(0, 4096)])
self.aboutArray.append(['Err min:', min(OFF), 'Err max:', max(OFF)])
self.DAC.CHANS[NAME].load_calibration_table(OFF)
def get_resistance(self):
V = self.get_average_voltage('SEN')
if V > 3.295: return np.Inf
I = (3.3 - V) / 5.1e3
res = V / I
return res * self.resistanceScaling
def __ignoreCalibration__(self):
print('CALIBRATION DISABLED')
for a in self.analogInputSources:
self.analogInputSources[a].__ignoreCalibration__()
self.analogInputSources[a].regenerateCalibration()
for a in ['PV1', 'PV2', 'PV3']: self.DAC.__ignoreCalibration__(a)
def __print__(self, *args):
if self.verbose:
for a in args:
print(a, end="")
print()
def __del__(self):
self.H.fd.close()
def get_version(self):
"""
Returns the version string of the device
format: LTS-......
"""
return self.H.get_version(self.H.fd)
def getRadioLinks(self):
return self.NRF.get_nodelist()
def newRadioLink(self, **args):
'''
.. tabularcolumns:: |p{3cm}|p{11cm}|
============== ==============================================================================
**Arguments** Description
============== ==============================================================================
\*\*Kwargs Keyword Arguments
address Address of the node. a 24 bit number. Printed on the nodes.\n
can also be retrieved using :py:meth:`~NRF24L01_class.NRF24L01.get_nodelist`
============== ==============================================================================
:return: :py:meth:`~NRF_NODE.RadioLink`
'''
from PSL.Peripherals import RadioLink
return RadioLink(self.NRF, **args)
# -------------------------------------------------------------------------------------------------------------------#
# |================================================ANALOG SECTION====================================================|
# |This section has commands related to analog measurement and control. These include the oscilloscope routines, |
# |voltmeters, ammeters, and Programmable voltage sources. |
# -------------------------------------------------------------------------------------------------------------------#
def reconnect(self, **kwargs):
'''
Attempts to reconnect to the device in case of a commmunication error or accidental disconnect.
'''
self.H.reconnect(**kwargs)
self.__runInitSequence__(**kwargs)
def capture1(self, ch, ns, tg, *args, **kwargs):
"""
Blocking call that fetches an oscilloscope trace from the specified input channel
.. tabularcolumns:: |p{3cm}|p{11cm}|
============== ============================================================================================
**Arguments**
============== ============================================================================================
ch Channel to select as input. ['CH1'..'CH3','SEN']
ns Number of samples to fetch. Maximum 10000
tg Timegap between samples in microseconds
============== ============================================================================================
.. figure:: images/capture1.png
:width: 11cm
:align: center
:alt: alternate text
:figclass: align-center
A sine wave captured and plotted.
Example
>>> from PSL import *
>>> from PSL import sciencelab
>>> I=sciencelab.connect()
>>> x,y = I.capture1('CH1',3200,1)
>>> plot(x,y)
>>> show()
:return: Arrays X(timestamps),Y(Corresponding Voltage values)
"""
return self.capture_fullspeed(ch, ns, tg, *args, **kwargs)
def capture2(self, ns, tg, TraceOneRemap='CH1'):
"""
Blocking call that fetches oscilloscope traces from CH1,CH2
.. tabularcolumns:: |p{3cm}|p{11cm}|
============== =======================================================================================================
**Arguments**
============== =======================================================================================================
ns Number of samples to fetch. Maximum 5000
tg Timegap between samples in microseconds
TraceOneRemap Choose the analog input for channel 1. It is connected to CH1 by default. Channel 2 always reads CH2.
============== =======================================================================================================
.. figure:: images/capture2.png
:width: 11cm
:align: center
:alt: alternate text
:figclass: align-center
Two sine waves captured and plotted.
Example
>>> from PSL import *
>>> from PSL import sciencelab
>>> I=sciencelab.connect()
>>> x,y1,y2 = I.capture2(1600,2,'MIC') #Chan1 remapped to MIC. Chan2 reads CH2
>>> plot(x,y1) #Plot of analog input MIC
>>> plot(x,y2) #plot of analog input CH2
>>> show()
:return: Arrays X(timestamps),Y1(Voltage at CH1),Y2(Voltage at CH2)
"""
self.capture_traces(2, ns, tg, TraceOneRemap)
time.sleep(1e-6 * self.samples * self.timebase + .01)
while not self.oscilloscope_progress()[0]:
pass
self.__fetch_channel__(1)
self.__fetch_channel__(2)
x = self.achans[0].get_xaxis()
y = self.achans[0].get_yaxis()
y2 = self.achans[1].get_yaxis()
# x,y2=self.fetch_trace(2)
return x, y, y2
def capture4(self, ns, tg, TraceOneRemap='CH1'):
"""
Blocking call that fetches oscilloscope traces from CH1,CH2,CH3,CH4
.. tabularcolumns:: |p{3cm}|p{11cm}|
============== ======================================================================================================
**Arguments**
============== ======================================================================================================
ns Number of samples to fetch. Maximum 2500
tg Timegap between samples in microseconds. Minimum 1.75uS
TraceOneRemap Choose the analog input for channel 1. It is connected to CH1 by default. Channel 2 always reads CH2.
============== ======================================================================================================
.. figure:: images/capture4.png
:width: 11cm
:align: center
:alt: alternate text
:figclass: align-center
Four traces captured and plotted.
Example
>>> from PSL import *
>>> I=sciencelab.ScienceLab()
>>> x,y1,y2,y3,y4 = I.capture4(800,1.75)
>>> plot(x,y1)
>>> plot(x,y2)
>>> plot(x,y3)
>>> plot(x,y4)
>>> show()
:return: Arrays X(timestamps),Y1(Voltage at CH1),Y2(Voltage at CH2),Y3(Voltage at CH3),Y4(Voltage at CH4)
"""
self.capture_traces(4, ns, tg, TraceOneRemap)
time.sleep(1e-6 * self.samples * self.timebase + .01)
while not self.oscilloscope_progress()[0]:
pass
x, y = self.fetch_trace(1)
x, y2 = self.fetch_trace(2)
x, y3 = self.fetch_trace(3)
x, y4 = self.fetch_trace(4)
return x, y, y2, y3, y4
def capture_multiple(self, samples, tg, *args):
"""
Blocking call that fetches oscilloscope traces from a set of specified channels
.. tabularcolumns:: |p{3cm}|p{11cm}|
============== ============================================================================================
**Arguments**
============== ============================================================================================
samples Number of samples to fetch. Maximum 10000/(total specified channels)
tg Timegap between samples in microseconds.
\*args channel names
============== ============================================================================================
Example
>>> from PSL import *
>>> I=sciencelab.ScienceLab()
>>> x,y1,y2,y3,y4 = I.capture_multiple(800,1.75,'CH1','CH2','MIC','SEN')
>>> plot(x,y1)
>>> plot(x,y2)
>>> plot(x,y3)
>>> plot(x,y4)
>>> show()
:return: Arrays X(timestamps),Y1,Y2 ...
"""
if len(args) == 0:
self.__print__('please specify channels to record')
return
tg = int(tg * 8) / 8. # Round off the timescale to 1/8uS units
if (tg < 1.5): tg = int(1.5 * 8) / 8.
total_chans = len(args)
total_samples = samples * total_chans
if (total_samples > self.MAX_SAMPLES):
self.__print__('Sample limit exceeded. 10,000 total')
total_samples = self.MAX_SAMPLES
samples = self.MAX_SAMPLES / total_chans
CHANNEL_SELECTION = 0
for chan in args:
C = self.analogInputSources[chan].CHOSA
self.__print__(chan, C)
CHANNEL_SELECTION |= (1 << C)
self.__print__('selection', CHANNEL_SELECTION, len(args), hex(CHANNEL_SELECTION | ((total_chans - 1) << 12)))
self.H.__sendByte__(CP.ADC)
self.H.__sendByte__(CP.CAPTURE_MULTIPLE)
self.H.__sendInt__(CHANNEL_SELECTION | ((total_chans - 1) << 12))
self.H.__sendInt__(total_samples) # total number of samples to record
self.H.__sendInt__(int(self.timebase * 8)) # Timegap between samples. 8MHz timer clock
self.H.__get_ack__()
self.__print__('wait')
time.sleep(1e-6 * total_samples * tg + .01)
self.__print__('done')
data = b''
for i in range(int(total_samples / self.data_splitting)):
self.H.__sendByte__(CP.ADC)
self.H.__sendByte__(CP.GET_CAPTURE_CHANNEL)
self.H.__sendByte__(0) # channel number . starts with A0 on PIC
self.H.__sendInt__(self.data_splitting)
self.H.__sendInt__(i * self.data_splitting)
data += self.H.fd.read(int(
self.data_splitting * 2)) # reading int by int sometimes causes a communication error. this works better.
self.H.__get_ack__()
if total_samples % self.data_splitting:
self.H.__sendByte__(CP.ADC)
self.H.__sendByte__(CP.GET_CAPTURE_CHANNEL)
self.H.__sendByte__(0) # channel number starts with A0 on PIC
self.H.__sendInt__(total_samples % self.data_splitting)
self.H.__sendInt__(total_samples - total_samples % self.data_splitting)
data += self.H.fd.read(int(2 * (
total_samples % self.data_splitting))) # reading int by int may cause packets to be dropped. this works better.
self.H.__get_ack__()
for a in range(int(total_samples)): self.buff[a] = CP.ShortInt.unpack(data[a * 2:a * 2 + 2])[0]
# self.achans[channel_number-1].yaxis = self.achans[channel_number-1].fix_value(self.buff[:samples])
yield np.linspace(0, tg * (samples - 1), samples)
for a in range(int(total_chans)):
yield self.buff[a:total_samples][::total_chans]
def __capture_fullspeed__(self, chan, samples, tg, *args, **kwargs):
tg = int(tg * 8) / 8. # Round off the timescale to 1/8uS units
if (tg < 0.5): tg = int(0.5 * 8) / 8.
if (samples > self.MAX_SAMPLES):
self.__print__('Sample limit exceeded. 10,000 max')
samples = self.MAX_SAMPLES
self.timebase = int(tg * 8) / 8.
self.samples = samples
CHOSA = self.analogInputSources[chan].CHOSA
self.H.__sendByte__(CP.ADC)
if 'SET_LOW' in args:
self.H.__sendByte__(CP.SET_LO_CAPTURE)
elif 'SET_HIGH' in args:
self.H.__sendByte__(CP.SET_HI_CAPTURE)
elif 'FIRE_PULSES' in args:
self.H.__sendByte__(CP.PULSE_TRAIN)
self.__print__('firing sqr1 pulses for ', kwargs.get('interval', 1000), 'uS')
else:
self.H.__sendByte__(CP.CAPTURE_DMASPEED)
self.H.__sendByte__(CHOSA)
self.H.__sendInt__(samples) # total number of samples to record
self.H.__sendInt__(int(tg * 8)) # Timegap between samples. 8MHz timer clock
if 'FIRE_PULSES' in args:
t = kwargs.get('interval', 1000)
print('Firing for', t, 'uS')
self.H.__sendInt__(t)
time.sleep(
t * 1e-6) # Wait for hardware to free up from firing pulses(blocking call). Background capture starts immediately after this
self.H.__get_ack__()
def capture_fullspeed(self, chan, samples, tg, *args, **kwargs):
"""
Blocking call that fetches oscilloscope traces from a single oscilloscope channel at a maximum speed of 2MSPS
.. tabularcolumns:: |p{3cm}|p{11cm}|
============== ============================================================================================
**Arguments**
============== ============================================================================================
chan channel name 'CH1' / 'CH2' ... 'SEN'
samples Number of samples to fetch. Maximum 10000/(total specified channels)
tg Timegap between samples in microseconds. minimum 0.5uS
\*args specify if SQR1 must be toggled right before capturing.
'SET_LOW' will set SQR1 to 0V
'SET_HIGH' will set it to 5V.
'FIRE_PULSES' will output a preset frequency on SQR1 for a given interval (keyword arg 'interval'
must be specified or it will default to 1000uS) before acquiring data. This is
used for measuring speed of sound using piezos
if no arguments are specified, a regular capture will be executed.
\*\*kwargs
interval units:uS . Necessary if 'FIRE_PULSES' argument was supplied. default 1000uS
============== ============================================================================================
.. code-block:: python
from PSL import *
I=sciencelab.ScienceLab()
x,y = I.capture_fullspeed('CH1',2000,1)
plot(x,y)
show()
.. code-block:: python
x,y = I.capture_fullspeed('CH1',2000,1,'SET_LOW')
plot(x,y)
show()
.. code-block:: python
I.sqr1(40e3 , 50, True ) # Prepare a 40KHz, 50% square wave. Do not output it yet
x,y = I.capture_fullspeed('CH1',2000,1,'FIRE_PULSES',interval = 250) #Output the prepared 40KHz(25uS) wave for 250uS(10 cycles) before acquisition
plot(x,y)
show()
:return: timestamp array ,voltage_value array
"""
self.__capture_fullspeed__(chan, samples, tg, *args, **kwargs)
time.sleep(1e-6 * self.samples * self.timebase + kwargs.get('interval', 0) * 1e-6 + 0.1)
x, y = self.__retrieveBufferData__(chan, self.samples, self.timebase)
return x, self.analogInputSources[chan].calPoly10(y)
def __capture_fullspeed_hr__(self, chan, samples, tg, *args):
tg = int(tg * 8) / 8. # Round off the timescale to 1/8uS units
if (tg < 1): tg = 1.
if (samples > self.MAX_SAMPLES):
self.__print__('Sample limit exceeded. 10,000 max')
samples = self.MAX_SAMPLES
self.timebase = int(tg * 8) / 8.
self.samples = samples
CHOSA = self.analogInputSources[chan].CHOSA
self.H.__sendByte__(CP.ADC)
if 'SET_LOW' in args:
self.H.__sendByte__(CP.SET_LO_CAPTURE)
elif 'SET_HIGH' in args:
self.H.__sendByte__(CP.SET_HI_CAPTURE)
elif 'READ_CAP' in args:
self.H.__sendByte__(CP.MULTIPOINT_CAPACITANCE)
else:
self.H.__sendByte__(CP.CAPTURE_DMASPEED)
self.H.__sendByte__(CHOSA | 0x80)
self.H.__sendInt__(samples) # total number of samples to record
self.H.__sendInt__(int(tg * 8)) # Timegap between samples. 8MHz timer clock
self.H.__get_ack__()
def capture_fullspeed_hr(self, chan, samples, tg, *args):
self.__capture_fullspeed_hr__(chan, samples, tg, *args)
time.sleep(1e-6 * self.samples * self.timebase + .01)
x, y = self.__retrieveBufferData__(chan, self.samples, self.timebase)
return x, self.analogInputSources[chan].calPoly12(y)
def __retrieveBufferData__(self, chan, samples, tg):
'''
'''
data = b''
for i in range(int(samples / self.data_splitting)):
self.H.__sendByte__(CP.ADC)
self.H.__sendByte__(CP.GET_CAPTURE_CHANNEL)
self.H.__sendByte__(0) # channel number . starts with A0 on PIC
self.H.__sendInt__(self.data_splitting)
self.H.__sendInt__(i * self.data_splitting)
data += self.H.fd.read(int(
self.data_splitting * 2)) # reading int by int sometimes causes a communication error. this works better.
self.H.__get_ack__()
if samples % self.data_splitting:
self.H.__sendByte__(CP.ADC)
self.H.__sendByte__(CP.GET_CAPTURE_CHANNEL)
self.H.__sendByte__(0) # channel number starts with A0 on PIC
self.H.__sendInt__(samples % self.data_splitting)
self.H.__sendInt__(samples - samples % self.data_splitting)
data += self.H.fd.read(int(2 * (
samples % self.data_splitting))) # reading int by int may cause packets to be dropped. this works better.
self.H.__get_ack__()
for a in range(int(samples)): self.buff[a] = CP.ShortInt.unpack(data[a * 2:a * 2 + 2])[0]
# self.achans[channel_number-1].yaxis = self.achans[channel_number-1].fix_value(self.buff[:samples])
return np.linspace(0, tg * (samples - 1), samples), self.buff[:samples]
def capture_traces(self, num, samples, tg, channel_one_input='CH1', CH123SA=0, **kwargs):
"""
Instruct the ADC to start sampling. use fetch_trace to retrieve the data
.. tabularcolumns:: |p{3cm}|p{11cm}|
=================== ============================================================================================
**Arguments**
=================== ============================================================================================
num Channels to acquire. 1/2/4
samples Total points to store per channel. Maximum 3200 total.
tg Timegap between two successive samples (in uSec)
channel_one_input map channel 1 to 'CH1' ... 'CH9'
\*\*kwargs
\*trigger Whether or not to trigger the oscilloscope based on the voltage level set by :func:`configure_trigger`
=================== ============================================================================================
see :ref:`capture_video`
.. _adc_example:
.. figure:: images/transient.png
:width: 11cm
:align: center
:alt: alternate text
:figclass: align-center
Transient response of an Inductor and Capacitor in series
The following example demonstrates how to use this function to record active events.
* Connect a capacitor and an Inductor in series.
* Connect CH1 to the spare leg of the inductor. Also Connect OD1 to this point
* Connect CH2 to the junction between the capacitor and the inductor
* connect the spare leg of the capacitor to GND( ground )
* set OD1 initially high using set_state(SQR1=1)
::
>>> I.set_state(OD1=1) #Turn on OD1
#Arbitrary delay to wait for stabilization
>>> time.sleep(0.5)
#Start acquiring data (2 channels,800 samples, 2microsecond intervals)
>>> I.capture_traces(2,800,2,trigger=False)
#Turn off OD1. This must occur immediately after the previous line was executed.
>>> I.set_state(OD1=0)
#Minimum interval to wait for completion of data acquisition.
#samples*timegap*(convert to Seconds)
>>> time.sleep(800*2*1e-6)
>>> x,CH1=I.fetch_trace(1)
>>> x,CH2=I.fetch_trace(2)
>>> plot(x,CH1-CH2) #Voltage across the inductor
>>> plot(x,CH2) ##Voltage across the capacitor
>>> show()
The following events take place when the above snippet runs
#. The oscilloscope starts storing voltages present at CH1 and CH2 every 2 microseconds
#. The output OD1 was enabled, and this causes the voltage between the L and C to approach OD1 voltage.
(It may or may not oscillate)
#. The data from CH1 and CH2 was read into x,CH1,CH2
#. Both traces were plotted in order to visualize the Transient response of series LC
:return: nothing
.. seealso::
:func:`fetch_trace` , :func:`oscilloscope_progress` , :func:`capture1` , :func:`capture2` , :func:`capture4`
"""
triggerornot = 0x80 if kwargs.get('trigger', True) else 0
self.timebase = tg
self.timebase = int(self.timebase * 8) / 8. # Round off the timescale to 1/8uS units
if channel_one_input not in self.analogInputSources: raise RuntimeError(
'Invalid input %s, not in %s' % (channel_one_input, str(self.analogInputSources.keys())))
CHOSA = self.analogInputSources[channel_one_input].CHOSA
self.H.__sendByte__(CP.ADC)
if (num == 1):
if (self.timebase < 1.5): self.timebase = int(1.5 * 8) / 8.
if (samples > self.MAX_SAMPLES): samples = self.MAX_SAMPLES
self.achans[0].set_params(channel=channel_one_input, length=samples, timebase=self.timebase,
resolution=10, source=self.analogInputSources[channel_one_input])
self.H.__sendByte__(CP.CAPTURE_ONE) # read 1 channel
self.H.__sendByte__(CHOSA | triggerornot) # channelk number
elif (num == 2):
if (self.timebase < 1.75): self.timebase = int(1.75 * 8) / 8.
if (samples > self.MAX_SAMPLES / 2): samples = self.MAX_SAMPLES / 2
self.achans[0].set_params(channel=channel_one_input, length=samples, timebase=self.timebase,
resolution=10, source=self.analogInputSources[channel_one_input])
self.achans[1].set_params(channel='CH2', length=samples, timebase=self.timebase, resolution=10,
source=self.analogInputSources['CH2'])
self.H.__sendByte__(CP.CAPTURE_TWO) # capture 2 channels
self.H.__sendByte__(CHOSA | triggerornot) # channel 0 number
elif (num == 3 or num == 4):
if (self.timebase < 1.75): self.timebase = int(1.75 * 8) / 8.
if (samples > self.MAX_SAMPLES / 4): samples = self.MAX_SAMPLES / 4
self.achans[0].set_params(channel=channel_one_input, length=samples, timebase=self.timebase, \
resolution=10, source=self.analogInputSources[channel_one_input])
for a in range(1, 4):
chans = ['NONE', 'CH2', 'CH3', 'MIC']
self.achans[a].set_params(channel=chans[a], length=samples, timebase=self.timebase, \
resolution=10, source=self.analogInputSources[chans[a]])
self.H.__sendByte__(CP.CAPTURE_FOUR) # read 4 channels
self.H.__sendByte__(CHOSA | (CH123SA << 4) | triggerornot) # channel number
self.samples = samples
self.H.__sendInt__(samples) # number of samples per channel to record
self.H.__sendInt__(int(self.timebase * 8)) # Timegap between samples. 8MHz timer clock
self.H.__get_ack__()
self.channels_in_buffer = num
def capture_highres_traces(self, channel, samples, tg, **kwargs):
"""
Instruct the ADC to start sampling. use fetch_trace to retrieve the data
.. tabularcolumns:: |p{3cm}|p{11cm}|
=================== ============================================================================================
**Arguments**
=================== ============================================================================================
channel channel to acquire data from 'CH1' ... 'CH9'
samples Total points to store per channel. Maximum 3200 total.
tg Timegap between two successive samples (in uSec)
\*\*kwargs
\*trigger Whether or not to trigger the oscilloscope based on the voltage level set by :func:`configure_trigger`
=================== ============================================================================================
:return: nothing
.. seealso::
:func:`fetch_trace` , :func:`oscilloscope_progress` , :func:`capture1` , :func:`capture2` , :func:`capture4`
"""
triggerornot = 0x80 if kwargs.get('trigger', True) else 0
self.timebase = tg
self.H.__sendByte__(CP.ADC)
CHOSA = self.analogInputSources[channel].CHOSA
if (self.timebase < 3): self.timebase = 3
if (samples > self.MAX_SAMPLES): samples = self.MAX_SAMPLES
self.achans[0].set_params(channel=channel, length=samples, timebase=self.timebase, resolution=12,
source=self.analogInputSources[channel])
self.H.__sendByte__(CP.CAPTURE_12BIT) # read 1 channel
self.H.__sendByte__(CHOSA | triggerornot) # channelk number
self.samples = samples
self.H.__sendInt__(samples) # number of samples to read
self.H.__sendInt__(int(self.timebase * 8)) # Timegap between samples. 8MHz timer clock
self.H.__get_ack__()
self.channels_in_buffer = 1
def fetch_trace(self, channel_number):
"""
fetches a channel(1-4) captured by :func:`capture_traces` called prior to this, and returns xaxis,yaxis
.. tabularcolumns:: |p{3cm}|p{11cm}|
============== ============================================================================================
**Arguments**
============== ============================================================================================
channel_number Any of the maximum of four channels that the oscilloscope captured. 1/2/3/4
============== ============================================================================================
:return: time array,voltage array
.. seealso::
:func:`capture_traces` , :func:`oscilloscope_progress`
"""
self.__fetch_channel__(channel_number)
return self.achans[channel_number - 1].get_xaxis(), self.achans[channel_number - 1].get_yaxis()
def oscilloscope_progress(self):
"""
returns the number of samples acquired by the capture routines, and the conversion_done status
:return: conversion done(bool) ,samples acquired (number)
>>> I.start_capture(1,3200,2)
>>> self.__print__(I.oscilloscope_progress())
(0,46)
>>> time.sleep(3200*2e-6)
>>> self.__print__(I.oscilloscope_progress())
(1,3200)
.. seealso::
:func:`fetch_trace` , :func:`capture_traces`
"""
conversion_done = 0
samples = 0
self.H.__sendByte__(CP.ADC)
self.H.__sendByte__(CP.GET_CAPTURE_STATUS)
conversion_done = self.H.__getByte__()
samples = self.H.__getInt__()
self.H.__get_ack__()
return conversion_done, samples
def __fetch_channel__(self, channel_number):
"""
Fetches a section of data from any channel and stores it in the relevant instance of achan()
.. tabularcolumns:: |p{3cm}|p{11cm}|
============== ============================================================================================
**Arguments**
============== ============================================================================================
channel_number channel number (1,2,3,4)
============== ============================================================================================
:return: True if successful
"""
samples = self.achans[channel_number - 1].length
if (channel_number > self.channels_in_buffer):
self.__print__('Channel unavailable')
return False
data = b''
for i in range(int(samples / self.data_splitting)):
self.H.__sendByte__(CP.ADC)
self.H.__sendByte__(CP.GET_CAPTURE_CHANNEL)
self.H.__sendByte__(channel_number - 1) # starts with A0 on PIC
self.H.__sendInt__(self.data_splitting)
self.H.__sendInt__(i * self.data_splitting)
data += self.H.fd.read(
int(self.data_splitting * 2)) # reading int by int sometimes causes a communication error.
self.H.__get_ack__()
if samples % self.data_splitting:
self.H.__sendByte__(CP.ADC)
self.H.__sendByte__(CP.GET_CAPTURE_CHANNEL)
self.H.__sendByte__(channel_number - 1) # starts with A0 on PIC
self.H.__sendInt__(samples % self.data_splitting)
self.H.__sendInt__(samples - samples % self.data_splitting)
data += self.H.fd.read(
int(2 * (samples % self.data_splitting))) # reading int by int may cause packets to be dropped.
self.H.__get_ack__()
for a in range(int(samples)): self.buff[a] = CP.ShortInt.unpack(data[a * 2:a * 2 + 2])[0]
self.achans[channel_number - 1].yaxis = self.achans[channel_number - 1].fix_value(self.buff[:int(samples)])
return True
def __fetch_channel_oneshot__(self, channel_number):
"""
Fetches all data from given channel and stores it in the relevant instance of achan()
.. tabularcolumns:: |p{3cm}|p{11cm}|
============== ============================================================================================
**Arguments**
============== ============================================================================================
channel_number channel number (1,2,3,4)
============== ============================================================================================
"""
offset = 0
samples = self.achans[channel_number - 1].length
if (channel_number > self.channels_in_buffer):
self.__print__('Channel unavailable')
return False
self.H.__sendByte__(CP.ADC)
self.H.__sendByte__(CP.GET_CAPTURE_CHANNEL)
self.H.__sendByte__(channel_number - 1) # starts with A0 on PIC
self.H.__sendInt__(samples)
self.H.__sendInt__(offset)
data = self.H.fd.read(
int(samples * 2)) # reading int by int sometimes causes a communication error. this works better.
self.H.__get_ack__()
for a in range(int(samples)): self.buff[a] = CP.ShortInt.unpack(data[a * 2:a * 2 + 2])[0]
self.achans[channel_number - 1].yaxis = self.achans[channel_number - 1].fix_value(self.buff[:samples])
return True
def configure_trigger(self, chan, name, voltage, resolution=10, **kwargs):
"""
configure trigger parameters for 10-bit capture commands
The capture routines will wait till a rising edge of the input signal crosses the specified level.
The trigger will timeout within 8mS, and capture routines will start regardless.
These settings will not be used if the trigger option in the capture routines are set to False
.. tabularcolumns:: |p{3cm}|p{11cm}|
============== =====================================================================================================================