forked from fossasia/pslab-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPeripherals.py
More file actions
1546 lines (1301 loc) · 56.4 KB
/
Peripherals.py
File metadata and controls
1546 lines (1301 loc) · 56.4 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
from __future__ import print_function
from warnings import warn
import PSL.commands_proto as CP
import numpy as np
import time
class I2CMaster():
"""
Methods to handle slave independent functionality with the I2C port.
An instance of Labtools.Packet_Handler must be passed to the init function
"""
MAX_BRGVAL = 511
def __init__(self, H):
self.H = H
from PSL import sensorlist
self.SENSORS = sensorlist.sensors
def init(self):
self.H.__sendByte__(CP.I2C_HEADER)
self.H.__sendByte__(CP.I2C_INIT)
self.H.__get_ack__()
def enable_smbus(self):
self.H.__sendByte__(CP.I2C_HEADER)
self.H.__sendByte__(CP.I2C_ENABLE_SMBUS)
self.H.__get_ack__()
def pullSCLLow(self, uS):
"""
Hold SCL pin at 0V for a specified time period. Used by certain sensors such
as MLX90316 PIR for initializing.
.. tabularcolumns:: |p{3cm}|p{11cm}|
================ ============================================================================================
**Arguments**
================ ============================================================================================
uS Time(in uS) to hold SCL output at 0 Volts
================ ============================================================================================
"""
self.H.__sendByte__(CP.I2C_HEADER)
self.H.__sendByte__(CP.I2C_PULLDOWN_SCL)
self.H.__sendInt__(uS)
self.H.__get_ack__()
def config(self, freq, verbose=True):
"""
Sets frequency for I2C transactions
.. tabularcolumns:: |p{3cm}|p{11cm}|
================ ============================================================================================
**Arguments**
================ ============================================================================================
freq I2C frequency
================ ============================================================================================
"""
self.H.__sendByte__(CP.I2C_HEADER)
self.H.__sendByte__(CP.I2C_CONFIG)
# freq=1/((BRGVAL+1.0)/64e6+1.0/1e7)
BRGVAL = int((1. / freq - 1. / 1e7) * 64e6 - 1)
if BRGVAL > self.MAX_BRGVAL:
BRGVAL = self.MAX_BRGVAL
if verbose: print('Frequency too low. Setting to :', 1 / ((BRGVAL + 1.0) / 64e6 + 1.0 / 1e7))
self.H.__sendInt__(BRGVAL)
self.H.__get_ack__()
def scan(self, frequency=100000, verbose=False):
"""
Scan I2C port for connected devices
.. tabularcolumns:: |p{3cm}|p{11cm}|
================ ============================================================================================
**Arguments**
================ ============================================================================================
Frequency I2C clock frequency
================ ============================================================================================
:return: Array of addresses of connected I2C slave devices
"""
self.config(frequency, verbose)
addrs = []
n = 0
if verbose:
print('Scanning addresses 0-127...')
print('Address', '\t', 'Possible Devices')
for a in range(0, 128):
slave = I2CSlave(self.H, a)
x = slave.start(0)
if x & 1 == 0: # ACK received
addrs.append(a)
if verbose: print(hex(a), '\t\t', self.SENSORS.get(a, 'None'))
n += 1
slave.stop()
return addrs
class I2CSlave():
"""
Methods to handle slave with the I2C port.
An instance of Labtools.Packet_Handler and slave address must be passed to the init function
"""
samples = 0
total_bytes = 0
channels = 0
tg = 100
MAX_SAMPLES = 10000
def __init__(self, H, address):
self.H = H
self.address = address
self.buff = np.zeros(10000)
def start(self, rw):
"""
Initiates I2C transfer to address via the I2C port
.. tabularcolumns:: |p{3cm}|p{11cm}|
================ ============================================================================================
**Arguments**
================ ============================================================================================
rw Read/write.
- 0 for writing
- 1 for reading.
================ ============================================================================================
"""
self.H.__sendByte__(CP.I2C_HEADER)
self.H.__sendByte__(CP.I2C_START)
self.H.__sendByte__(((self.address << 1) | rw) & 0xFF) # address
return self.H.__get_ack__() >> 4
def stop(self):
"""
stops I2C transfer
:return: Nothing
"""
self.H.__sendByte__(CP.I2C_HEADER)
self.H.__sendByte__(CP.I2C_STOP)
self.H.__get_ack__()
def wait(self):
"""
wait for I2C
:return: Nothing
"""
self.H.__sendByte__(CP.I2C_HEADER)
self.H.__sendByte__(CP.I2C_WAIT)
self.H.__get_ack__()
def send(self, data):
"""
SENDS data over I2C.
The I2C bus needs to be initialized and set to the correct slave address first.
Use I2C.start(address) for this.
.. tabularcolumns:: |p{3cm}|p{11cm}|
================ ============================================================================================
**Arguments**
================ ============================================================================================
data Sends data byte over I2C bus
================ ============================================================================================
:return: Nothing
"""
self.H.__sendByte__(CP.I2C_HEADER)
self.H.__sendByte__(CP.I2C_SEND)
self.H.__sendByte__(data) # data byte
return self.H.__get_ack__() >> 4
def send_burst(self, data):
"""
SENDS data over I2C. The function does not wait for the I2C to finish before returning.
It is used for sending large packets quickly.
The I2C bus needs to be initialized and set to the correct slave address first.
Use start(address) for this.
.. tabularcolumns:: |p{3cm}|p{11cm}|
================ ============================================================================================
**Arguments**
================ ============================================================================================
data Sends data byte over I2C bus
================ ============================================================================================
:return: Nothing
"""
self.H.__sendByte__(CP.I2C_HEADER)
self.H.__sendByte__(CP.I2C_SEND_BURST)
self.H.__sendByte__(data) # data byte
# No handshake. for the sake of speed. e.g. loading a frame buffer onto an I2C display such as ssd1306
def restart(self, rw):
"""
Initiates I2C transfer to address
.. tabularcolumns:: |p{3cm}|p{11cm}|
================ ============================================================================================
**Arguments**
================ ============================================================================================
rw Read/write.
* 0 for writing
* 1 for reading.
================ ============================================================================================
"""
self.H.__sendByte__(CP.I2C_HEADER)
self.H.__sendByte__(CP.I2C_RESTART)
self.H.__sendByte__(((self.address << 1) | rw) & 0xFF) # address
return self.H.__get_ack__() >> 4
def read(self, length):
"""
Reads a fixed number of data bytes from I2C device. Fetches length-1 bytes with acknowledge bits for each, +1 byte
with Nack.
.. tabularcolumns:: |p{3cm}|p{11cm}|
================ ============================================================================================
**Arguments**
================ ============================================================================================
length number of bytes to read from I2C bus
================ ============================================================================================
"""
data = []
for _ in range(length - 1):
self.H.__sendByte__(CP.I2C_HEADER)
self.H.__sendByte__(CP.I2C_READ_MORE)
data.append(self.H.__getByte__())
self.H.__get_ack__()
self.H.__sendByte__(CP.I2C_HEADER)
self.H.__sendByte__(CP.I2C_READ_END)
data.append(self.H.__getByte__())
self.H.__get_ack__()
return data
def read_repeat(self):
self.H.__sendByte__(CP.I2C_HEADER)
self.H.__sendByte__(CP.I2C_READ_MORE)
val = self.H.__getByte__()
self.H.__get_ack__()
return val
def read_end(self):
self.H.__sendByte__(CP.I2C_HEADER)
self.H.__sendByte__(CP.I2C_READ_END)
val = self.H.__getByte__()
self.H.__get_ack__()
return val
def read_status(self):
self.H.__sendByte__(CP.I2C_HEADER)
self.H.__sendByte__(CP.I2C_STATUS)
val = self.H.__getInt__()
self.H.__get_ack__()
return val
def simple_read(self, numbytes):
"""
Read bytes from I2C slave without first transmitting the read location.
.. tabularcolumns:: |p{3cm}|p{11cm}|
================ ============================================================================================
**Arguments**
================ ============================================================================================
numbytes Total Bytes to read
================ ============================================================================================
"""
self.start(1)
vals = self.read(numbytes)
return vals
def simple_read_byte(self):
vals = self.simple_read(1)
return vals[0]
def simple_read_int(self):
vals = self.simple_read(2)
bytes_ = bytearray(vals)
return CP.ShortInt.unpack(bytes_)[0]
def simple_read_long(self):
vals = self.simple_read(4)
bytes_ = bytearray(vals)
return CP.Integer.unpack(bytes_)[0]
def read_bulk(self, register_address, bytes_to_read):
self.H.__sendByte__(CP.I2C_HEADER)
self.H.__sendByte__(CP.I2C_READ_BULK)
self.H.__sendByte__(self.address)
self.H.__sendByte__(register_address)
self.H.__sendByte__(bytes_to_read)
data = self.H.interface.read(bytes_to_read)
self.H.__get_ack__()
try:
return list(data)
except:
print('Transaction failed')
return False
def read_bulk_byte(self, register_address):
data = self.read_bulk(register_address, 1)
if data:
return data[0]
def read_bulk_int(self, register_address):
data = self.read_bulk(register_address, 2)
if data:
bytes_ = bytearray(data)
return CP.ShortInt.unpack(bytes_)[0]
def read_bulk_long(self, register_address):
data = self.read_bulk(register_address, 4)
if data:
bytes_ = bytearray(data)
return CP.Integer.unpack(bytes_)[0]
def write_bulk(self, bytestream):
"""
write bytes to I2C slave
.. tabularcolumns:: |p{3cm}|p{11cm}|
================ ============================================================================================
**Arguments**
================ ============================================================================================
bytestream List of bytes to write
================ ============================================================================================
"""
self.H.__sendByte__(CP.I2C_HEADER)
self.H.__sendByte__(CP.I2C_WRITE_BULK)
self.H.__sendByte__(self.address)
self.H.__sendByte__(len(bytestream))
for a in bytestream:
self.H.__sendByte__(a)
self.H.__get_ack__()
def __captureStart__(self, location, sample_length, total_samples, tg):
"""
Blocking call that starts fetching data from I2C sensors like an oscilloscope fetches voltage readings
You will then have to call `__retrievebuffer__` to fetch this data, and `__dataProcessor` to process and return separate channels
refer to `capture` if you want a one-stop solution.
.. tabularcolumns:: |p{3cm}|p{11cm}|
================== ============================================================================================
**Arguments**
================== ============================================================================================
location Address of the register to read from
sample_length Each sample can be made up of multiple bytes startng from <location> . such as 3-axis data
total_samples Total samples to acquire. Total bytes fetched = total_samples*sample_length
tg timegap between samples (in uS)
================== ============================================================================================
:return: Arrays X(timestamps),Y1,Y2 ...
"""
if (tg < 20): tg = 20
total_bytes = total_samples * sample_length
print('total bytes calculated : ', total_bytes)
if (total_bytes > self.MAX_SAMPLES * 2):
print('Sample limit exceeded. 10,000 int / 20000 bytes total')
total_bytes = self.MAX_SAMPLES * 2
total_samples = total_bytes / sample_length # 2* because sample array is in Integers, and we're using it to store bytes
print('length of each channel : ', sample_length)
self.total_bytes = total_bytes
self.channels = sample_length
self.samples = total_samples
self.tg = tg
self.H.__sendByte__(CP.I2C_HEADER)
self.H.__sendByte__(CP.I2C_START_SCOPE)
self.H.__sendByte__(self.address)
self.H.__sendByte__(location)
self.H.__sendByte__(sample_length)
self.H.__sendInt__(total_samples) # total number of samples to record
self.H.__sendInt__(tg) # Timegap between samples. 1MHz timer clock
self.H.__get_ack__()
return 1e-6 * self.samples * self.tg + .01
def __retrievebuffer__(self):
'''
Fetch data acquired by the I2C scope. refer to :func:`__captureStart__`
'''
total_int_samples = self.total_bytes // 2
DATA_SPLITTING = 500
print('fetchin samples : ', total_int_samples, ' split', DATA_SPLITTING)
data = b''
for i in range(int(total_int_samples / DATA_SPLITTING)):
self.H.__sendByte__(CP.ADC)
self.H.__sendByte__(CP.GET_CAPTURE_CHANNEL)
self.H.__sendByte__(0) # starts with A0 on PIC
self.H.__sendInt__(DATA_SPLITTING)
self.H.__sendInt__(i * DATA_SPLITTING)
rem = DATA_SPLITTING * 2 + 1
for _ in range(200):
partial = self.H.interface.read(
rem) # reading int by int sometimes causes a communication error. this works better.
rem -= len(partial)
data += partial
# print ('partial: ',len(partial), end=",")
if rem <= 0:
break
data = data[:-1]
# print ('Pass : len=',len(data), ' i = ',i)
if total_int_samples % DATA_SPLITTING:
self.H.__sendByte__(CP.ADC)
self.H.__sendByte__(CP.GET_CAPTURE_CHANNEL)
self.H.__sendByte__(0) # starts with A0 on PIC
self.H.__sendInt__(total_int_samples % DATA_SPLITTING)
self.H.__sendInt__(total_int_samples - total_int_samples % DATA_SPLITTING)
rem = 2 * (total_int_samples % DATA_SPLITTING) + 1
for _ in range(20):
partial = self.H.interface.read(
rem) # reading int by int sometimes causes a communication error. this works better.
rem -= len(partial)
data += partial
# print ('partial: ',len(partial), end="")
if rem <= 0:
break
data = data[:-1]
print('Final Pass : len=', len(data))
return data
def __dataProcessor__(self, data, *args):
'''
Interpret data acquired by the I2C scope. refer to :func:`__retrievebuffer__` to fetch data
================== ============================================================================================
**Arguments**
================== ============================================================================================
data byte array returned by :func:`__retrievebuffer__`
*args supply optional argument 'int' if consecutive bytes must be combined to form short integers
================== ============================================================================================
'''
data = [ord(a) for a in data]
if ('int' in args):
for a in range(self.channels * self.samples / 2): self.buff[a] = np.int16(
(data[a * 2] << 8) | data[a * 2 + 1])
else:
for a in range(self.channels * self.samples): self.buff[a] = data[a]
yield np.linspace(0, self.tg * (self.samples - 1), self.samples)
for a in range(int(self.channels / 2)):
yield self.buff[a:self.samples * self.channels / 2][::self.channels / 2]
def capture(self, location, sample_length, total_samples, tg, *args):
"""
Blocking call that fetches data from I2C sensors like an oscilloscope fetches voltage readings
.. tabularcolumns:: |p{3cm}|p{11cm}|
================== ============================================================================================
**Arguments**
================== ============================================================================================
location Address of the register to read from
sample_length Each sample can be made up of multiple bytes startng from <location> . such as 3-axis data
total_samples Total samples to acquire. Total bytes fetched = total_samples*sample_length
tg timegap between samples (in uS)
================== ============================================================================================
Example
>>> from pylab import *
>>> I=sciencelab.ScienceLab()
>>> x,y1,y2,y3,y4 = I.capture_multiple(800,1.75,'CH1','CH2','MIC','RES')
>>> plot(x,y1)
>>> plot(x,y2)
>>> plot(x,y3)
>>> plot(x,y4)
>>> show()
:return: Arrays X(timestamps),Y1,Y2 ...
"""
t = self.__captureStart__(location, sample_length, total_samples, tg)
time.sleep(t)
data = self.__retrievebuffer__()
return self.__dataProcessor__(data, *args)
class I2C(I2CMaster, I2CSlave): # for backwards compatibility
"""
Methods to interact with the I2C port. An instance of Labtools.Packet_Handler must be passed to the init function
Example:: Read Values from an HMC5883L 3-axis Magnetometer(compass) [GY-273 sensor] connected to the I2C port
>>> ADDRESS = 0x1E
>>> from PSL import sciencelab
>>> I = sciencelab.connect()
#Alternately, you may skip using I2C as a child instance of Interface,
#and instead use I2C=PSL.Peripherals.I2C(PSL.packet_handler.Handler())
# writing to 0x1E, set gain(0x01) to smallest(0 : 1x)
>>> I.I2C.writeBulk(ADDRESS,[0x01,0])
# writing to 0x1E, set mode conf(0x02), continuous measurement(0)
>>> I.I2C.writeBulk(ADDRESS,[0x02,0])
# read 6 bytes from addr register on I2C device located at ADDRESS
>>> vals = I.I2C.readBulk(ADDRESS,addr,6)
>>> from numpy import int16
#conversion to signed datatype
>>> x=int16((vals[0]<<8)|vals[1])
>>> y=int16((vals[2]<<8)|vals[3])
>>> z=int16((vals[4]<<8)|vals[5])
>>> print (x,y,z)
"""
def __init__(self, H):
I2CMaster.__init__(self, H)
I2CSlave.__init__(self, H, None)
warn('I2C is deprecated; use I2CMaster and I2CSlave', DeprecationWarning)
def start(self, address, rw): # pylint: disable=arguments-differ
self.address = address
return super().start(rw)
def restart(self, address, rw): # pylint: disable=arguments-differ
self.address = address
return super().restart(rw)
def simpleRead(self, address, numbytes): # pylint: disable=arguments-differ
self.address = address
return super().simple_read(numbytes)
def simple_read_byte(self, address): # pylint: disable=arguments-differ
self.address = address
return super().simple_read_byte()
def simple_read_int(self, address): # pylint: disable=arguments-differ
self.address = address
return super().simple_read_int()
def simple_read_long(self, address): # pylint: disable=arguments-differ
self.address = address
return super().simple_read_long()
def readBulk(self, device_address, register_address, bytes_to_read): # pylint: disable=arguments-differ
self.address = device_address
return super().read_bulk(register_address, bytes_to_read)
def read_bulk_byte(self, device_address, register_address): # pylint: disable=arguments-differ
self.address = device_address
return super().read_bulk_byte(register_address)
def read_bulk_int(self, device_address, register_address): # pylint: disable=arguments-differ
self.address = device_address
return super().read_bulk_int(register_address)
def read_bulk_long(self, device_address, register_address): # pylint: disable=arguments-differ
self.address = device_address
return super().read_bulk_long(register_address)
def writeBulk(self, device_address, bytestream): # pylint: disable=arguments-differ
self.address = device_address
return super().write_bulk(bytestream)
def __captureStart__(self, address, location, sample_length, total_samples, tg): # pylint: disable=arguments-differ
self.address = address
return super().__captureStart__(location, sample_length, total_samples, tg)
def capture(self, address, location, sample_length, total_samples, tg, *args): # pylint: disable=arguments-differ
self.address = address
return super().capture(location, sample_length, total_samples, tg, *args)
class SPI():
"""
Methods to interact with the SPI port. An instance of Packet_Handler must be passed to the init function
"""
def __init__(self, H):
self.H = H
def set_parameters(self, primary_prescaler=0, secondary_prescaler=2, CKE=1, CKP=0, SMP=1):
"""
sets SPI parameters.
.. tabularcolumns:: |p{3cm}|p{11cm}|
================ ============================================================================================
**Arguments**
================ ============================================================================================
primary_pres Primary Prescaler(0,1,2,3) for 64MHz clock->(64:1,16:1,4:1,1:1)
secondary_pres Secondary prescaler(0,1,..7)->(8:1,7:1,..1:1)
CKE CKE 0 or 1.
CKP CKP 0 or 1.
================ ============================================================================================
"""
self.H.__sendByte__(CP.SPI_HEADER)
self.H.__sendByte__(CP.SET_SPI_PARAMETERS)
# 0Bhgfedcba - > <g>: modebit CKP,<f>: modebit CKE, <ed>:primary pre,<cba>:secondary pre
self.H.__sendByte__(secondary_prescaler | (primary_prescaler << 3) | (CKE << 5) | (CKP << 6) | (SMP << 7))
self.H.__get_ack__()
def start(self, channel):
"""
selects SPI channel to enable.
Basically lowers the relevant chip select pin .
.. tabularcolumns:: |p{3cm}|p{11cm}|
================ ============================================================================================
**Arguments**
================ ============================================================================================
channel 1-7 ->[PGA1 connected to CH1,PGA2,PGA3,PGA4,PGA5,external chip select 1,external chip select 2]
8 -> sine1
9 -> sine2
================ ============================================================================================
"""
self.H.__sendByte__(CP.SPI_HEADER)
self.H.__sendByte__(CP.START_SPI)
self.H.__sendByte__(channel) # value byte
# self.H.__get_ack__()
def set_cs(self, channel, state):
"""
Enable or disable a chip select
.. tabularcolumns:: |p{3cm}|p{11cm}|
================ ============================================================================================
**Arguments**
================ ============================================================================================
channel 'CS1','CS2'
state 1 for HIGH, 0 for LOW
================ ============================================================================================
"""
channel = channel.upper()
if channel in ['CS1', 'CS2']:
csnum = ['CS1', 'CS2'].index(channel) + 9 # chip select number 9=CSOUT1,10=CSOUT2
self.H.__sendByte__(CP.SPI_HEADER)
if state:
self.H.__sendByte__(CP.STOP_SPI)
else:
self.H.__sendByte__(CP.START_SPI)
self.H.__sendByte__(csnum)
else:
print('Channel does not exist')
def stop(self, channel):
"""
selects SPI channel to disable.
Sets the relevant chip select pin to HIGH.
.. tabularcolumns:: |p{3cm}|p{11cm}|
================ ============================================================================================
**Arguments**
================ ============================================================================================
channel 1-7 ->[PGA1 connected to CH1,PGA2,PGA3,PGA4,PGA5,external chip select 1,external chip select 2]
================ ============================================================================================
"""
self.H.__sendByte__(CP.SPI_HEADER)
self.H.__sendByte__(CP.STOP_SPI)
self.H.__sendByte__(channel) # value byte
# self.H.__get_ack__()
def send8(self, value):
"""
SENDS 8-bit data over SPI
.. tabularcolumns:: |p{3cm}|p{11cm}|
================ ============================================================================================
**Arguments**
================ ============================================================================================
value value to transmit
================ ============================================================================================
:return: value returned by slave device
"""
self.H.__sendByte__(CP.SPI_HEADER)
self.H.__sendByte__(CP.SEND_SPI8)
self.H.__sendByte__(value) # value byte
v = self.H.__getByte__()
self.H.__get_ack__()
return v
def send16(self, value):
"""
SENDS 16-bit data over SPI
.. tabularcolumns:: |p{3cm}|p{11cm}|
================ ============================================================================================
**Arguments**
================ ============================================================================================
value value to transmit
================ ============================================================================================
:return: value returned by slave device
:rtype: int
"""
self.H.__sendByte__(CP.SPI_HEADER)
self.H.__sendByte__(CP.SEND_SPI16)
self.H.__sendInt__(value) # value byte
v = self.H.__getInt__()
self.H.__get_ack__()
return v
def send8_burst(self, value):
"""
SENDS 8-bit data over SPI
No acknowledge/return value
.. tabularcolumns:: |p{3cm}|p{11cm}|
================ ============================================================================================
**Arguments**
================ ============================================================================================
value value to transmit
================ ============================================================================================
:return: Nothing
"""
self.H.__sendByte__(CP.SPI_HEADER)
self.H.__sendByte__(CP.SEND_SPI8_BURST)
self.H.__sendByte__(value) # value byte
def send16_burst(self, value):
"""
SENDS 16-bit data over SPI
no acknowledge/return value
.. tabularcolumns:: |p{3cm}|p{11cm}|
============== ============================================================================================
**Arguments**
============== ============================================================================================
value value to transmit
============== ============================================================================================
:return: nothing
"""
self.H.__sendByte__(CP.SPI_HEADER)
self.H.__sendByte__(CP.SEND_SPI16_BURST)
self.H.__sendInt__(value) # value byte
def xfer(self, chan, data):
self.start(chan)
reply = []
for a in data:
reply.append(self.send8(a))
self.stop(chan)
return reply
class DACCHAN:
def __init__(self, name, span, channum, **kwargs):
self.name = name
self.channum = channum
self.VREF = kwargs.get('VREF', 0)
self.SwitchedOff = kwargs.get('STATE', 0)
self.range = span
slope = (span[1] - span[0])
intercept = span[0]
self.VToCode = np.poly1d([4095. / slope, -4095. * intercept / slope])
self.CodeToV = np.poly1d([slope / 4095., intercept])
self.calibration_enabled = False
self.calibration_table = []
self.slope = 1
self.offset = 0
def load_calibration_table(self, table):
self.calibration_enabled = 'table'
self.calibration_table = table
def load_calibration_twopoint(self, slope, offset):
self.calibration_enabled = 'twopoint'
self.slope = slope
self.offset = offset
# print('########################',slope,offset)
def apply_calibration(self, v):
if self.calibration_enabled == 'table': # Each point is individually calibrated
return int(np.clip(v + self.calibration_table[v], 0, 4095))
elif self.calibration_enabled == 'twopoint': # Overall slope and offset correction is applied
# print (self.slope,self.offset,v)
return int(np.clip(v * self.slope + self.offset, 0, 4095))
else:
return v
class MCP4728:
defaultVDD = 3300
RESET = 6
WAKEUP = 9
UPDATE = 8
WRITEALL = 64
WRITEONE = 88
SEQWRITE = 80
VREFWRITE = 128
GAINWRITE = 192
POWERDOWNWRITE = 160
GENERALCALL = 0
# def __init__(self,I2C,vref=3.3,devid=0):
def __init__(self, H, vref=3.3, devid=0):
self.devid = devid
self.addr = 0x60 | self.devid # 0x60 is the base address
self.H = H
self.I2C = I2C(self.H)
self.SWITCHEDOFF = [0, 0, 0, 0]
self.VREFS = [0, 0, 0, 0] # 0=Vdd,1=Internal reference
self.CHANS = {'PCS': DACCHAN('PCS', [0, 3.3e-3], 0), 'PV3': DACCHAN('PV3', [0, 3.3], 1),
'PV2': DACCHAN('PV2', [-3.3, 3.3], 2), 'PV1': DACCHAN('PV1', [-5., 5.], 3)}
self.CHANNEL_MAP = {0: 'PCS', 1: 'PV3', 2: 'PV2', 3: 'PV1'}
self.values = {'PV1': 0, 'PV2': 0, 'PV3': 0, 'PCS': 0}
def __ignoreCalibration__(self, name):
self.CHANS[name].calibration_enabled = False
def setVoltage(self, name, v):
chan = self.CHANS[name]
v = int(round(chan.VToCode(v)))
return self.__setRawVoltage__(name, v)
def getVoltage(self, name):
return self.values[name]
def setCurrent(self, v):
chan = self.CHANS['PCS']
v = int(round(chan.VToCode(v)))
return self.__setRawVoltage__('PCS', v)
def __setRawVoltage__(self, name, v):
v = int(np.clip(v, 0, 4095))
CHAN = self.CHANS[name]
'''
self.H.__sendByte__(CP.DAC) #DAC write coming through.(MCP4728)
self.H.__sendByte__(CP.SET_DAC)
self.H.__sendByte__(self.addr<<1) #I2C address
self.H.__sendByte__(CHAN.channum) #DAC channel
if self.calibration_enabled[name]:
val = v+self.calibration_tables[name][v]
#print (val,v,self.calibration_tables[name][v])
self.H.__sendInt__((CHAN.VREF << 15) | (CHAN.SwitchedOff << 13) | (0 << 12) | (val) )
else:
self.H.__sendInt__((CHAN.VREF << 15) | (CHAN.SwitchedOff << 13) | (0 << 12) | v )
self.H.__get_ack__()
'''
val = self.CHANS[name].apply_calibration(v)
self.I2C.writeBulk(self.addr, [64 | (CHAN.channum << 1), (val >> 8) & 0x0F, val & 0xFF])
self.values[name] = CHAN.CodeToV(v)
return self.values[name]
def __writeall__(self, v1, v2, v3, v4):
self.I2C.start(self.addr, 0)
self.I2C.send((v1 >> 8) & 0xF)
self.I2C.send(v1 & 0xFF)
self.I2C.send((v2 >> 8) & 0xF)
self.I2C.send(v2 & 0xFF)
self.I2C.send((v3 >> 8) & 0xF)
self.I2C.send(v3 & 0xFF)
self.I2C.send((v4 >> 8) & 0xF)
self.I2C.send(v4 & 0xFF)
self.I2C.stop()
def stat(self):
self.I2C.start(self.addr, 0)
self.I2C.send(0x0) # read raw values starting from address
self.I2C.restart(self.addr, 1)
vals = self.I2C.read(24)
self.I2C.stop()
print(vals)
class NRF24L01():
# Commands
R_REG = 0x00
W_REG = 0x20
RX_PAYLOAD = 0x61
TX_PAYLOAD = 0xA0
ACK_PAYLOAD = 0xA8
FLUSH_TX = 0xE1
FLUSH_RX = 0xE2
ACTIVATE = 0x50
R_STATUS = 0xFF
# Registers
NRF_CONFIG = 0x00
EN_AA = 0x01
EN_RXADDR = 0x02
SETUP_AW = 0x03
SETUP_RETR = 0x04
RF_CH = 0x05
RF_SETUP = 0x06
NRF_STATUS = 0x07
OBSERVE_TX = 0x08
CD = 0x09
RX_ADDR_P0 = 0x0A
RX_ADDR_P1 = 0x0B
RX_ADDR_P2 = 0x0C
RX_ADDR_P3 = 0x0D
RX_ADDR_P4 = 0x0E
RX_ADDR_P5 = 0x0F
TX_ADDR = 0x10
RX_PW_P0 = 0x11
RX_PW_P1 = 0x12
RX_PW_P2 = 0x13
RX_PW_P3 = 0x14
RX_PW_P4 = 0x15
RX_PW_P5 = 0x16
R_RX_PL_WID = 0x60
FIFO_STATUS = 0x17
DYNPD = 0x1C
FEATURE = 0x1D
PAYLOAD_SIZE = 0
ACK_PAYLOAD_SIZE = 0
READ_PAYLOAD_SIZE = 0
ADC_COMMANDS = 1
READ_ADC = 0 << 4
I2C_COMMANDS = 2
I2C_TRANSACTION = 0 << 4
I2C_WRITE = 1 << 4
I2C_SCAN = 2 << 4
PULL_SCL_LOW = 3 << 4
I2C_CONFIG = 4 << 4
I2C_READ = 5 << 4
NRF_COMMANDS = 3
NRF_READ_REGISTER = 0
NRF_WRITE_REGISTER = 1 << 4
CURRENT_ADDRESS = 0xAAAA01
nodelist = {}
nodepos = 0
NODELIST_MAXLENGTH = 15
connected = False
def __init__(self, H):
self.H = H
self.ready = False
self.sigs = {self.CURRENT_ADDRESS: 1}
if self.H.connected:
self.connected = self.init()
"""
routines for the NRFL01 radio
"""
def init(self):
self.H.__sendByte__(CP.NRFL01)
self.H.__sendByte__(CP.NRF_SETUP)
self.H.__get_ack__()
time.sleep(0.015) # 15 mS settling time
stat = self.get_status()
if stat & 0x80:
print("Radio transceiver not installed/not found")
return False
else:
self.ready = True
self.selectAddress(self.CURRENT_ADDRESS)
# self.write_register(self.RF_SETUP,0x06)
self.rxmode()
time.sleep(0.1)
self.flush()
return True
def rxmode(self):
'''
Puts the radio into listening mode.
'''
self.H.__sendByte__(CP.NRFL01)
self.H.__sendByte__(CP.NRF_RXMODE)
self.H.__get_ack__()
def txmode(self):
'''
Puts the radio into transmit mode.
'''
self.H.__sendByte__(CP.NRFL01)