forked from fossasia/pslab-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsciencelab.py
More file actions
1732 lines (1408 loc) · 65.5 KB
/
sciencelab.py
File metadata and controls
1732 lines (1408 loc) · 65.5 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
# -*- coding: utf-8 -*-
# Communication Library for Pocket Science Lab from FOSSASIA
#
# License : GNU GPL
from __future__ import print_function
import time
import numpy as np
import PSL.commands_proto as CP
import PSL.packet_handler as packet_handler
from PSL.logic_analyzer import LogicAnalyzer
from PSL.oscilloscope import Oscilloscope
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
.. 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.
"""
BAUD = 1000000
WType = {'SI1': 'sine', 'SI2': '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.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.logic_analyzer = LogicAnalyzer(device=self.H)
self.oscilloscope = Oscilloscope(device=self.H)
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.buff = np.zeros(10000)
self.SOCKET_CAPACITANCE = 42e-12 # 42e-12 is typical for the FOSSASIA PSLab. Actual values require calibration (currently not supported).
self.resistanceScaling = 1.
self.gains = {'CH1': 0, 'CH2': 0}
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.oscilloscope._channels[a].gain = 1
for a in ['SI1', 'SI2']: 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)
def get_resistance(self):
V = self.get_average_voltage('RES')
if V > 3.295: return np.Inf
I = (3.3 - V) / 5.1e3
res = V / I
return res * self.resistanceScaling
def __print__(self, *args):
if self.verbose:
for a in args:
print(a, end="")
print()
def get_version(self):
"""
Returns the version string of the device
format: LTS-......
"""
return self.H.get_version()
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 get_voltage(self, channel_name, **kwargs):
self.voltmeter_autorange(channel_name)
return self.get_average_voltage(channel_name, **kwargs)
def voltmeter_autorange(self, channel_name):
try:
self.oscilloscope._channels[channel_name].gain = 1
except TypeError: # channel_name is not CH1 or CH2.
return 1
V = self.get_average_voltage(channel_name)
return self.__autoSelectRange__(channel_name, V)
def __autoSelectRange__(self, channel_name, V):
keys = [8, 4, 3, 2, 1.5, 1, .5, 0]
cutoffs = {8: 1, 4: 2, 3: 4, 2: 5, 1.5: 8, 1.: 10, .5: 16, 0: 32}
for a in keys:
if abs(V) > a:
g = cutoffs[a]
break
self.oscilloscope._channels[channel_name].gain = g
return g
def __autoRangeScope__(self, tg):
x, y1, y2 = self.oscilloscope.capture(2, 1000, tg)
self.__autoSelectRange__('CH1', max(abs(y1)))
self.__autoSelectRange__('CH2', max(abs(y2)))
def get_average_voltage(self, channel_name, **kwargs):
"""
Return the voltage on the selected channel
.. tabularcolumns:: |p{3cm}|p{11cm}|
+------------+-----------------------------------------------------------------------------------------+
|Arguments |Description |
+============+=========================================================================================+
|channel_name| 'CH1','CH2','CH3', 'MIC','IN1','RES','V+' |
+------------+-----------------------------------------------------------------------------------------+
|sleep | read voltage in CPU sleep mode. not particularly useful. Also, Buggy. |
+------------+-----------------------------------------------------------------------------------------+
|\*\*kwargs | Samples to average can be specified. eg. samples=100 will average a hundred readings |
+------------+-----------------------------------------------------------------------------------------+
see :ref:`stream_video`
Example:
>>> self.__print__(I.get_average_voltage('CH4'))
1.002
"""
self.oscilloscope._channels[channel_name].resolution = 12
scale = self.oscilloscope._channels[channel_name].scale
vals = [self.__get_raw_average_voltage__(channel_name, **kwargs) for a in range(int(kwargs.get('samples', 1)))]
# if vals[0]>2052:print (vals)
val = np.average([scale(a) for a in vals])
return val
def __get_raw_average_voltage__(self, channel_name, **kwargs):
"""
Return the average of 16 raw 12-bit ADC values of the voltage on the selected channel
.. tabularcolumns:: |p{3cm}|p{11cm}|
============== ============================================================================================================
**Arguments**
============== ============================================================================================================
channel_name 'CH1', 'CH2', 'CH3', 'MIC', '5V', 'IN1','RES'
sleep read voltage in CPU sleep mode
============== ============================================================================================================
"""
chosa = self.oscilloscope._channels[channel_name].chosa
self.H.__sendByte__(CP.ADC)
self.H.__sendByte__(CP.GET_VOLTAGE_SUMMED)
self.H.__sendByte__(chosa)
V_sum = self.H.__getInt__()
self.H.__get_ack__()
return V_sum / 16. # sum(V)/16.0 #
def fetch_buffer(self, starting_position=0, total_points=100):
"""
fetches a section of the ADC hardware buffer
"""
self.H.__sendByte__(CP.COMMON)
self.H.__sendByte__(CP.RETRIEVE_BUFFER)
self.H.__sendInt__(starting_position)
self.H.__sendInt__(total_points)
for a in range(int(total_points)): self.buff[a] = self.H.__getInt__()
self.H.__get_ack__()
def clear_buffer(self, starting_position, total_points):
"""
clears a section of the ADC hardware buffer
"""
self.H.__sendByte__(CP.COMMON)
self.H.__sendByte__(CP.CLEAR_BUFFER)
self.H.__sendInt__(starting_position)
self.H.__sendInt__(total_points)
self.H.__get_ack__()
def fill_buffer(self, starting_position, point_array):
"""
fill a section of the ADC hardware buffer with data
"""
self.H.__sendByte__(CP.COMMON)
self.H.__sendByte__(CP.FILL_BUFFER)
self.H.__sendInt__(starting_position)
self.H.__sendInt__(len(point_array))
for a in point_array:
self.H.__sendInt__(int(a))
self.H.__get_ack__()
def start_streaming(self, tg, channel='CH1'):
"""
Instruct the ADC to start streaming 8-bit data. use stop_streaming to stop.
.. tabularcolumns:: |p{3cm}|p{11cm}|
============== ============================================================================================
**Arguments**
============== ============================================================================================
tg timegap. 250KHz clock
channel channel 'CH1'... 'CH9','IN1','RES'
============== ============================================================================================
"""
chosa = self.oscilloscope.channels[channel].chosa
if (self.streaming): self.stop_streaming()
self.H.__sendByte__(CP.ADC)
self.H.__sendByte__(CP.START_ADC_STREAMING)
self.H.__sendByte__(chosa)
self.H.__sendInt__(tg) # Timegap between samples. 8MHz timer clock
self.streaming = True
def stop_streaming(self):
"""
Instruct the ADC to stop streaming data
"""
if (self.streaming):
self.H.__sendByte__(CP.STOP_STREAMING)
self.H.fd.read(20000)
self.H.fd.flush()
else:
self.__print__('not streaming')
self.streaming = False
# -------------------------------------------------------------------------------------------------------------------#
# |===============================================DIGITAL SECTION====================================================|
# |This section has commands related to digital measurement and control. These include the Logic Analyzer, frequency |
# |measurement calls, timing routines, digital outputs etc |
# -------------------------------------------------------------------------------------------------------------------#
def set_state(self, **kwargs):
"""
set the logic level on digital outputs SQR1,SQR2,SQR3,SQR4
.. tabularcolumns:: |p{3cm}|p{11cm}|
============== ============================================================================================
**Arguments**
============== ============================================================================================
\*\*kwargs SQR1,SQR2,SQR3,SQR4
states(0 or 1)
============== ============================================================================================
>>> I.set_state(SQR1=1,SQR2=0)
sets SQR1 HIGH, SQR2 LOw, but leave SQR3,SQR4 untouched.
"""
data = 0
if 'SQR1' in kwargs:
data |= 0x10 | (kwargs.get('SQR1'))
if 'SQR2' in kwargs:
data |= 0x20 | (kwargs.get('SQR2') << 1)
if 'SQR3' in kwargs:
data |= 0x40 | (kwargs.get('SQR3') << 2)
if 'SQR4' in kwargs:
data |= 0x80 | (kwargs.get('SQR4') << 3)
self.H.__sendByte__(CP.DOUT)
self.H.__sendByte__(CP.SET_STATE)
self.H.__sendByte__(data)
self.H.__get_ack__()
def __charge_cap__(self, state, t):
self.H.__sendByte__(CP.ADC)
self.H.__sendByte__(CP.SET_CAP)
self.H.__sendByte__(state)
self.H.__sendInt__(t)
self.H.__get_ack__()
def __capture_capacitance__(self, samples, tg):
raise NotImplementedError
# from PSL.analyticsClass import analyticsClass
# self.AC = analyticsClass()
# self.__charge_cap__(1, 50000)
# x, y = self.capture_fullspeed_hr('CAP', samples, tg, 'READ_CAP')
# fitres = self.AC.fit_exp(x * 1e-6, y)
# if fitres:
# cVal, newy = fitres
# # from PSL import *
# # plot(x,newy)
# # show()
# return x, y, newy, cVal
# else:
# return None
def capacitance_via_RC_discharge(self):
cap = self.get_capacitor_range()[1]
T = 2 * cap * 20e3 * 1e6 # uS
samples = 500
if T > 5000 and T < 10e6:
if T > 50e3: samples = 250
RC = self.__capture_capacitance__(samples, int(T / samples))[3][1]
return RC / 10e3
else:
self.__print__('cap out of range %f %f' % (T, cap))
return 0
def __get_capacitor_range__(self, ctime):
self.__charge_cap__(0, 30000)
self.H.__sendByte__(CP.COMMON)
self.H.__sendByte__(CP.GET_CAP_RANGE)
self.H.__sendInt__(ctime)
V_sum = self.H.__getInt__()
self.H.__get_ack__()
V = V_sum * 3.3 / 16 / 4095
C = -ctime * 1e-6 / 1e4 / np.log(1 - V / 3.3)
return V, C
def get_capacitor_range(self):
"""
Charges a capacitor connected to IN1 via a 20K resistor from a 3.3V source for a fixed interval
Returns the capacitance calculated using the formula Vc = Vs(1-exp(-t/RC))
This function allows an estimation of the parameters to be used with the :func:`get_capacitance` function.
"""
t = 10
P = [1.5, 50e-12]
for a in range(4):
P = list(self.__get_capacitor_range__(50 * (10 ** a)))
if (P[0] > 1.5):
if a == 0 and P[0] > 3.28: # pico farads range. Values will be incorrect using this method
P[1] = 50e-12
break
return P
def get_capacitance(self): # time in uS
"""
measures capacitance of component connected between CAP and ground
:return: Capacitance (F)
Constant Current Charging
.. math::
Q_{stored} = C*V
I_{constant}*time = C*V
C = I_{constant}*time/V_{measured}
Also uses Constant Voltage Charging via 20K resistor if required.
"""
GOOD_VOLTS = [2.5, 2.8]
CT = 10
CR = 1
iterations = 0
start_time = time.time()
while (time.time() - start_time) < 1:
# self.__print__('vals',CR,',',CT)
if CT > 65000:
self.__print__('CT too high')
return self.capacitance_via_RC_discharge()
V, C = self.__get_capacitance__(CR, 0, CT)
# print(CR,CT,V,C)
if CT > 30000 and V < 0.1:
self.__print__('Capacitance too high for this method')
return 0
elif V > GOOD_VOLTS[0] and V < GOOD_VOLTS[1]:
return C
elif V < GOOD_VOLTS[0] and V > 0.01 and CT < 40000:
if GOOD_VOLTS[0] / V > 1.1 and iterations < 10:
CT = int(CT * GOOD_VOLTS[0] / V)
iterations += 1
self.__print__('increased CT ', CT)
elif iterations == 10:
return 0
else:
return C
elif V <= 0.1 and CR < 3:
CR += 1
elif CR == 3:
self.__print__('Capture mode ')
return self.capacitance_via_RC_discharge()
def __get_capacitance__(self, current_range, trim, Charge_Time): # time in uS
self.__charge_cap__(0, 30000)
self.H.__sendByte__(CP.COMMON)
self.H.__sendByte__(CP.GET_CAPACITANCE)
self.H.__sendByte__(current_range)
if (trim < 0):
self.H.__sendByte__(int(31 - abs(trim) / 2) | 32)
else:
self.H.__sendByte__(int(trim / 2))
self.H.__sendInt__(Charge_Time)
time.sleep(Charge_Time * 1e-6 + .02)
VCode = self.H.__getInt__()
V = 3.3 * VCode / 4095
self.H.__get_ack__()
Charge_Current = self.currents[current_range] * (100 + trim) / 100.0
if V:
C = (Charge_Current * Charge_Time * 1e-6 / V - self.SOCKET_CAPACITANCE) / self.currentScalers[
current_range]
else:
C = 0
return V, C
def get_temperature(self):
"""
return the processor's temperature
:return: Chip Temperature in degree Celcius
"""
cs = 3
V = self.get_ctmu_voltage(0b11110, cs, 0)
if cs == 1:
return (646 - V * 1000) / 1.92 # current source = 1
elif cs == 2:
return (701.5 - V * 1000) / 1.74 # current source = 2
elif cs == 3:
return (760 - V * 1000) / 1.56 # current source = 3
def get_ctmu_voltage(self, channel, Crange, tgen=1):
"""
get_ctmu_voltage(5,2) will activate a constant current source of 5.5uA on IN1 and then measure the voltage at the output.
If a diode is used to connect IN1 to ground, the forward voltage drop of the diode will be returned. e.g. .6V for a 4148diode.
If a resistor is connected, ohm's law will be followed within reasonable limits
channel=5 for IN1
CRange=0 implies 550uA
CRange=1 implies 0.55uA
CRange=2 implies 5.5uA
CRange=3 implies 55uA
:return: Voltage
"""
if channel == 'CAP': channel = 5
self.H.__sendByte__(CP.COMMON)
self.H.__sendByte__(CP.GET_CTMU_VOLTAGE)
self.H.__sendByte__((channel) | (Crange << 5) | (tgen << 7))
v = self.H.__getInt__() # 16*voltage across the current source
self.H.__get_ack__()
V = 3.3 * v / 16 / 4095.
return V
def __start_ctmu__(self, Crange, trim, tgen=1):
self.H.__sendByte__(CP.COMMON)
self.H.__sendByte__(CP.START_CTMU)
self.H.__sendByte__((Crange) | (tgen << 7))
self.H.__sendByte__(trim)
self.H.__get_ack__()
def __stop_ctmu__(self):
self.H.__sendByte__(CP.COMMON)
self.H.__sendByte__(CP.STOP_CTMU)
self.H.__get_ack__()
def resetHardware(self):
"""
Resets the device, and standalone mode will be enabled if an OLED is connected to the I2C port
"""
self.H.__sendByte__(CP.COMMON)
self.H.__sendByte__(CP.RESTORE_STANDALONE)
def read_flash(self, page, location):
"""
Reads 16 BYTES from the specified location
.. tabularcolumns:: |p{3cm}|p{11cm}|
================ ============================================================================================
**Arguments**
================ ============================================================================================
page page number. 20 pages with 2KBytes each
location The flash location(0 to 63) to read from .
================ ============================================================================================
:return: a string of 16 characters read from the location
"""
self.H.__sendByte__(CP.FLASH)
self.H.__sendByte__(CP.READ_FLASH)
self.H.__sendByte__(page) # send the page number. 20 pages with 2K bytes each
self.H.__sendByte__(location) # send the location
ss = self.H.fd.read(16)
self.H.__get_ack__()
return ss
def read_bulk_flash(self, page, numbytes):
"""
Reads BYTES from the specified location
.. tabularcolumns:: |p{3cm}|p{11cm}|
================ ============================================================================================
**Arguments**
================ ============================================================================================
page Block number. 0-20. each block is 2kB.
numbytes Total bytes to read
================ ============================================================================================
:return: a string of 16 characters read from the location
"""
self.H.__sendByte__(CP.FLASH)
self.H.__sendByte__(CP.READ_BULK_FLASH)
bytes_to_read = numbytes
if numbytes % 2: bytes_to_read += 1 # bytes+1 . stuff is stored as integers (byte+byte) in the hardware
self.H.__sendInt__(bytes_to_read)
self.H.__sendByte__(page)
ss = self.H.fd.read(int(bytes_to_read))
self.H.__get_ack__()
if numbytes % 2: return ss[:-1] # Kill the extra character we read. Don't surprise the user with extra data
return ss
def write_flash(self, page, location, string_to_write):
"""
write a 16 BYTE string to the selected location (0-63)
DO NOT USE THIS UNLESS YOU'RE ABSOLUTELY SURE KNOW THIS!
YOU MAY END UP OVERWRITING THE CALIBRATION DATA, AND WILL HAVE
TO GO THROUGH THE TROUBLE OF GETTING IT FROM THE MANUFACTURER AND
REFLASHING IT.
.. tabularcolumns:: |p{3cm}|p{11cm}|
================ ============================================================================================
**Arguments**
================ ============================================================================================
page page number. 20 pages with 2KBytes each
location The flash location(0 to 63) to write to.
string_to_write a string of 16 characters can be written to each location
================ ============================================================================================
"""
while (len(string_to_write) < 16): string_to_write += '.'
self.H.__sendByte__(CP.FLASH)
self.H.__sendByte__(CP.WRITE_FLASH) # indicate a flash write coming through
self.H.__sendByte__(page) # send the page number. 20 pages with 2K bytes each
self.H.__sendByte__(location) # send the location
self.H.fd.write(string_to_write)
time.sleep(0.1)
self.H.__get_ack__()
def write_bulk_flash(self, location, data):
"""
write a byte array to the entire flash page. Erases any other data
DO NOT USE THIS UNLESS YOU'RE ABSOLUTELY SURE YOU KNOW THIS!
YOU MAY END UP OVERWRITING THE CALIBRATION DATA, AND WILL HAVE
TO GO THROUGH THE TROUBLE OF GETTING IT FROM THE MANUFACTURER AND
REFLASHING IT.
.. tabularcolumns:: |p{3cm}|p{11cm}|
================ ============================================================================================
**Arguments**
================ ============================================================================================
location Block number. 0-20. each block is 2kB.
bytearray Array to dump onto flash. Max size 2048 bytes
================ ============================================================================================
"""
if (type(data) == str): data = [ord(a) for a in data]
if len(data) % 2 == 1: data.append(0)
self.H.__sendByte__(CP.FLASH)
self.H.__sendByte__(CP.WRITE_BULK_FLASH) # indicate a flash write coming through
self.H.__sendInt__(len(data)) # send the length
self.H.__sendByte__(location)
for n in range(len(data)):
self.H.__sendByte__(data[n])
self.H.__get_ack__()
# verification by readback
tmp = [ord(a) for a in self.read_bulk_flash(location, len(data))]
print('Verification done', tmp == data)
if tmp != data: raise Exception('Verification by readback failed')
# -------------------------------------------------------------------------------------------------------------------#
# |===============================================WAVEGEN SECTION====================================================|
# |This section has commands related to waveform generators SI1, SI2, PWM outputs, servo motor control etc. |
# -------------------------------------------------------------------------------------------------------------------#
def set_wave(self, chan, freq):
"""
Set the frequency of wavegen
.. tabularcolumns:: |p{3cm}|p{11cm}|
============== ============================================================================================
**Arguments**
============== ============================================================================================
chan Channel to set frequency for. SI1 or SI2
frequency Frequency to set on wave generator
============== ============================================================================================
:return: frequency
"""
if chan == 'SI1':
self.set_w1(freq)
elif chan == 'SI2':
self.set_w2(freq)
def set_sine1(self, freq):
"""
Set the frequency of wavegen 1 after setting its waveform type to sinusoidal
.. tabularcolumns:: |p{3cm}|p{11cm}|
============== ============================================================================================
**Arguments**
============== ============================================================================================
frequency Frequency to set on wave generator 1.
============== ============================================================================================
:return: frequency
"""
return self.set_w1(freq, 'sine')
def set_sine2(self, freq):
"""
Set the frequency of wavegen 2 after setting its waveform type to sinusoidal
.. tabularcolumns:: |p{3cm}|p{11cm}|
============== ============================================================================================
**Arguments**
============== ============================================================================================
frequency Frequency to set on wave generator 1.
============== ============================================================================================
:return: frequency
"""
return self.set_w2(freq, 'sine')
def set_w1(self, freq, waveType=None):
"""
Set the frequency of wavegen 1
.. tabularcolumns:: |p{3cm}|p{11cm}|
============== ============================================================================================
**Arguments**
============== ============================================================================================
frequency Frequency to set on wave generator 1.
waveType 'sine','tria' . Default : Do not reload table. and use last set table
============== ============================================================================================
:return: frequency
"""
if freq < 0.1:
self.__print__('freq too low')
return 0
elif freq < 1100:
HIGHRES = 1
table_size = 512
else:
HIGHRES = 0
table_size = 32
if waveType: # User wants to set a particular waveform type. sine or tria
if waveType in ['sine', 'tria']:
if (self.WType['SI1'] != waveType):
self.load_equation('SI1', waveType)
else:
print('Not a valid waveform. try sine or tria')
p = [1, 8, 64, 256]
prescaler = 0
while prescaler <= 3:
wavelength = int(round(64e6 / freq / p[prescaler] / table_size))
freq = (64e6 / wavelength / p[prescaler] / table_size)
if wavelength < 65525: break
prescaler += 1
if prescaler == 4:
self.__print__('out of range')
return 0
self.H.__sendByte__(CP.WAVEGEN)
self.H.__sendByte__(CP.SET_SINE1)
self.H.__sendByte__(HIGHRES | (prescaler << 1)) # use larger table for low frequencies
self.H.__sendInt__(wavelength - 1)
self.H.__get_ack__()
self.sine1freq = freq
return freq
def set_w2(self, freq, waveType=None):
"""
Set the frequency of wavegen 2
.. tabularcolumns:: |p{3cm}|p{11cm}|
============== ============================================================================================
**Arguments**
============== ============================================================================================
frequency Frequency to set on wave generator 1.
============== ============================================================================================
:return: frequency
"""
if freq < 0.1:
self.__print__('freq too low')
return 0
elif freq < 1100:
HIGHRES = 1
table_size = 512
else:
HIGHRES = 0
table_size = 32
if waveType: # User wants to set a particular waveform type. sine or tria
if waveType in ['sine', 'tria']:
if (self.WType['SI2'] != waveType):
self.load_equation('SI2', waveType)
else:
print('Not a valid waveform. try sine or tria')
p = [1, 8, 64, 256]
prescaler = 0
while prescaler <= 3:
wavelength = int(round(64e6 / freq / p[prescaler] / table_size))
freq = (64e6 / wavelength / p[prescaler] / table_size)
if wavelength < 65525: break
prescaler += 1
if prescaler == 4:
self.__print__('out of range')
return 0
self.H.__sendByte__(CP.WAVEGEN)
self.H.__sendByte__(CP.SET_SINE2)
self.H.__sendByte__(HIGHRES | (prescaler << 1)) # use larger table for low frequencies
self.H.__sendInt__(wavelength - 1)
self.H.__get_ack__()
self.sine2freq = freq
return freq
def readbackWaveform(self, chan):
"""
Set the frequency of wavegen 1
.. tabularcolumns:: |p{3cm}|p{11cm}|
============== ============================================================================================
**Arguments**
============== ============================================================================================
chan Any of SI1,SI2,SQR1,SQR2,SQR3,SQR4
============== ============================================================================================
:return: frequency
"""
if chan == 'SI1':
return self.sine1freq
elif chan == 'SI2':
return self.sine2freq
elif chan[:3] == 'SQR':
return self.sqrfreq.get(chan, None)
def set_waves(self, freq, phase, f2=None):
"""
Set the frequency of wavegen
.. tabularcolumns:: |p{3cm}|p{11cm}|
============== ============================================================================================
**Arguments**
============== ============================================================================================
frequency Frequency to set on both wave generators
phase Phase difference between the two. 0-360 degrees
f2 Only specify if you require two separate frequencies to be set
============== ============================================================================================
:return: frequency
"""
if f2:
freq2 = f2
else:
freq2 = freq
if freq < 0.1:
self.__print__('freq1 too low')
return 0
elif freq < 1100:
HIGHRES = 1
table_size = 512
else:
HIGHRES = 0
table_size = 32
if freq2 < 0.1:
self.__print__('freq2 too low')
return 0
elif freq2 < 1100:
HIGHRES2 = 1
table_size2 = 512
else:
HIGHRES2 = 0
table_size2 = 32
if freq < 1. or freq2 < 1.:
self.__print__('extremely low frequencies will have reduced amplitudes due to AC coupling restrictions')
p = [1, 8, 64, 256]
prescaler1 = 0
while prescaler1 <= 3:
wavelength = int(round(64e6 / freq / p[prescaler1] / table_size))
retfreq = (64e6 / wavelength / p[prescaler1] / table_size)
if wavelength < 65525: break
prescaler1 += 1
if prescaler1 == 4:
self.__print__('#1 out of range')
return 0
p = [1, 8, 64, 256]
prescaler2 = 0
while prescaler2 <= 3:
wavelength2 = int(round(64e6 / freq2 / p[prescaler2] / table_size2))
retfreq2 = (64e6 / wavelength2 / p[prescaler2] / table_size2)
if wavelength2 < 65525: break
prescaler2 += 1
if prescaler2 == 4:
self.__print__('#2 out of range')
return 0
phase_coarse = int(table_size2 * (phase) / 360.)
phase_fine = int(wavelength2 * (phase - (phase_coarse) * 360. / table_size2) / (360. / table_size2))
self.H.__sendByte__(CP.WAVEGEN)
self.H.__sendByte__(CP.SET_BOTH_WG)
self.H.__sendInt__(wavelength - 1) # not really wavelength. time between each datapoint
self.H.__sendInt__(wavelength2 - 1) # not really wavelength. time between each datapoint
self.H.__sendInt__(phase_coarse) # table position for phase adjust
self.H.__sendInt__(phase_fine) # timer delay / fine phase adjust
self.H.__sendByte__((prescaler2 << 4) | (prescaler1 << 2) | (HIGHRES2 << 1) | (
HIGHRES)) # use larger table for low frequencies
self.H.__get_ack__()
self.sine1freq = retfreq
self.sine2freq = retfreq2
return retfreq
def load_equation(self, chan, function, span=None, **kwargs):
'''
Load an arbitrary waveform to the waveform generators
.. tabularcolumns:: |p{3cm}|p{11cm}|
============== ============================================================================================
**Arguments**
============== ============================================================================================
chan The waveform generator to alter. SI1 or SI2
function A function that will be used to generate the datapoints
span the range of values in which to evaluate the given function
============== ============================================================================================
.. code-block:: python
fn = lambda x:abs(x-50) #Triangular waveform
self.I.load_waveform('SI1',fn,[0,100])
#Load triangular wave to wavegen 1
#Load sinusoidal wave to wavegen 2
self.I.load_waveform('SI2',np.sin,[0,2*np.pi])
'''
if function == 'sine' or function == np.sin:
function = np.sin
span = [0, 2 * np.pi]
self.WType[chan] = 'sine'
elif function == 'tria':
function = lambda x: abs(x % 4 - 2) - 1
span = [-1, 3]
self.WType[chan] = 'tria'
else:
self.WType[chan] = 'arbit'
self.__print__('reloaded wave equation for %s : %s' % (chan, self.WType[chan]))
x1 = np.linspace(span[0], span[1], 512 + 1)[:-1]
y1 = function(x1)
self.load_table(chan, y1, self.WType[chan], **kwargs)
def load_table(self, chan, points, mode='arbit', **kwargs):
'''
Load an arbitrary waveform table to the waveform generators
.. tabularcolumns:: |p{3cm}|p{11cm}|
============== ============================================================================================
**Arguments**
============== ============================================================================================