-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcaravel.py
1486 lines (1281 loc) · 49.1 KB
/
caravel.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
import datetime
from multiprocessing.sharedctypes import Value
import pyvisa
from WF_SDK import * # import instruments
from WF_SDK.dmm import *
from power_supply import PowerSupply
import time
import subprocess
import sys
from ctypes import *
import logging
import os
import math
from rich.console import Console
from rich.progress import (
Progress,
TextColumn,
BarColumn,
MofNCompleteColumn,
TimeElapsedColumn,
)
import pyvisa
# import flash
def accurate_delay(delay):
"""Function to provide accurate time delay in millisecond"""
_ = time.perf_counter() + delay / 1000
while time.perf_counter() < _:
pass
class Test:
def __init__(
self,
device1v8,
device3v3,
deviced=None,
test_name=None,
passing_criteria=[],
l_voltage=1.8,
h_voltage=3.3,
sram=1,
):
self.device1v8 = device1v8
self.device3v3 = device3v3
self.deviced = deviced
self.rstb = self.device1v8.dio_map["rstb"]
self.gpio_mgmt = self.device1v8.dio_map["gpio_mgmt"]
self.test_name = test_name
self.l_voltage = l_voltage
self.h_voltage = h_voltage
self.sram = sram
self.passing_criteria = passing_criteria
self.task = None
self.console = Console()
self.progress = Progress(
TextColumn("[progress.description]{task.description}"),
BarColumn(),
MofNCompleteColumn(),
TimeElapsedColumn(),
console=self.console,
)
self.runs_dir = os.path.join(os.getcwd(), "runs")
self.date_dir = os.path.join(self.runs_dir, datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S"))
self.log_file = f"{self.date_dir}/terminal_output.log"
def log_to_file(self, message):
if self.log_file:
self.log_file = f"{self.date_dir}/terminal_output.log"
logging.basicConfig(filename=self.log_file, level=logging.INFO, format='%(asctime)s - %(message)s')
logging.info(message)
def print_and_log(self, message):
self.console.print(message)
self.log_to_file(message)
def make_runs_dirs(self):
os.makedirs(self.runs_dir, exist_ok=True)
os.makedirs(self.date_dir, exist_ok=True)
def receive_packet(self, pulse_width=25):
"""recieves packet using the wire protocol, uses the gpio_mgmt I/O
Returns:
int: pulse count
"""
ones = 0
pulses = 0
self.gpio_mgmt.set_state(False)
timeout = time.time() + 50
while self.gpio_mgmt.get_value() != False:
if time.time() > timeout:
self.console.print("Timeout!")
self.progress.stop()
self.close_devices()
os._exit(1)
state = "LOW"
accurate_delay(pulse_width / 2.0)
for i in range(0, 30):
accurate_delay(pulse_width)
x = self.gpio_mgmt.get_value()
if state == "LOW":
if x:
state = "HI"
elif state == "HI":
if not x:
state = "LOW"
ones = 0
pulses = pulses + 1
if x:
ones = ones + 1
if ones > 3:
break
# test.console.print("A packet has been received!")
return pulses
def send_packet(self, num_pulses, pulse_width=25):
num_pulses = num_pulses + 1
self.gpio_mgmt.set_state(True)
self.gpio_mgmt.set_value(1)
time.sleep(5)
for i in range(0, num_pulses):
self.gpio_mgmt.set_value(0)
accurate_delay(pulse_width)
self.gpio_mgmt.set_value(1)
accurate_delay(pulse_width)
def send_pulse(self, num_pulses, channel, pulse_width=25):
if channel < 14:
channel = self.device1v8.dio_map[channel]
elif channel > 21:
channel = self.device3v3.dio_map[channel]
elif self.deviced:
channel = self.deviced.dio_map[channel]
channel.set_state(True)
channel.set_value(1)
num_pulses = num_pulses + 1
accurate_delay(25)
for i in range(0, num_pulses):
channel.set_value(0)
accurate_delay(pulse_width)
channel.set_value(1)
accurate_delay(pulse_width)
def reset(self, duration=0.1):
"""applies reset to the caravel board
Args:
duration (int, optional): duration of reset. Defaults to 1.
"""
# logging.info(" applying reset on channel 0 device 1")
# self.rstb.set_value(0)
self.apply_reset()
time.sleep(duration)
# self.rstb.set_value(1)
self.release_reset()
time.sleep(duration)
# logging.info(" reset done")
def apply_reset(self):
"""applies reset to the caravel board
Args:
duration (int, optional): duration of reset. Defaults to 1.
"""
# logging.info(" applying reset on channel 0 device 1")
self.rstb.set_state(True)
self.rstb.set_value(0)
def release_reset(self):
"""applies reset to the caravel board
Args:
duration (int, optional): duration of reset. Defaults to 1.
"""
# logging.info(" releasing reset on channel 0 device 1")
self.rstb.set_state(False)
# self.rstb.set_value(1)
def flash(self, hex_file):
"""flashes the caravel board with hex file,
uses silicon_tests/util/caravel_hkflash.py script
Args:
hex_file (string): path to hex file
"""
with open(f"{self.date_dir}/flash.log", "a") as f:
f.write("==============================================")
f.write(f" Flashed {self.test_name}")
f.write(" ==============================================\n")
sp = subprocess.run(
f"python3 caravel_hkflash.py {hex_file}",
cwd="./silicon_tests/util/",
shell=True,
stdout=f,
stderr=subprocess.PIPE,
universal_newlines=True,
)
ret_code = sp.returncode
if ret_code != 0:
self.console.print("[red]Can't flash!")
self.close_devices()
sys.exit(1)
# flash.erase()
# if flash.flash(hex_file):
# logging.error("Can't flash!")
# self.close_devices()
# sys.exit()
def change_voltage(self):
"""
changes voltage output of the device connected to `VCORE` power supply
"""
self.device1v8.supply.set_voltage(self.voltage)
def exec_flashing(self):
"""
Automates flashing based on sram of DFFRAM, and test name
"""
logging.info(" Flashing CPU")
self.apply_reset()
self.powerup_sequence()
if self.sram == 1:
self.flash(f"silicon_tests/{self.test_name}/{self.test_name}_sram.hex")
else:
self.flash(f"silicon_tests/{self.test_name}/{self.test_name}_dff.hex")
self.release_reset()
self.powerup_sequence()
logging.info(f" changing VCORE voltage to {self.l_voltage}v")
self.device1v8.supply.set_voltage(self.l_voltage)
self.reset()
def powerup_sequence(self):
"""
Power supply powerup sequence:
turns off both devices
turns on device and change voltage to the required one
"""
self.device1v8.supply.turn_off()
self.device3v3.supply.turn_off()
time.sleep(5)
# logging.info(" Turning on VIO with 3.3v")
self.device3v3.supply.set_voltage(self.h_voltage)
time.sleep(1)
# logging.info(f" Turning on VCORE with {self.voltage}v")
self.device1v8.supply.set_voltage(self.l_voltage)
time.sleep(1)
def power_down(self):
"""
Power supply powerup sequence:
turns off both devices
turns on device and change voltage to the required one
"""
rm = pyvisa.ResourceManager("@py")
usb_devices = [
resource for resource in rm.list_resources() if "SPD" in resource
]
if usb_devices:
# Use the first USB device found with 'SPD' in its name
resource_name = usb_devices[0]
inst = rm.open_resource(resource_name)
inst.query_delay = 0.1
inst.write("OUTP CH1, OFF")
time.sleep(0.1)
inst.write("OUTP CH2, OFF")
time.sleep(0.1)
rm.close()
else:
self.device1v8.supply.turn_off()
self.device3v3.supply.turn_off()
time.sleep(0.1)
def power_up(self):
"""
Power supply powerup sequence:
turns off both devices
turns on device and change voltage to the required one
"""
rm = pyvisa.ResourceManager("@py")
usb_devices = [
resource for resource in rm.list_resources() if "SPD" in resource
]
if usb_devices:
# Use the first USB device found with 'SPD' in its name
resource_name = usb_devices[0]
inst = rm.open_resource(resource_name)
inst.query_delay = 0.1
inst.write(f"CH1:VOLT {self.l_voltage}")
time.sleep(0.1)
inst.write("OUTP CH1, ON")
time.sleep(0.1)
inst.write(f"CH2:VOLT {self.h_voltage}")
time.sleep(0.1)
inst.write("OUTP CH2, ON")
time.sleep(0.8)
l_volt = float(inst.query('MEAsure:VOLTage? CH1'))
h_volt = float(inst.query('MEAsure:VOLTage? CH2'))
l_volt_expected = self.l_voltage
h_volt_expected = self.h_voltage
error_tolerance = 0.1
if not math.isclose(l_volt, l_volt_expected, abs_tol=error_tolerance) or not math.isclose(h_volt, h_volt_expected, abs_tol=error_tolerance):
Console.print(f"[red]Error: {resource_name} not within 0.1V of expected voltages")
self.turn_off_devices()
exit()
rm.close()
else:
self.device3v3.supply.set_voltage(self.h_voltage)
time.sleep(0.01)
self.device1v8.supply.set_voltage(self.l_voltage)
time.sleep(0.01)
def power_up_1v8(self):
"""
Power supply powerup sequence:
turns off both devices
turns on device and change voltage to the required one
"""
rm = pyvisa.ResourceManager("@py")
usb_devices = [
resource for resource in rm.list_resources() if "SPD" in resource
]
if usb_devices:
# Use the first USB device found with 'SPD' in its name
resource_name = usb_devices[0]
inst = rm.open_resource(resource_name)
inst.query_delay = 0.1
inst.write("CH1:VOLT 1.8")
time.sleep(0.1)
inst.write("OUTP CH1, ON")
time.sleep(0.1)
inst.write("CH2:VOLT 3.3")
time.sleep(0.1)
inst.write("OUTP CH2, ON")
time.sleep(0.8)
l_volt = float(inst.query('MEAsure:VOLTage? CH1'))
h_volt = float(inst.query('MEAsure:VOLTage? CH2'))
l_volt_expected = 1.8
h_volt_expected = 3.3
error_tolerance = 0.1
if not math.isclose(l_volt, l_volt_expected, abs_tol=error_tolerance) or not math.isclose(h_volt, h_volt_expected, abs_tol=error_tolerance):
Console.print(f"[red]Error: {resource_name} not within 0.1V of expected voltages")
self.turn_off_devices()
exit()
rm.close()
else:
self.device3v3.supply.set_voltage(3.3)
time.sleep(0.1)
self.device1v8.supply.set_voltage(1.8)
time.sleep(0.1)
def turn_off_devices(self):
"""
turns off all devices
"""
rm = pyvisa.ResourceManager("@py")
usb_devices = [
resource for resource in rm.list_resources() if "SPD" in resource
]
if usb_devices:
# Use the first USB device found with 'SPD' in its name
resource_name = usb_devices[0]
inst = rm.open_resource(resource_name)
inst.query_delay = 0.1
inst.write("OUTP CH1, OFF")
time.sleep(0.1)
inst.write("OUTP CH2, OFF")
time.sleep(0.1)
rm.close()
else:
self.device1v8.supply.turn_off()
self.device3v3.supply.turn_off()
def close_devices(self):
"""
turns off devices and closes them
"""
rm = pyvisa.ResourceManager("@py")
usb_devices = [
resource for resource in rm.list_resources() if "SPD" in resource
]
if usb_devices:
# Use the first USB device found with 'SPD' in its name
resource_name = usb_devices[0]
inst = rm.open_resource(resource_name)
inst.query_delay = 0.1
inst.write("OUTP CH1, OFF")
time.sleep(0.1)
inst.write("OUTP CH2, OFF")
time.sleep(0.1)
rm.close()
else:
self.device1v8.supply.turn_off()
self.device3v3.supply.turn_off()
device.close(self.device1v8)
device.close(self.device3v3)
device.close(self.deviced)
def reset_devices(self):
# dwf.FDwfDigitalOutReset(self.device1v8.handle)
# dwf.FDwfDigitalOutReset(self.device3v3.handle)
# dwf.FDwfDigitalOutReset(self.deviced.handle)
# dwf.DwfDeviceReset(self.device1v8.handle)
# dwf.DwfDeviceReset(self.device3v3.handle)
# dwf.DwfDeviceReset(self.deviced.handle)
for c in self.device1v8.dio_map:
self.device1v8.dio_map[c].set_state(False)
for c in self.device3v3.dio_map:
self.device3v3.dio_map[c].set_state(False)
for c in self.deviced.dio_map:
self.deviced.dio_map[c].set_state(False)
def io_receive(self, pulses, channel):
io_pulse = 0
if channel > 13 and channel < 22:
io = self.deviced.dio_map[channel]
elif channel > 21:
io = self.device3v3.dio_map[channel]
else:
io = self.device1v8.dio_map[channel]
# self.console.print(f"recieve pulse on IO[{channel}]")
state = "HI"
timeout = time.time() + 20
accurate_delay(12.5)
while 1:
accurate_delay(25)
x = io.get_value()
if state == "LOW":
if x:
state = "HI"
elif state == "HI":
if not x:
state = "LOW"
io_pulse = io_pulse + 1
if io_pulse == pulses:
io_pulse = 0
return True
if time.time() > timeout:
return False
def setup_clock(self, clk_io, data_io):
dwf.FDwfDigitalOutEnableSet(self.device3v3.handle, c_int(self.device3v3.dio_map[clk_io].channel), c_int(1)) # enable DIO 0 as output (clock)
dwf.FDwfDigitalOutEnableSet(self.device3v3.handle, c_int(self.device3v3.dio_map[data_io].channel), c_int(1)) # enable DIO 1 as output (output)
dwf.FDwfDigitalOutDividerSet(self.device3v3.handle, c_int(1)) # set divider to 1 (fastest clock)
dwf.FDwfDigitalOutCounterInitSet(self.device3v3.handle, c_int(0), c_int(1)) # set counter to 1 (fastest clock)
def run_clock(self, data, clk_io, data_io):
self.setup_clock(clk_io, data_io)
for bit in data:
dwf.FDwfDigitalOutCounterSet(self.device3v3.handle, c_int(self.device3v3.dio_map[clk_io].channel), c_int(1), c_int(1)) # set output on positive edge of DIO 0
dwf.FDwfDigitalOutDataSet(self.device3v3.handle, c_int(self.device3v3.dio_map[data_io].channel << bit)) # set output data on DIO 1
time.sleep(0.001) # adjust sleep time as needed
class Device:
"""
Device class to initialize devices
"""
def __init__(self, device, id, dio_map):
self.ad_device = device
self.id = id
self.dio_map = dio_map
self.handle = device.handle
self.supply = PowerSupply(self.ad_device)
class Dio:
def __init__(self, channel, device_data, state=False):
self.device_data = device_data
self.channel = channel
self.state = self.set_state(state)
def get_value(self):
"""
get the state of a DIO line
parameters: - device data
- selected DIO channel number
returns: - True if the channel is HIGH, or False, if the channel is LOW
"""
# load internal buffer with current state of the pins
dwf.FDwfDigitalIOStatus(self.device_data.handle)
# get the current state of the pins
data = ctypes.c_uint32() # variable for this current state
dwf.FDwfDigitalIOInputStatus(self.device_data.handle, ctypes.byref(data))
# convert the state to a 16 character binary string
data = list(bin(data.value)[2:].zfill(16))
# check the required bit
if data[15 - self.channel] != "0":
value = True
else:
value = False
return value
def set_state(self, state):
"""
set a DIO line as input, or as output
parameters: - device data
- selected DIO channel number
- True means output, False means input
"""
# load current state of the output enable buffer
mask = ctypes.c_uint16()
dwf.FDwfDigitalIOOutputEnableGet(self.device_data.handle, ctypes.byref(mask))
# convert mask to list
mask = list(bin(mask.value)[2:].zfill(16))
# set bit in mask
if state:
mask[15 - self.channel] = "1"
else:
mask[15 - self.channel] = "0"
# convert mask to number
mask = "".join(element for element in mask)
mask = int(mask, 2)
# set the pin to output
dwf.FDwfDigitalIOOutputEnableSet(self.device_data.handle, ctypes.c_int(mask))
def set_value(self, value):
"""
set a DIO line as input, or as output
parameters: - device data
- selected DIO channel number
- True means HIGH, False means LOW
"""
if self.state is True:
test.console.print("can't set value for an input pin")
else:
# load current state of the output state buffer
mask = ctypes.c_uint16()
dwf.FDwfDigitalIOOutputGet(self.device_data.handle, ctypes.byref(mask))
# convert mask to list
mask = list(bin(mask.value)[2:].zfill(16))
# set bit in mask
if value:
mask[15 - self.channel] = "1"
else:
mask[15 - self.channel] = "0"
# convert mask to number
mask = "".join(element for element in mask)
mask = int(mask, 2)
# set the pin state
dwf.FDwfDigitalIOOutputSet(self.device_data.handle, ctypes.c_int(mask))
return
class UART:
def __init__(self, device_data):
self.device_data = device_data
self.rx = 8
# self.tx = 5
self.tx = 7
def open(self, baud_rate=9600, parity=None, data_bits=8, stop_bits=1):
"""
initializes UART communication
parameters: - device data
- rx (DIO line used to receive data)
- tx (DIO line used to send data)
- baud_rate (communication speed, default is 9600 bits/s)
- parity possible: None (default), True means odd, False means even
- data_bits (default is 8)
- stop_bits (default is 1)
"""
# set baud rate
dwf.FDwfDigitalUartRateSet(self.device_data.handle, ctypes.c_double(baud_rate))
# set communication channels
dwf.FDwfDigitalUartTxSet(self.device_data.handle, ctypes.c_int(self.tx))
dwf.FDwfDigitalUartRxSet(self.device_data.handle, ctypes.c_int(self.rx))
# set data bit count
dwf.FDwfDigitalUartBitsSet(self.device_data.handle, ctypes.c_int(data_bits))
# set parity bit requirements
if parity == True:
parity = 2
elif parity == False:
parity = 1
else:
parity = 0
dwf.FDwfDigitalUartParitySet(self.device_data.handle, ctypes.c_int(parity))
# set stop bit count
dwf.FDwfDigitalUartStopSet(self.device_data.handle, ctypes.c_double(stop_bits))
# initialize channels with idle levels
# dummy read
dummy_buffer = ctypes.create_string_buffer(0)
dummy_buffer = ctypes.c_int(0)
dummy_parity_flag = ctypes.c_int(0)
dwf.FDwfDigitalUartRx(
self.device_data.handle,
dummy_buffer,
ctypes.c_int(0),
ctypes.byref(dummy_buffer),
ctypes.byref(dummy_parity_flag),
)
# dummy write
dwf.FDwfDigitalUartTx(self.device_data.handle, dummy_buffer, ctypes.c_int(0))
return
def read_uart(self):
"""
receives data from UART
parameters: - device data
return: - integer list containing the received bytes
- error message or empty string
"""
# variable to store results
# error = ""
# rx_data = []
# create empty string buffer
data = create_string_buffer(8193)
# character counter
count = ctypes.c_int(0)
# parity flag
parity_flag = ctypes.c_int(0)
# read up to 8k characters
dwf.FDwfDigitalUartRx(
self.device_data.handle,
data,
ctypes.c_int(ctypes.sizeof(data) - 1),
ctypes.byref(count),
ctypes.byref(parity_flag),
)
# append current data chunks
# for index in range(0, count.value):
# rx_data.append(int(data[index]))
# ensure data integrity
# while count.value > 0:
# # create empty string buffer
# data = (ctypes.c_ubyte * 8193)()
# # character counter
# count = ctypes.c_int(0)
# # parity flag
# parity_flag= ctypes.c_int(0)
# # read up to 8k characters
# dwf.FDwfDigitalUartRx(self.device_data.handle, data, ctypes.c_int(ctypes.sizeof(data)-1), ctypes.byref(count), ctypes.byref(parity_flag))
# # append current data chunks
# # for index in range(0, count.value):
# # rx_data.append(int(data[index]))
# # check for not acknowledged
# if error == "":
# if parity_flag.value < 0:
# error = "Buffer overflow"
# elif parity_flag.value > 0:
# error = "Parity error: index {}".format(parity_flag.value)
if count.value > 0:
return data, count
else:
return None, count
def write(self, data):
"""
send data through UART
parameters: - data of type string, int, or list of characters/integers
"""
# cast data
if type(data) == int:
data = "".join(chr(data))
elif type(data) == list:
data = "".join(chr(element) for element in data)
# encode the string into a string buffer
data = ctypes.create_string_buffer(data.encode("UTF-8"))
# send text, trim zero ending
dwf.FDwfDigitalUartTx(
self.device_data.handle, data, ctypes.c_int(ctypes.sizeof(data) - 1)
)
return
def read_data(self, test, timeout=50):
self.open()
timeout = time.time() + timeout
rgRX = b""
while True:
uart_data, count = self.read_uart()
if uart_data:
uart_data[count.value] = 0
rgRX = rgRX + uart_data.value
if b"\n" in rgRX:
return rgRX
if time.time() > timeout:
return b"UART Timeout!\n\r"
# test.progress.stop()
# self.close()
# os._exit(1)
def close(self):
# dwf.FDwfDeviceClose(self.device_data.handle)
# device.open(self.device_data.handle)
# dwf.FDwfDigitalUartReset(self.device_data.handle)
dwf.FDwfDigitalOutReset(self.device_data.handle)
class SPI:
def __init__(self, device_data, rw_mode="r", data=[]):
self.device_data = device_data
self.cs = 33
self.sck = 32
self.miso = 35
self.mosi = 34
self.clk_freq = 10e06
self.mode = 0
self.order = True
self.data = data
self.rw_mode = rw_mode
def open(self):
"""
initializes SPI communication
parameters: - device data
- cs (DIO line used for chip select)
- sck (DIO line used for serial clock)
- miso (DIO line used for master in - slave out, optional)
- mosi (DIO line used for master out - slave in, optional)
- frequency (communication frequency in Hz, default is 1MHz)
- mode (SPI mode: 0: CPOL=0, CPHA=0; 1: CPOL-0, CPHA=1; 2: CPOL=1, CPHA=0; 3: CPOL=1, CPHA=1)
- order (endianness, True means MSB first - default, False means LSB first)
"""
# set the clock frequency
dwf.FDwfDigitalSpiFrequencySet(
self.device_data.handle, ctypes.c_double(self.clk_frequency)
)
# set the clock pin
dwf.FDwfDigitalSpiClockSet(self.device_data.handle, ctypes.c_int(self.sck))
if self.mosi != None:
# set the mosi pin
dwf.FDwfDigitalSpiDataSet(
self.device_data.handle, ctypes.c_int(0), ctypes.c_int(self.mosi)
)
# set the initial state
dwf.FDwfDigitalSpiIdleSet(
self.device_data.handle, ctypes.c_int(0), constants.DwfDigitalOutIdleZet
)
if self.miso != None:
# set the miso pin
dwf.FDwfDigitalSpiDataSet(
self.device_data.handle, ctypes.c_int(1), ctypes.c_int(self.miso)
)
# set the initial state
dwf.FDwfDigitalSpiIdleSet(
self.device_data.handle, ctypes.c_int(1), constants.DwfDigitalOutIdleZet
)
# set the SPI mode
dwf.FDwfDigitalSpiModeSet(self.device_data.handle, ctypes.c_int(self.mode))
# set endianness
if self.order:
# MSB first
dwf.FDwfDigitalSpiOrderSet(self.device_data.handle, ctypes.c_int(1))
else:
# LSB first
dwf.FDwfDigitalSpiOrderSet(self.device_data.handle, ctypes.c_int(0))
# set the cs pin HIGH
dwf.FDwfDigitalSpiSelect(
self.device_data.handle, ctypes.c_int(self.cs), ctypes.c_int(1)
)
# dummy write
dwf.FDwfDigitalSpiWriteOne(
self.device_data.handle, ctypes.c_int(1), ctypes.c_int(0), ctypes.c_int(0)
)
return
def read(self, count=1):
"""
receives data from SPI
parameters: - device data
- count (number of bytes to receive)
- chip select line number
return: - integer list containing the received bytes
"""
# enable the chip select line
dwf.FDwfDigitalSpiSelect(
self.device_data.handle, ctypes.c_int(self.cs), ctypes.c_int(0)
)
# create buffer to store data
buffer = (ctypes.c_ubyte * count)()
# read array of 8 bit elements
dwf.FDwfDigitalSpiRead(
self.device_data.handle,
ctypes.c_int(1),
ctypes.c_int(8),
buffer,
ctypes.c_int(len(buffer)),
)
# disable the chip select line
dwf.FDwfDigitalSpiSelect(
self.device_data.handle, ctypes.c_int(cs), ctypes.c_int(1)
)
# decode data
data = [int(element) for element in buffer]
return data
def write(self, data):
"""
send data through SPI
parameters: - device data
- data of type string, int, or list of characters/integers
- chip select line number
"""
# cast data
if type(data) == int:
data = "".join(chr(data))
elif type(data) == list:
data = "".join(chr(element) for element in data)
# enable the chip select line
dwf.FDwfDigitalSpiSelect(
self.device_data.handle, ctypes.c_int(self.cs), ctypes.c_int(0)
)
# create buffer to write
data = bytes(data, "utf-8")
buffer = (ctypes.c_ubyte * len(data))()
for index in range(0, len(buffer)):
buffer[index] = ctypes.c_ubyte(data[index])
# write array of 8 bit elements
dwf.FDwfDigitalSpiWrite(
self.device_data.handle,
ctypes.c_int(1),
ctypes.c_int(8),
buffer,
ctypes.c_int(len(buffer)),
)
# disable the chip select line
dwf.FDwfDigitalSpiSelect(
self.device_data.handle, ctypes.c_int(cs), ctypes.c_int(1)
)
return
class SPI:
def __init__(self, device_data, rw_mode="r", data=[]):
self.device_data = device_data
self.cs = 11
self.sck = 10
self.miso = 13
self.mosi = 12
self.clk_frequency = 151
self.mode = 0
self.order = True
self.data = data
self.rw_mode = rw_mode
def open(self):
"""
initializes SPI communication
parameters: - device data
- cs (DIO line used for chip select)
- sck (DIO line used for serial clock)
- miso (DIO line used for master in - slave out, optional)
- mosi (DIO line used for master out - slave in, optional)
- frequency (communication frequency in Hz, default is 1MHz)
- mode (SPI mode: 0: CPOL=0, CPHA=0; 1: CPOL-0, CPHA=1; 2: CPOL=1, CPHA=0; 3: CPOL=1, CPHA=1)
- order (endianness, True means MSB first - default, False means LSB first)
"""
# set the clock frequency
dwf.FDwfDigitalSpiFrequencySet(
self.device_data.handle, ctypes.c_double(self.clk_frequency)
)
# set the clock pin
dwf.FDwfDigitalSpiClockSet(self.device_data.handle, ctypes.c_int(self.sck))
if self.mosi != None:
# set the mosi pin
dwf.FDwfDigitalSpiDataSet(
self.device_data.handle, ctypes.c_int(0), ctypes.c_int(self.mosi)
)
# set the initial state
dwf.FDwfDigitalSpiIdleSet(
self.device_data.handle, ctypes.c_int(0), constants.DwfDigitalOutIdleZet
)
if self.miso != None:
# set the miso pin
dwf.FDwfDigitalSpiDataSet(
self.device_data.handle, ctypes.c_int(1), ctypes.c_int(self.miso)
)
# set the initial state
dwf.FDwfDigitalSpiIdleSet(
self.device_data.handle, ctypes.c_int(1), constants.DwfDigitalOutIdleZet
)
# set the SPI mode
dwf.FDwfDigitalSpiModeSet(self.device_data.handle, ctypes.c_int(self.mode))
# set endianness
if self.order:
# MSB first
dwf.FDwfDigitalSpiOrderSet(self.device_data.handle, ctypes.c_int(1))
else:
# LSB first
dwf.FDwfDigitalSpiOrderSet(self.device_data.handle, ctypes.c_int(0))
# set the cs pin HIGH
dwf.FDwfDigitalSpiSelect(
self.device_data.handle, ctypes.c_int(self.cs), ctypes.c_int(1)
)
# dummy write
dwf.FDwfDigitalSpiWriteOne(
self.device_data.handle, ctypes.c_int(1), ctypes.c_int(0), ctypes.c_int(0)
)
return
def read(self, count):
"""
receives data from SPI
parameters: - device data
- count (number of bytes to receive)
- chip select line number
return: - integer list containing the received bytes
"""
# enable the chip select line
# dwf.FDwfDigitalSpiSelect(
# self.device_data.handle, ctypes.c_int(self.cs), ctypes.c_int(0)
# )
if dwf.FDwfDigitalInTriggerSet(
self.device_data.handle,
ctypes.c_int(0),
ctypes.c_int(0),
ctypes.c_int((1 << self.sck) | (1 << self.cs)),
ctypes.c_int(0),
):
# create buffer to store data
buffer = (ctypes.c_ubyte * count)()
# read array of 8 bit elements
dwf.FDwfDigitalSpiRead(
self.device_data.handle,
ctypes.c_int(1),
ctypes.c_int(8),
buffer,
ctypes.c_int(len(buffer)),
)
# disable the chip select line
# dwf.FDwfDigitalSpiSelect(