main.js entry 1.9 KB
Copy main.js
SimKit.define({
title: "RC circuit: charging and discharging",
dt: 2e-5, speed: 0.05, height: 300,
params: {
V: { label: "Source voltage", unit: "V", min: 0, max: 12, value: 5, step: 0.1 },
R: { label: "Resistance", unit: "Ω", min: 100, max: 100000, value: 2000, log: true },
C: { label: "Capacitance", unit: "F", min: 1e-7, max: 1e-3, value: 1e-5, log: true },
f: { label: "Square-wave frequency", unit: "Hz", min: 1, max: 200, value: 10, log: true }
},
init(P, S) {
const c = new SimKit.Circuit();
const a = c.node(), b = c.node();
S.c = c; S.a = a; S.b = b;
S.src = c.V(a, 0, 0);
S.r = c.R(a, b, P.R);
S.cap = c.C(b, 0, P.C);
},
step(dt, P, S, t) {
S.src.value = Math.floor(t * P.f * 2) % 2 === 0 ? P.V : 0;
S.r.value = P.R;
S.cap.value = P.C;
S.c.step(dt);
},
draw(g, W, H, P, S) {
const sch = SimKit.sch, v = S.c.v, vm = Math.max(P.V, 1);
const col = n => SimKit.voltColor(v[n], vm);
const x0 = W * 0.14, x1 = W * 0.52, x2 = W * 0.86, yt = H * 0.3, yb = H * 0.8;
sch.wire(g, x0, yb, x2, yb, "#555");
sch.vsource(g, x0, yb, x0, yt, col(S.a));
sch.resistor(g, x0, yt, x1, yt, col(S.a));
sch.wire(g, x1, yt, x2, yt, col(S.b));
sch.capacitor(g, x2, yt, x2, yb, col(S.b));
sch.ground(g, (x0 + x2) / 2, yb);
sch.label(g, "R = " + SimKit.fmt(P.R, "Ω"), (x0 + x1) / 2, yt - 18);
sch.label(g, "C = " + SimKit.fmt(P.C, "F"), x2 + 46, (yt + yb) / 2);
sch.label(g, "τ = RC = " + SimKit.fmt(P.R * P.C, "s"), W / 2, H - 12, "#444");
sch.arrow(g, x0 + 30, yt + 16, x1 - 30, yt + 16, "#d03030");
sch.label(g, "i = " + SimKit.fmt(S.r.i, "A"), (x0 + x1) / 2, yt + 34, "#d03030");
},
scope: {
span: P => 4 / P.f, unit: "V",
traces: [
{ label: "Source", color: "#5aa0ff", get: S => S.c.v[S.a] },
{ label: "Capacitor", color: "#ff6060", get: S => S.c.v[S.b] }
]
}
});