3 ms·
I wrote a toy digital circuit simulator[1] as part of a personal "NAND to Tetris" style project. It has none of the bells and whistles of a full simulator but d
by olooney 6y ago
I wrote a toy digital circuit simulator[1] as part of a personal "NAND to Tetris" style project. It has none of the bells and whistles of a full simulator but does illustrate how you could write you own in only a few dozen lines of Python. It also has a kind of neat "declarative" syntax inspired by VHDL/Verilog where components (i.e., Verilog modules, VHDL entities) are defined as regular Python classes and describe their contents. For example, here's a half-adder component, which is comprised of a XOR gate and an AND gate:
class HalfAdder(Component):
def __init__(self, a, b, out=None, c=None):
super().__init__()
self.a = self.input(a)
self.b = self.input(b)
self.out = self.output(out)
self.c = self.output(c)
XOR(a=self.a, b=self.b, out=self.out)
AND(a=self.a, b=self.b, out=self.c)
having to declare each pin as input or output adds a lot of boilerplate; I was hoping to add a feature where input/output information could be declared using type annotations in the function signature itself. That would look something like:
class HalfAdder(Component):
def __init__(self,
a: input,
b: input,
out:output = None,
c:output = None):
super().__init__()
XOR(a=self.a, b=self.b, out=self.out)
AND(a=self.a, b=self.b, out=self.c)
which I think is starting to look pretty Verilog-ish, while still staying Pythonic.
[1]: https://github.com/olooney/circuit https://github.com/olooney/circuit