-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathtest_usb_source_measure.py
More file actions
1121 lines (987 loc) · 53.9 KB
/
test_usb_source_measure.py
File metadata and controls
1121 lines (987 loc) · 53.9 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
import unittest
from typing import Mapping, Dict
from typing_extensions import override
from edg.abstract_parts.ESeriesUtil import ESeriesRatioUtil
from edg.abstract_parts.ResistiveDivider import DividerValues
from edg.electronics_model.VoltagePorts import VoltageSinkAdapterAnalogSource # needed by imported schematic
from edg.electronics_model.GroundPort import GroundAdapterAnalogSource # needed by imported schematic
from edg import *
class SourceMeasureDutConnector(Connector):
def __init__(self) -> None:
super().__init__()
self.conn = self.Block(PinHeader254Horizontal(3))
self.gnd = self.Port(Ground(), [Common])
self.io0 = self.Export(self.conn.pins.request("2").adapt_to(DigitalBidir()))
self.io1 = self.Export(self.conn.pins.request("3").adapt_to(DigitalBidir()))
self.connect(self.gnd.net, self.conn.pins.request("1"))
class SourceMeasureFan(Connector):
def __init__(self) -> None:
super().__init__()
self.gnd = self.Port(Ground(), [Common])
self.pwr = self.Port(VoltageSink(voltage_limits=5 * Volt(tol=0.1), current_draw=200 * mAmp(tol=0)), [Power])
self.conn = self.Block(JstPhKVertical(2)).connected({"1": self.gnd, "2": self.pwr})
class SourceMeasureRangingCell(Interface, KiCadSchematicBlock):
def __init__(self, resistance: RangeLike):
super().__init__()
self.resistance = self.ArgParameter(resistance)
self.actual_resistance = self.Parameter(RangeExpr())
self.gnd = self.Port(Ground.empty(), [Common])
self.pwr = self.Port(VoltageSink.empty(), [Power])
self.pwr_in = self.Port(VoltageSink.empty())
self.pwr_out = self.Port(VoltageSource.empty())
self.control = self.Port(DigitalSink.empty())
self.sense_in = self.Port(AnalogSource.empty())
self.sense_out = self.Port(AnalogSource.empty())
@override
def contents(self) -> None:
super().contents()
self.import_kicad(
self.file_path("UsbSourceMeasure", f"{self.__class__.__name__}.kicad_sch"),
locals={
"clamp": {"clamp_current": (5, 25) * mAmp, "clamp_target": (0, float("inf")) * Volt, "zero_out": True},
"resistance": self.resistance,
},
)
self.sense_sw: AnalogMuxer # schematic-defined
self.connect(self.control, self.sense_sw.control.request())
self.isense: CurrentSenseResistor
self.assign(self.actual_resistance, self.isense.actual_resistance)
class RangingCurrentSenseResistor(Interface, KiCadImportableBlock, GeneratorBlock):
"""Generates an array of current-sense resistors with one side muxed and the other end an array.
The resistors are tied common on the com side, and have a solid-state relay for the power path
on the input side. Each resistor has an analog switch on the input sense side.
The control line is one bit for each range (range connectivity is independent).
Multiple ranges can be connected simultaneously, this allows make-before-break connectivity."""
@override
def symbol_pinning(self, symbol_name: str) -> Dict[str, BasePort]:
assert symbol_name == "edg_importable:CurrentSenseResistorMux"
return {
"control": self.control,
"sw": self.pwr_in,
"com": self.pwr_out,
"sen_sw": self.sense_in,
"sen_com": self.sense_out,
"V+": self.pwr,
"V-": self.gnd,
}
def __init__(self, resistances: ArrayRangeLike, currents: ArrayRangeLike):
super().__init__()
self.gnd = self.Port(Ground.empty(), [Common])
self.pwr = self.Port(VoltageSink.empty(), [Power])
self.pwr_in = self.Port(VoltageSink.empty())
self.pwr_out = self.Port(VoltageSource.empty())
self.control = self.Port(Vector(DigitalSink.empty()))
self.sense_in = self.Port(AnalogSource.empty())
self.sense_out = self.Port(AnalogSource.empty())
self.resistances = self.ArgParameter(resistances)
self.currents = self.ArgParameter(currents)
self.generator_param(self.resistances, self.currents)
self.out_range = self.Parameter(RangeExpr())
@override
def generate(self) -> None:
super().generate()
self.ranges = ElementDict[SourceMeasureRangingCell]()
self.forced = ElementDict[ForcedVoltageCurrentDraw]()
self.pwr_out_merge = self.Block(MergedVoltageSource())
self.connect(self.pwr_out_merge.pwr_out, self.pwr_out)
self.sense_in_merge = self.Block(MergedAnalogSource())
self.connect(self.sense_in_merge.output, self.sense_in)
self.sense_out_merge = self.Block(MergedAnalogSource())
self.connect(self.sense_out_merge.output, self.sense_out)
out_range = RangeExpr._to_expr_type(RangeExpr.EMPTY)
with self.implicit_connect(ImplicitConnect(self.gnd, [Common]), ImplicitConnect(self.pwr, [Power])) as imp:
for i, (resistance, current) in enumerate(zip(self.get(self.resistances), self.get(self.currents))):
range = self.ranges[i] = imp.Block(SourceMeasureRangingCell(resistance))
self.connect(self.pwr_in, range.pwr_in)
forced = self.forced[i] = self.Block(ForcedVoltageCurrentDraw(current))
self.connect(range.pwr_out, forced.pwr_in)
self.connect(self.pwr_out_merge.pwr_ins.request(str(i)), forced.pwr_out)
self.connect(range.control, self.control.append_elt(DigitalSink.empty(), str(i)))
self.connect(self.sense_in_merge.inputs.request(str(i)), range.sense_in)
self.connect(self.sense_out_merge.inputs.request(str(i)), range.sense_out)
out_range = out_range.hull(current * range.actual_resistance)
self.assign(self.out_range, out_range)
class EmitterFollower(InternalSubcircuit, KiCadSchematicBlock, KiCadImportableBlock, Block):
"""Emitter follower circuit."""
@override
def symbol_pinning(self, symbol_name: str) -> Mapping[str, BasePort]:
assert symbol_name == "edg_importable:Follower" # this requires an schematic-modified symbol
return {
"1": self.control,
"3": self.out,
"V+": self.pwr,
"V-": self.gnd,
"HG": self.high_gate_ctl,
"LG": self.low_gate_ctl,
"VG+": self.pwr_gate_pos,
"VG-": self.pwr_gate_neg,
}
def __init__(self, current: RangeLike, rds_on: RangeLike, gate_clamp_voltage: RangeLike):
super().__init__()
self.pwr = self.Port(VoltageSink.empty(), [Power])
self.gnd = self.Port(Ground.empty(), [Common])
self.pwr_gate_pos = self.Port(VoltageSink.empty())
self.pwr_gate_neg = self.Port(Ground.empty())
self.out = self.Port(VoltageSource.empty())
self.control = self.Port(AnalogSink.empty())
self.high_gate_ctl = self.Port(DigitalSink.empty())
self.low_gate_ctl = self.Port(DigitalSink.empty())
self.current = self.ArgParameter(current)
self.rds_on = self.ArgParameter(rds_on)
self.gate_clamp_voltage = self.ArgParameter(gate_clamp_voltage)
@override
def contents(self) -> None:
super().contents()
zener_model = ZenerDiode(self.gate_clamp_voltage)
self.clamp1 = self.Block(zener_model)
self.clamp2 = self.Block(zener_model)
gate_voltage = (-self.clamp1.actual_zener_voltage).hull(self.clamp2.actual_zener_voltage)
self.high_fet = self.Block(
Fet.NFet(
drain_voltage=self.pwr.link().voltage,
drain_current=self.current,
gate_voltage=gate_voltage,
rds_on=self.rds_on,
power=self.pwr.link().voltage * self.current,
)
)
self.low_fet = self.Block(
Fet.PFet(
drain_voltage=self.pwr.link().voltage,
drain_current=self.current,
gate_voltage=gate_voltage,
rds_on=self.rds_on,
power=self.pwr.link().voltage * self.current,
)
)
# resistance is low enough to slew the FET Ciss,
# but high enough to prevent excessive loading of the opamp to instability
# and to allow the clamping zeners to control an overvoltage
resistance = 15 * 10 * Ohm(tol=0.02)
max_opamp_current = 0.07 # amps
max_clamp_voltage = (
VoltageLink._supply_voltage_range(self.pwr_gate_neg, self.pwr_gate_pos).upper()
- self.gate_clamp_voltage.lower()
)
self.res = self.Block(
Resistor(
resistance=resistance,
power=(0, max_opamp_current**2 * resistance.upper()),
voltage=(0, max_clamp_voltage),
)
)
self.import_kicad(
self.file_path("UsbSourceMeasure", f"{self.__class__.__name__}.kicad_sch"),
conversions={
"low_fet.D": Ground(),
"high_fet.D": VoltageSink(
current_draw=self.current,
voltage_limits=self.high_fet.actual_drain_voltage_rating.intersect(
self.low_fet.actual_drain_voltage_rating
),
),
"out": VoltageSource(
voltage_out=self.pwr.link().voltage,
current_limits=self.high_fet.actual_drain_current_rating.intersect(
self.low_fet.actual_drain_current_rating
),
),
"control": AnalogSink(),
# TODO FIXME
"res.2": AnalogSource(),
"clamp1.A": AnalogSink(),
"low_res.1": AnalogSink(),
"low_fet.G": AnalogSink(),
"high_res.1": AnalogSink(),
"high_fet.G": AnalogSink(),
},
)
self.high_gate: AnalogMuxer # defined in schematic
self.connect(self.high_gate_ctl, self.high_gate.control.request())
self.low_gate: AnalogMuxer
self.connect(self.low_gate_ctl, self.low_gate.control.request())
self.connect(self.gnd, self.high_gate.control_gnd, self.low_gate.control_gnd)
class GatedSummingAmplifier(InternalSubcircuit, KiCadSchematicBlock, KiCadImportableBlock, GeneratorBlock):
"""A noninverting summing amplifier with an optional diode gate (enforcing drive direction) and inline resistance
(to allow its output to be overridden by a stronger driver).
Used as the error amplifier in SMU analog control block, the target is set with inverted polarity
(around the integrator reference). When the measured signal is at the target, the output (sum)
is the integrator reference, producing zero error. Otherwise, the error signal is proportional to the deviation.
The sense_out line is upstream of this element and can be used to determine if a current limit amplifier is active.
TODO: diode parameter should be an enum. Current values: '' (no diode), 'sink', 'source' (sinks or sources current)
"""
@override
def symbol_pinning(self, symbol_name: str) -> Mapping[str, BasePort]:
assert symbol_name in ("Simulation_SPICE:OPAMP", "edg_importable:Opamp")
return {
"M": self.actual,
"T": self.target,
"F": self.target_fine,
"3": self.output,
"S": self.sense_out,
"V+": self.pwr,
"V-": self.gnd,
}
def __init__(
self,
input_resistance: RangeLike = 0 * Ohm(tol=0),
*,
dir: StringLike = "",
res: RangeLike = 0 * Ohm(tol=0),
fine_scale: FloatLike = 0,
series: IntLike = 24,
tolerance: FloatLike = 0.01,
):
super().__init__()
self.pwr = self.Port(VoltageSink.empty(), [Power])
self.gnd = self.Port(Ground.empty(), [Common])
self.target = self.Port(AnalogSink.empty())
self.target_fine = self.Port(AnalogSink.empty(), optional=True)
self.actual = self.Port(AnalogSink.empty())
self.output = self.Port(AnalogSource.empty())
self.sense_out = self.Port(AnalogSource.empty(), optional=True)
self.input_resistance = self.ArgParameter(input_resistance)
self.dir = self.ArgParameter(dir)
self.res = self.ArgParameter(res) # output side
self.fine_scale = self.ArgParameter(fine_scale)
self.series = self.ArgParameter(series)
self.tolerance = self.ArgParameter(tolerance)
self.generator_param(
self.input_resistance,
self.res,
self.dir,
self.series,
self.tolerance,
self.target_fine.is_connected(),
self.sense_out.is_connected(),
self.fine_scale,
)
@override
def generate(self) -> None:
super().generate()
# The 1/4 factor is a way to specify the series resistance of the divider assuming both resistors are equal,
# since the DividerValues util only takes the parallel resistance
calculator = ESeriesRatioUtil(
ESeriesUtil.SERIES[self.get(self.series)], self.get(self.tolerance), DividerValues
)
top_resistance, bottom_resistance = calculator.find(
DividerValues(Range.from_tolerance(0.5, self.get(self.tolerance)), self.get(self.input_resistance) / 4)
)
self.amp = self.Block(Opamp())
self.rtop = self.Block(Resistor(resistance=Range.from_tolerance(top_resistance, self.get(self.tolerance))))
self.rbot = self.Block(Resistor(resistance=Range.from_tolerance(bottom_resistance, self.get(self.tolerance))))
output_impedance = self.amp.out.link().source_impedance
dir = self.get(self.dir)
if dir:
self.diode = self.Block(
Diode( # TODO should be encoded as a voltage difference?
reverse_voltage=self.amp.out.voltage_out,
current=RangeExpr.ZERO, # an approximation, current rating not significant here
voltage_drop=(0, 0.8) * Volt, # arbitrary low threshold
)
)
amp_out_model = AnalogSink(impedance=self.output.link().sink_impedance)
if dir == "source":
self.connect(self.amp.out, self.diode.anode.adapt_to(amp_out_model))
amp_out_node = self.diode.cathode
elif dir == "sink":
self.connect(self.amp.out, self.diode.cathode.adapt_to(amp_out_model))
amp_out_node = self.diode.anode
else:
raise ValueError(f"invalid dir '{dir}', expected '', 'source', or 'sink'")
if self.get(self.res) != Range.exact(0): # if resistor requested
assert not dir, "diode + output resistance not supported"
self.rout = self.Block(Resistor(resistance=self.res))
self.connect(
self.amp.out,
self.rout.a.adapt_to(
AnalogSink(impedance=self.rout.actual_resistance + self.output.link().sink_impedance)
),
)
amp_out_node = self.rout.b
output_impedance += self.rout.actual_resistance
self.connect(amp_out_node.adapt_to(AnalogSource(impedance=output_impedance)), self.output)
self.import_kicad(
self.file_path("UsbSourceMeasure", f"{self.__class__.__name__}.kicad_sch"),
conversions={
"target": AnalogSink(
impedance=self.rtop.actual_resistance
+ self.rbot.actual_resistance # assumed dominates fine resistance
),
"actual": AnalogSink(impedance=self.rtop.actual_resistance + self.rbot.actual_resistance),
"rtop.2": AnalogSource(
voltage_out=self.target.link().voltage.hull(self.actual.link().voltage),
signal_out=self.target.link().voltage.hull(self.actual.link().voltage),
impedance=1 / (1 / self.rtop.actual_resistance + 1 / self.rbot.actual_resistance),
),
"rbot.2": AnalogSink(), # ideal, rtop.2 contains the parameter model
},
)
if self.get(self.target_fine.is_connected()):
assert self.get(self.fine_scale) != 0
self.rfine = self.Block(
Resistor(
resistance=Range.from_tolerance(
top_resistance * self.get(self.fine_scale), self.get(self.tolerance)
)
)
)
self.connect(
self.target_fine,
self.rfine.a.adapt_to(
AnalogSink(impedance=self.rfine.actual_resistance) # assumed non-fine resistance dominates
),
)
self.connect(self.rfine.b.adapt_to(AnalogSink()), self.amp.inp)
if self.get(self.sense_out.is_connected()):
self.connect(self.amp.out, self.sense_out)
class JfetCurrentClamp(InternalSubcircuit, KiCadSchematicBlock, KiCadImportableBlock, Block):
"""JET-based current clamp, clamps to roughly 10mA while maintaining a relatively low non-clamping
impedance of ~100ohm. Max ~35V limited by JFET Vgs,max.
"""
@override
def symbol_pinning(self, symbol_name: str) -> Mapping[str, BasePort]:
assert symbol_name == "edg_importable:Unk2"
return {"1": self.input, "2": self.output}
def __init__(self, model_voltage_clamp: RangeLike, model_signal_clamp: RangeLike = RangeExpr.ALL):
super().__init__()
self.model_voltage_clamp = self.ArgParameter(model_voltage_clamp)
self.model_signal_clamp = self.ArgParameter(model_signal_clamp)
self.input = self.Port(AnalogSink.empty(), [Power])
self.output = self.Port(AnalogSource.empty(), [Common])
@override
def contents(self) -> None:
super().contents()
self.import_kicad(
self.file_path("UsbSourceMeasure", f"{self.__class__.__name__}.kicad_sch"),
conversions={
"input": AnalogSink(
current_draw=self.output.link().current_drawn, impedance=self.output.link().sink_impedance
),
"output": AnalogSource(
voltage_out=self.input.link().voltage.intersect(self.model_voltage_clamp),
signal_out=self.input.link().signal.intersect(self.model_signal_clamp),
impedance=self.input.link().source_impedance,
),
},
)
class SrLatchInverted(Block):
"""Set-reset latch with active-high set, active-high reset, set priority, and low output when set (high when idle).
This uses two NOR gates.
NOR1 handles set with priority, when any input is high, the output goes low.
Latching is done when NOR1 is low, which feeds into NOR2. If reset isn't asserted, both NOR2 inputs are low
and NOR2 output is high, which feeds back into a NOR1 input to keep NOR1 low.
NOR2 handles reset without priority, when the input goes high, its output goes low which clears the latch.
"""
def __init__(self) -> None:
super().__init__()
self.ic = self.Block(Sn74lvc2g02())
self.gnd = self.Export(self.ic.gnd, [Common])
self.pwr = self.Export(self.ic.pwr, [Power])
self.set = self.Export(self.ic.in1a) # any in1
self.rst = self.Export(self.ic.in2a) # any in2
self.out = self.Export(self.ic.out1)
@override
def contents(self) -> None:
super().contents()
self.connect(self.ic.out1, self.ic.in2b)
self.connect(self.ic.out2, self.ic.in1b)
class SourceMeasureControl(InternalSubcircuit, KiCadSchematicBlock, Block):
"""Analog feedback circuit for the source-measure unit"""
def __init__(self, current: RangeLike, rds_on: RangeLike):
super().__init__()
self.pwr = self.Port(VoltageSink.empty(), [Power])
self.pwr_logic = self.Port(VoltageSink.empty())
self.gnd = self.Port(Ground.empty(), [Common])
self.ref_center = self.Port(AnalogSink.empty())
self.pwr_gate_pos = self.Port(VoltageSink.empty())
self.pwr_gate_neg = self.Port(Ground.empty())
self.control_voltage = self.Port(AnalogSink.empty())
self.control_voltage_fine = self.Port(AnalogSink.empty())
self.control_current_source = self.Port(AnalogSink.empty())
self.control_current_sink = self.Port(AnalogSink.empty())
self.high_gate_ctl = self.Port(DigitalSink.empty())
self.low_gate_ctl = self.Port(DigitalSink.empty())
self.irange = self.Port(Vector(DigitalSink.empty()))
self.off = self.Port(Vector(DigitalSink.empty()))
self.out = self.Port(VoltageSource.empty())
self.measured_voltage = self.Port(AnalogSource.empty())
self.measured_current = self.Port(AnalogSource.empty())
self.limit_source = self.Port(DigitalSource.empty())
self.limit_sink = self.Port(DigitalSource.empty())
self.tp_err = self.Port(AnalogSource.empty(), optional=True)
self.tp_int = self.Port(AnalogSource.empty(), optional=True)
self.current = self.ArgParameter(current)
self.rds_on = self.ArgParameter(rds_on)
@override
def contents(self) -> None:
super().contents()
self.import_kicad(
self.file_path("UsbSourceMeasure", f"{self.__class__.__name__}.kicad_sch"),
locals={"self": self},
conversions={
"tvs_p.K": VoltageSink(),
"tvs_n.K": Ground(),
},
)
# JlcPartsRefinements are used in production since the old parts table
# list many parts that are no longer basic.
# class UsbSourceMeasure(JlcPartsRefinements, JlcBoardTop):
class UsbSourceMeasure(JlcBoardTop):
@override
def contents(self) -> None:
super().contents()
# overall design parameters
OUTPUT_CURRENT_RATING = (0, 3) * Amp
# USB PD port that supplies power to the load
# USB PD can't actually do 8 A, but this suppresses the error and we can software-limit current draw
self.usb = self.Block(UsbCReceptacle(voltage_out=(5, 20) * Volt, current_limits=(0, 8) * Amp))
self.gnd = self.connect(self.usb.gnd)
self.tp_gnd = self.Block(GroundTestPoint()).connected(self.usb.gnd)
# power supplies
with self.implicit_connect(
ImplicitConnect(self.gnd, [Common]),
) as imp:
self.vusb_sense = imp.Block(Ina219(10 * mOhm(tol=0.01)))
# input filtering and protection
(self.fuse_vusb, self.filt_vusb, self.prot_vusb), _ = self.chain(
self.usb.pwr,
self.Block(SeriesPowerFuse(trip_current=(7, 8) * Amp)),
self.Block(SeriesPowerFerriteBead()),
imp.Block(ProtectionZenerDiode(voltage=(32, 40) * Volt)), # for parts commonality w/ the Vconv zener
self.vusb_sense.sense_pos,
)
self.vusb = self.connect(self.vusb_sense.sense_neg)
(self.ramp, self.cap_conv), _ = self.chain(
self.vusb,
imp.Block(
RampLimiter(target_vgs=(3.5, 17.5) * Volt)
), # avoid excess capacitance on VBus which may cause the PD source to reset
imp.Block(DecouplingCapacitor(47 * uFarad(tol=0.25))),
)
self.vusb_ramp = self.connect(self.ramp.pwr_out) # vusb post-ramp
self.tp_vusb = self.Block(VoltageTestPoint()).connected(self.ramp.pwr_out)
# logic supplies
(self.reg_v5, self.tp_v5), _ = self.chain(
self.vusb_ramp, # non-critical power supply downstream of ramp limiter
imp.Block(BuckConverter(output_voltage=5 * Volt(tol=0.05))), # min set by gate drivers
self.Block(VoltageTestPoint()),
)
self.v5 = self.connect(self.reg_v5.pwr_out)
(self.reg_3v3, self.prot_3v3, self.tp_3v3), _ = self.chain(
self.vusb, # upstream of ramp limiter, required for bootstrapping
imp.Block(BuckConverter(output_voltage=3.3 * Volt(tol=0.05))),
imp.Block(ProtectionZenerDiode(voltage=(3.6, 4.5) * Volt)),
self.Block(VoltageTestPoint()),
)
self.v3v3 = self.connect(self.reg_3v3.pwr_out)
self.connect(self.vusb_sense.pwr, self.v3v3)
(self.reg_v12,), _ = self.chain(
self.v5,
imp.Block(BoostConverter(output_voltage=(12, 13) * Volt)), # limits of the OLED
)
self.v12 = self.connect(self.reg_v12.pwr_out)
# output power supplies
self.convin_sense = imp.Block(Ina219(10 * mOhm(tol=0.01), addr_lsb=4))
self.connect(self.convin_sense.pwr, self.v3v3)
self.connect(self.vusb_ramp, self.convin_sense.sense_pos)
self.vconvin = self.connect(self.convin_sense.sense_neg)
(self.conv_inforce, self.conv, self.conv_outforce, self.prot_conv, self.tp_conv), _ = self.chain(
self.vconvin,
imp.Block(ForcedVoltage(20 * Volt(tol=0))), # assumed input voltage to target buck-boost ratios
imp.Block(
CustomSyncBuckBoostConverterPwm(
output_voltage=(15, 30) * Volt, # design for 0.5x - 1.5x conv ratio
frequency=500 * kHertz(tol=0),
ripple_ratio=(0.01, 0.9),
input_ripple_limit=(100 * (6 / 7)) * mVolt, # fill empty space with caps
output_ripple_limit=(25 * (7 / 8)) * mVolt, # fill empty space with caps
)
),
imp.Block(ForcedVoltage((2, 30) * Volt)), # at least 2v to allow current sensor to work
imp.Block(
ProtectionZenerDiode(voltage=(32, 40) * Volt)
), # zener shunt in case the boost converter goes crazy
self.Block(VoltageTestPoint()),
)
self.connect(self.conv.pwr_logic, self.v5)
self.vconv = self.connect(self.conv_outforce.pwr_out)
# analog supplies
(self.reg_analog, self.tp_analog), _ = self.chain(
self.v5,
imp.Block(LinearRegulator(output_voltage=3.3 * Volt(tol=0.05))),
self.Block(VoltageTestPoint("va")),
)
self.vanalog = self.connect(self.reg_analog.pwr_out)
(self.reg_vref, self.tp_vref), _ = self.chain(
self.v5,
imp.Block(VoltageReference(output_voltage=3.3 * Volt(tol=0.01))),
self.Block(VoltageTestPoint()),
)
self.vref = self.connect(self.reg_vref.pwr_out)
(self.ref_div, self.ref_buf, self.ref_rc), _ = self.chain(
self.vref,
imp.Block(VoltageDivider(output_voltage=1.65 * Volt(tol=0.05), impedance=(10, 100) * kOhm)),
imp.Block(OpampFollower()),
# opamp outputs generally not stable under capacitive loading and requires an isolation series resistor
# 4.7 tries to balance low output impedance and some level of isolation
imp.Block(AnalogLowPassRc(4.7 * Ohm(tol=0.05), 1 * MHertz(tol=0.25))),
)
self.connect(self.vanalog, self.ref_buf.pwr)
self.vcenter = self.connect(self.ref_rc.output)
(self.reg_vcontrol, self.tp_vcontrol), _ = self.chain(
self.v5,
imp.Block(
BoostConverter(
output_voltage=(30, 33) * Volt, output_ripple_limit=1 * mVolt # up to but not greater
)
),
self.Block(VoltageTestPoint("vc+")),
)
self.vcontrol = self.connect(self.reg_vcontrol.pwr_out)
(self.filt_vcontroln, self.reg_vcontroln, self.tp_vcontroln), _ = self.chain(
self.vanalog,
self.Block(SeriesPowerFerriteBead()),
imp.Block(Lm2664(output_ripple_limit=5 * mVolt)),
self.Block(VoltageTestPoint("vc-")),
)
self.vcontroln = self.connect(
self.reg_vcontroln.pwr_out.as_ground(current_draw=self.reg_vcontrol.pwr_out.link().current_drawn)
)
# power path domain
with self.implicit_connect(
ImplicitConnect(self.vconv, [Power]),
ImplicitConnect(self.gnd, [Common]),
) as imp:
self.control = imp.Block(SourceMeasureControl(current=OUTPUT_CURRENT_RATING, rds_on=(0, 0.2) * Ohm))
self.connect(self.vanalog, self.control.pwr_logic)
self.connect(self.vcenter, self.control.ref_center)
self.connect(self.vcontroln, self.control.pwr_gate_neg)
self.connect(self.vcontrol, self.control.pwr_gate_pos)
(self.tp_err,), _ = self.chain(self.control.tp_err, imp.Block(AnalogCoaxTestPoint("err")))
(self.tp_int,), _ = self.chain(self.control.tp_int, imp.Block(AnalogCoaxTestPoint("int")))
# logic domain
with self.implicit_connect(
ImplicitConnect(self.v3v3, [Power]),
ImplicitConnect(self.gnd, [Common]),
) as imp:
# TODO next revision: optional clamping diode on CC lines (as present in PD buddy sink, but not OtterPill)
self.pd = imp.Block(Fusb302b())
self.connect(self.vusb, self.pd.vbus)
self.connect(self.usb.cc, self.pd.cc)
self.mcu = imp.Block(IoController())
(self.led,), _ = self.chain(
imp.Block(IndicatorSinkLed(Led.Red)), self.mcu.gpio.request("led")
) # debugging LED
(self.usb_esd,), self.usb_chain = self.chain(self.usb.usb, imp.Block(UsbEsdDiode()), self.mcu.usb.request())
int_i2c = self.mcu.i2c.request("int_i2c")
self.i2c_tp = self.Block(I2cTestPoint("i2c")).connected(int_i2c)
(self.i2c_pull,), _ = self.chain(int_i2c, imp.Block(I2cPullup()))
self.connect(int_i2c, self.pd.i2c, self.vusb_sense.i2c, self.convin_sense.i2c)
self.connect(self.mcu.gpio.request("pd_int"), self.pd.int)
self.oled = imp.Block(
Er_Oled022_1()
) # (probably) pin compatible w/ 2.4" ER-OLED024-2B; maybe ER-OLED015-2B
self.connect(self.oled.vcc, self.v12)
self.connect(self.oled.pwr, self.v3v3)
self.oled_rc = imp.Block(PullupDelayRc(10 * kOhm(tol=0.05), 10 * mSecond(tol=0.2))).connected(
io=self.oled.reset
)
self.connect(int_i2c, self.oled.i2c)
# self.connect(self.mcu.spi.request('oled_spi'), self.oled.spi)
# self.connect(self.mcu.gpio.request('oled_cs'), self.oled.cs)
# self.connect(self.mcu.gpio.request('oled_dc'), self.oled.dc)
# expander for low-speed control signals
self.ioe_ctl = imp.Block(Pca9554())
self.connect(self.ioe_ctl.i2c, int_i2c)
self.connect(self.ioe_ctl.io.request("high_gate"), self.control.high_gate_ctl)
self.connect(self.ioe_ctl.io.request("low_gate"), self.control.low_gate_ctl)
self.connect(self.ioe_ctl.io.request_vector("off"), self.control.off)
(self.ramp_pull,), _ = self.chain(
self.ioe_ctl.io.request("ramp"), imp.Block(PulldownResistor(10 * kOhm(tol=0.05))), self.ramp.control
)
rc_model = DigitalLowPassRc(150 * Ohm(tol=0.05), 7 * MHertz(tol=0.2))
(self.buck_rc,), _ = self.chain(self.mcu.gpio.request("buck_pwm"), imp.Block(rc_model), self.conv.buck_pwm)
(self.boost_rc,), _ = self.chain(
self.mcu.gpio.request("boost_pwm"), imp.Block(rc_model), self.conv.boost_pwm
)
(self.conv_ovp,), _ = self.chain(
self.conv_outforce.pwr_out.as_analog_source(),
imp.Block(VoltageComparator(trip_voltage=(30, 40) * Volt)),
)
self.conv_latch = imp.Block(SrLatchInverted())
(self.conv_en_pull,), _ = self.chain(
self.ioe_ctl.io.request("conv_en"),
imp.Block(PulldownResistor(10 * kOhm(tol=0.05))),
self.conv_latch.rst,
)
(self.comp_pull,), _ = self.chain(
self.conv_ovp.output, imp.Block(PullupResistor(resistance=10 * kOhm(tol=0.05))), self.conv_latch.set
)
self.connect(self.conv_latch.out, self.conv.reset, self.ioe_ctl.io.request("conv_en_sense"))
(self.pass_temp,), _ = self.chain(int_i2c, imp.Block(Tmp1075n(0)))
(self.conv_temp,), _ = self.chain(int_i2c, imp.Block(Tmp1075n(1)))
(self.conv_sense,), _ = self.chain(
self.vconv,
imp.Block(VoltageSenseDivider(full_scale_voltage=2.2 * Volt(tol=0.1), impedance=(1, 10) * kOhm)),
self.mcu.adc.request("vconv_sense"),
)
# expander and interface elements
self.ioe_ui = imp.Block(Pca9554(addr_lsb=2))
self.connect(self.ioe_ui.i2c, int_i2c)
self.enc = imp.Block(DigitalRotaryEncoder())
self.connect(self.enc.a, self.mcu.gpio.request("enc_a"))
self.connect(self.enc.b, self.mcu.gpio.request("enc_b"))
self.connect(self.enc.with_mixin(DigitalRotaryEncoderSwitch()).sw, self.mcu.gpio.request("enc_sw"))
self.dir = imp.Block(DigitalDirectionSwitch())
self.connect(self.dir.a, self.ioe_ui.io.request("dir_a"))
self.connect(self.dir.b, self.ioe_ui.io.request("dir_b"))
self.connect(self.dir.c, self.ioe_ui.io.request("dir_c"))
self.connect(self.dir.d, self.ioe_ui.io.request("dir_d"))
self.connect(self.dir.with_mixin(DigitalDirectionSwitchCenter()).center, self.ioe_ui.io.request("dir_cen"))
self.connect(self.ioe_ui.io.request_vector("irange"), self.control.irange)
# expansion ports
(
self.qwiic_pull,
self.qwiic,
), _ = self.chain(self.mcu.i2c.request("qwiic"), imp.Block(I2cPullup()), imp.Block(QwiicTarget()))
self.dutio = imp.Block(SourceMeasureDutConnector())
(self.dut0_clamp,), _ = self.chain(
self.dutio.io0,
self.Block(DigitalClampResistor(protection_voltage=(0, 30) * Volt)),
self.mcu.gpio.request("dut0"),
)
(self.dut1_clamp,), _ = self.chain(
self.dutio.io1,
self.Block(DigitalClampResistor(protection_voltage=(0, 30) * Volt)),
self.mcu.gpio.request("dut1"),
)
mcu_touch = self.mcu.with_mixin(IoControllerTouchDriver())
(self.touch_duck,), _ = self.chain(
mcu_touch.touch.request("touch_duck"), imp.Block(FootprintToucbPad("edg:Symbol_DucklingSolid"))
)
# 5v domain
with self.implicit_connect(
ImplicitConnect(self.v5, [Power]),
ImplicitConnect(self.gnd, [Common]),
) as imp:
(self.rgbs,), _ = self.chain(
self.mcu.gpio.request("rgb"),
imp.Block(NeopixelArray(4 + 1 + 1)), # 4 for encoder, 1 for output, 1 for USB
)
self.fan_cap = imp.Block(DecouplingCapacitor(1 * uFarad(tol=0.2)))
self.fan_drv = imp.Block(HighSideSwitch())
self.connect(self.mcu.gpio.request("fan"), self.fan_drv.control)
self.fan = self.Block(SourceMeasureFan())
self.connect(self.fan.gnd, self.gnd)
self.connect(self.fan.pwr, self.fan_drv.output)
(self.spk_drv, self.spk), _ = self.chain(
self.mcu.with_mixin(IoControllerI2s()).i2s.request("speaker"),
imp.Block(Max98357a()),
self.Block(Speaker()),
)
# analog domain
with self.implicit_connect(
ImplicitConnect(self.gnd, [Common]),
) as imp:
self.dac = imp.Block(Mcp4728())
(self.dac_ferrite,), _ = self.chain(
self.vref, imp.Block(SeriesPowerFerriteBead(Range.from_lower(1000))), self.dac.pwr
)
self.connect(self.dac.out0, self.control.control_voltage)
self.connect(self.dac.out2, self.control.control_voltage_fine)
self.connect(self.dac.out1, self.control.control_current_sink)
self.connect(self.dac.out3, self.control.control_current_source)
self.connect(self.dac.i2c, int_i2c)
self.adc = imp.Block(Mcp3561())
self.connect(self.adc.pwra, self.vanalog)
self.connect(self.adc.pwr, self.v3v3)
self.connect(self.adc.vref, self.vref)
self.connect(self.adc.spi, self.mcu.spi.request("adc_spi"))
self.connect(self.adc.cs, self.mcu.gpio.request("adc_cs"))
self.connect(self.adc.mclkin, self.mcu.gpio.request("adc_clk")) # up to 20MHz output from LEDC peripheral
(
self.tp_vcen,
self.vcen_rc,
), _ = self.chain(
self.vcenter,
imp.Block(AnalogCoaxTestPoint("cen")),
imp.Block(AnalogLowPassRc(1 * kOhm(tol=0.05), 16 * kHertz(tol=0.25))),
self.adc.vins.request("2"),
)
(
self.tp_mv,
self.mv_rc,
), _ = self.chain(
self.control.measured_voltage,
imp.Block(AnalogCoaxTestPoint("mv")),
imp.Block(AnalogLowPassRc(1 * kOhm(tol=0.05), 16 * kHertz(tol=0.25))),
self.adc.vins.request("0"),
)
(
self.tp_mi,
self.mi_rc,
), _ = self.chain(
self.control.measured_current,
imp.Block(AnalogCoaxTestPoint("mi")),
imp.Block(AnalogLowPassRc(1 * kOhm(tol=0.05), 16 * kHertz(tol=0.25))),
self.adc.vins.request("1"),
)
self.connect(self.control.limit_source, self.mcu.gpio.request("limit_source"))
self.connect(self.control.limit_sink, self.mcu.gpio.request("limit_sink"))
self.outn = self.Block(BananaSafetyJack())
self.outp = self.Block(BananaSafetyJack())
self.outd = self.Block(PinHeader254Horizontal(2)) # 2.54 output option
self.connect(self.gnd, self.outn.port.adapt_to(Ground()), self.outd.pins.request("1").adapt_to(Ground()))
self.connect(
self.control.out,
self.outp.port.adapt_to(VoltageSink(current_draw=OUTPUT_CURRENT_RATING)),
self.outd.pins.request("2").adapt_to(VoltageSink()),
)
self._block_diagram_grouping = self.Metadata(
{
"pwr": "usb, filt_vusb, fuse_vusb, prot_vusb, pd, vusb_sense, reg_v5, reg_3v3, prot_3v3",
"conv": "conv_inforce, ramp, convin_sense, cap_conv, conv, conv_outforce, conv_sense, prot_conv, "
"conv_en_pull, conv_latch, conv_ovp, comp_pull, buck_rc, boost_rc",
"analog": "reg_analog, reg_vcontrol, reg_vcontroln, reg_vref, ref_div, ref_buf, ref_cap, vcen_rc, "
"dac_ferrite, dac, mv_rc, mi_rc, adc, control, "
"outn, outp, outd",
"mcu": "mcu, led, touch_duck, ioe_ctl, usb_esd, i2c_pull, qwiic_pull, qwiic, dutio",
"sensing": "conv_temp, pass_temp",
"ui": "ioe_ui, enc, dir, rgb, reg_v12, oled, oled_rc, spk_drv, spk",
"tp": "tp_vusb, tp_gnd, tp_3v3, tp_v5, tp_v12, tp_conv, tp_analog, tp_vcontrol, tp_vcontroln, tp_vref, tp_lsrc, tp_lsnk, "
"i2c_tp",
"rf_tp": "tp_vcen, tp_cv, tp_cvf, tp_cisrc, tp_cisnk, tp_mv, tp_mi",
"packed_amps": "vimeas_amps, ampdmeas_amps, cv_amps, ci_amps, cintref_amps",
"misc": "fan_drv, fan, jlc_th",
}
)
@override
def multipack(self) -> None:
self.vimeas_amps = self.PackedBlock(Opa2189()) # low noise opamp
self.pack(self.vimeas_amps.elements.request("0"), ["control", "amp", "amp"])
self.pack(self.vimeas_amps.elements.request("1"), ["control", "hvbuf", "amp"])
self.cv_amps = self.PackedBlock(Tlv9152())
self.pack(self.cv_amps.elements.request("0"), ["ref_buf", "amp"]) # place the reference more centrally
self.pack(self.cv_amps.elements.request("1"), ["control", "err_volt", "amp"])
self.ci_amps = self.PackedBlock(Tlv9152())
self.pack(self.ci_amps.elements.request("0"), ["control", "err_sink", "amp"])
self.pack(self.ci_amps.elements.request("1"), ["control", "err_source", "amp"])
self.cintref_amps = self.PackedBlock(Tlv9152())
self.pack(self.cintref_amps.elements.request("0"), ["control", "int", "amp"])
self.pack(self.cintref_amps.elements.request("1"), ["control", "dmeas", "amp"]) # this path matters much less
@override
def refinements(self) -> Refinements:
return super().refinements() + Refinements(
instance_refinements=[
(["mcu"], Esp32s3_Wroom_1),
(["reg_v5"], Tps54202h),
(["reg_3v3"], Tps54202h),
(["reg_v12"], Lm2733),
(["reg_analog"], Ap2210),
(["reg_vref"], Ref30xx),
(["reg_vcontrol"], Lm2733),
(["control", "driver", "low_fet"], CustomFet),
(["control", "driver", "high_fet"], CustomFet),
(["control", "off_sw", "device"], Sn74lvc1g3157),
(["cap_conv", "cap"], JlcAluminumCapacitor),
(["control", "driver", "cap_in1", "cap"], JlcAluminumCapacitor),
(["spk", "conn"], JstPhKVertical),
(["control", "isense", "ranges[0]", "pwr_sw", "ic"], Tlp3545a), # higher current on 3A range
(["control", "driver", "res"], SeriesResistor), # needed for high power within a basic part
(["oled", "device", "conn"], Fpc050BottomFlip), # more compact connector, double-fold the FPC ribbon
],
class_refinements=[
(EspProgrammingHeader, EspProgrammingTc2030),
(TagConnect, TagConnectNonLegged), # really for initial flash / emergency upload only
(Opamp, Tlv9061), # higher precision opamps
(AnalogSwitch, Dg468),
(SolidStateRelay, Tlp170am),
(BananaSafetyJack, Ct3151),
(HalfBridgeDriver, Ncp3420),
(DirectionSwitch, Skrh),
(TestPoint, CompactKeystone5015),
(RotaryEncoder, Pec11s),
(Neopixel, Ws2812c_2020),
(RfConnector, UflConnector),
(UsbEsdDiode, Pgb102st23), # in stock
],
instance_values=[
(["mcu", "programming"], "uart-auto"),
(
["mcu", "pin_assigns"],
[
# left side
"speaker.sd=4",
"speaker.sck=5",
"speaker.ws=6",
"int_i2c.sda=7",
"int_i2c.scl=8",
"pd_int=9",
"buck_pwm=10",
"boost_pwm=11",
"vconv_sense=12",
# bottom side
"adc_cs=15",
"adc_spi.sck=17",
"adc_spi.mosi=18",
"adc_spi.miso=19",
"adc_clk=20",
"touch_duck=21",
"limit_source=22",
"limit_sink=23",
"dut0=24",
"dut1=25",
# right side
"rgb=31",
"fan=32",
"enc_sw=33",
"enc_b=34",
"enc_a=35",
"qwiic.sda=38",
"qwiic.scl=39",
"led=_GPIO0_STRAP",
],
),
(
["ioe_ui", "pin_assigns"],
[
"dir_a=4",
"dir_cen=5",
"dir_c=6",
"dir_d=7",
"dir_b=12",
"irange_1=9",
"irange_2=10",
"irange_0=11",
],
),
(
["ioe_ctl", "pin_assigns"],
[
"ramp=4",
"conv_en=6",
"conv_en_sense=7",
"low_gate=12",
"high_gate=11",
"off_0=9",
],