logicsimulator/components/jkflipflop.ts

70 lines
2.3 KiB
TypeScript

// J-K-Flip-Flop component for the LogicSimulator
// Copyright (C) 2022 Sascha Nitsch
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
interface JKFlipFlopParam extends BaseComponentParam {
default?: boolean;
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
class JKFlipFlop extends BaseComponent {
private j = false;
private k = false;
private CLK = true;
private oldCLK = true;
private q = false;
constructor(simulator: Simulator, id: string, param: JKFlipFlopParam = {}) {
super(simulator, id, param);
this.pins.set('j', new TriState(this, -30, -15));
this.pins.set('k', new TriState(this, -30, 15));
this.pins.set('clk', new TriState(this, -30, 0));
this.pins.set('q', new TriState(this, 30, -15));
this.pins.set('notq', new TriState(this, 30, 15));
if (param.default) this.q = param.default;
this.getPin('q').setBool(this.q);
this.getPin('notq').setBool(!this.q);
}
setup(canvas: SVGElement) {
super.doSetup('jkflipflop', canvas);
}
io() {
this.j = this.binary(this.getPin('j').getAndReset(), true);
this.k = this.binary(this.getPin('k').getAndReset(), true);
this.CLK = this.binary(this.getPin('clk').getAndReset(), true);
}
update(): boolean {
const oldstate = this.q;
if (this.oldCLK === false && this.CLK === true) {
if (this.j === true && this.k === true) {
this.q = !this.q;
} else {
if (this.j === true) {
this.q = true;
}
if (this.k === true) {
this.q = false;
}
}
}
this.getPin('q').setBool(this.q);
this.getPin('notq').setBool(this.q === false);
this.oldCLK = this.CLK;
return oldstate !== this.q;
}
}