DEV Community

Cover image for D-FlipFlip circuit model with signals and Dart
Daniel VH
Daniel VH

Posted on

D-FlipFlip circuit model with signals and Dart

One of my hobbies is to "re-invent" already done things, such as building a CPU simulator, create my own ISA and what-not.

While happily coding away on an instruction decoder with some simulated EEPROM chips, it hit me: why don't I use signals to simulate wiring between the components? I used them in Flutter and I need the same kind of reactivity here too. Guess what? Signals were originally intended for that. WHO KNEW?! :D

trivia: signals got their name after digital circuit modeling research in the 1970s1.

What is a D-FlipFlop

In a super-simple form, a D-FlipFlop samples an input pin when another signal (clock transitions from lo to hi2. When transition happens, the state of the input pin (hi or lo) is latched in and is output to q. The inverse of that latched in value is output to (q-bar).

Simulation in Dart

A couple of hours of playing around and I ended up with the following piece of code to simulate a D-FlipFlop:

class DFlipFlop {
  final clock = Input(false); // Input is a signal
  final input = Input(false);
  late bool _prevQ = input.value;

  late final q = computed<bool>(() {
    final clk = clock.value;
    if (clk) {
      // detect rising edge, sample input pin
      _prevQ = input.value;
    }
    return _prevQ;
  });

  late final qBar = computed<bool>(() => !q.value);
}
Enter fullscreen mode Exit fullscreen mode

That's it!

Essentially it boils down to the following core concepts:

  • input pins are signals
  • output pins are derived values (computed)
  • connections/wires between input and output pins are effects

For the full code sample, check out this gist:


Footnotes

1. https://youtu.be/Jp7QBjY5K34?t=171
2. lo and hi values are often "mistyped" to indicate logical high and low voltage levels

Top comments (1)

Collapse
 
daniel_vh profile image
Daniel VH

If anyone knows how to link headers within the same markdown document on dev.to, I would appreciate some tips :) Want to link the footnotes for superscripts. Thanks!