logicsimulator/components/rsflipflop.ts

65 lines
2.1 KiB
TypeScript

// R-S-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/>.
// eslint-disable-next-line @typescript-eslint/no-unused-vars
class RSFlipFlop extends BaseComponent {
private a = true;
private b = true;
private r = true;
private s = true;
private clk = true;
private oldclk = true;
private q = false;
constructor(simulator: Simulator, id: string, param: BaseComponentParam) {
super(simulator, id, param);
this.pins.set('r', new TriState(this, -30, -15));
this.pins.set('s', new TriState(this, -30, 15));
this.pins.set('clk', new TriState(this, -30, 0));
this.pins.set('q', new TriState(this, 30, -15));
this.getPin('q').setState(WireState.low);
this.pins.set('notq', new TriState(this, 30, 15));
this.getPin('notq').setState(WireState.high);
}
setup(canvas: SVGElement) {
super.doSetup('rsflipflop', canvas);
}
io() {
this.r = this.binary(this.getPin('r').getAndReset(), true);
this.s = this.binary(this.getPin('s').getAndReset(), true);
this.clk = this.binary(this.getPin('clk').getAndReset(), true);
}
update() {
const oldstate = this.q;
const rising = this.oldclk === false && this.clk === true;
if (rising) {
if (this.s === true) {
this.q = true;
}
if (this.r === true) {
this.q = false;
}
}
const newstate = this.q;
this.getPin('q').setBool(newstate);
this.getPin('notq').setBool(newstate === false);
this.oldclk = this.clk;
return oldstate !== newstate;
}
}