<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[CPU Simulation in JavaScript - Medium]]></title>
        <description><![CDATA[Collection of articles detailing the simulation of digital logic circuits and components to create a primitive but functional computer. - Medium]]></description>
        <link>https://medium.com/cpu-simulation-in-javascript?source=rss----51b7ca779c92---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>CPU Simulation in JavaScript - Medium</title>
            <link>https://medium.com/cpu-simulation-in-javascript?source=rss----51b7ca779c92---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 21:39:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/cpu-simulation-in-javascript" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Simulating Boolean Gates in JavaScript]]></title>
            <link>https://medium.com/cpu-simulation-in-javascript/simulating-boolean-gates-in-javascript-cc40e3d65478?source=rss----51b7ca779c92---4</link>
            <guid isPermaLink="false">https://medium.com/p/cc40e3d65478</guid>
            <category><![CDATA[simulator]]></category>
            <category><![CDATA[logic]]></category>
            <category><![CDATA[boolean]]></category>
            <dc:creator><![CDATA[Jon Trauntvein]]></dc:creator>
            <pubDate>Sun, 24 Nov 2024 20:58:59 GMT</pubDate>
            <atom:updated>2024-11-24T20:58:58.980Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*6wKpTYFgAnwqsJu28cDUOw.jpeg" /><figcaption>Turn of the Century Burroughs Adding Machine — Photo Taken by Author</figcaption></figure><p>Two years ago, I wrote an article in this publication called <a href="https://medium.com/cpu-simulation-in-javascript/logic-gates-a40e03c0a0f6">Logic Gates</a> in which I attempted a basic introduction of basic Boolean logic functions. I recall thinking that, having gotten that out of my hair, I could proceed at break-neck pace to the next article about registers. I have indeed made starts at that topic… five of them to be exact. Unfortunately, along the way, I realised that I needed a more rigorous set of tools to simulate the basic logic gates and the means of connecting them together. So this belated installment will be much more code heavy than the previous two and, in it, I will describes a collection of JavaScript classes that can be used to simulate the logical operations of these gates. In advance, I will mention that the full implementation of these classes can be found on <a href="https://github.com/jtrauntvein/basic-logic-gates">GitHub</a>. In addition, I have published this package to <a href="https://www.npmjs.com/package/jhtrauntvein-basic-logic-gates">NPM </a>so that these classes can be easily loaded and used in the various projects that I am going to have to create for these articles.</p><h4>Requirements</h4><p>Let’s start with a basic set of requirements. I want to:</p><ul><li>illustrate the basic operation of logic functions</li><li>be able to create objects that would represent individual gates and connect them with event handling functions</li><li>be able to place monitors (such as logging events to console or, much later, create visual real-time state indicators at various locations in composed device</li><li>be able to evaluate the current output of a gate at any time without changing that state.</li></ul><p>An astute observer may notice that there is no mention of operation efficiency in this list. It would be easy enough to implement all of the basic operations using JavaScript logic operators but that does very little to illustrate the basic functions of those operators. I have instead chosen to use truth table structures to map the state of device inputs to the device outputs. This approach will turn a very efficient JavaScript expression such as (A &amp;&amp; B) into a linear lookup in an array.</p><p>My design approach is to create a single base class that manages inputs, output event handlers, and logical evaluation using a provided truth table. I am going to call this base class TruthTableGate and, once it is defined, we will be able to derive all of the other basic Boolean functions in extended classes. Any logic device has at least one input channel and at least one output channel. In order to evaluate the logic function at any time, our emulator will maintain an array of Boolean values called inputs:</p><pre>class TruthTableGate {<br>  /**<br>   * specifies the collection of input channel values<br>   */<br>  #inputs;<br><br>  constructor() {<br>    this.#inputs = [ false, false ];<br>  }<br><br>  /**<br>   * sets the state of one of the input channels<br>   * @param {number} channel specifies the input channel number<br>   * @param {boolean} value specifies the value for the channel<br>  set(channel, value) {<br>    if(this.#inputs[channel] !== value) {<br>      this.#inputs[channel] = value;<br>      // @todo: we need to evaluate the logical function and report any change events<br>    }<br>  }<br>}</pre><p>We’ve already defined a constructor for this class as well as a set() method that is not yet complete. I was at first tempted to reevaluate the logical function any time that an input was set to any value but I soon learned that my event handlers could get called far more times than I wanted. Instead, we will only change the value of an input channel and evaluate the logical function. Before we start on the evaluate() function, let’s first consider what it will be operating on beyond the inputs that we have already defined.</p><h4>Truth Table Structure</h4><p>I wrote of truth tables in depth in the previous article but a short review might be in order. A truth table is an approach of defining a function where we list all of the possible combinations of inputs and the expected output(s) for each combination. In “normal” math, the size of the range and domain of most functions tends toward infinity. Fortunately, for the logical functions that we will consider here, we have a very limited set of inputs and outputs for each basic function. Thus the truth table is actually a viable approach. If I have have a logical function that expects one input, there are only two values that can be considered: true and false. Likewise, if I have a function that accepts two inputs, there are only four combinations that need be considered: false-false, false-true, true-false, true-true. With three inputs, such a function would needs to consider a total of eight combinations. In designing the structure for our truth table, it makes sense to create an array of something where each element of that array represents one of these combinations. For the sake of clarity, I have chosen make this an array of objects where each object has two properties:</p><ul><li>inputs (boolean[]): specifies the combination of input values for one row in the truth table. The size of this array must be equal to the size of the #inputs private member.</li><li>outputs (boolean[]): specifies the output value(s) associated with the combination of input values. For the basic functions that we will implement here, there is only one output for any given function but that will not always be the case and it feels right to establish the more general pattern now. Let’s construct a truth table array that describes the logical complement (NOT) function:</li></ul><pre>const not_truth_table = [<br>  { inputs: [ false], outputs: [ true ] },<br>  { inputs: [ true ], outputs: [ false ] }<br>];</pre><p>In addition, let’s consider the truth table for the logical AND function:</p><pre>const and_truth_table = [<br>  { inputs: [ false, false ], outputs: [ false ] },<br>  { inputs: [ false, true ], outputs: [ false ] },<br>  { inputs: [ true, false ], outputs: [ false ] },<br>  { inputs: [ true, true ], outputs: [ true ] }<br>];</pre><p>I hope that it is obvious that, by defining the structure in this way, we can write an algorithm that will map the current set of input values to the expected output because the truth table is the concise description of that logical function. Let’s continue building our TruthTableGate class by considering how the object can be initialised with this structure. Let’s also define a new method, evaluate(), that will map the given set of inputs to the expected output. This method will require no parameters and will produce a Boolean array:</p><pre>class TruthTableGate {<br>  #inputs<br>  #truth_table<br><br>  constructor(truth_table) {<br>    // we can construct the default set of inputs from the first row in the<br>    // truth table.  we make our own copy of that row so we don&#39;t risk<br>    // changing the truth table<br>    this.#truth_table = truth_table;<br>    this.#inputs = [ ...truth_table[0].inputs ];<br>  }<br><br>  evaluate() {<br>    const match = this.#truth_table.find((row) =&gt; {<br>      return row.inputs.every((value, channel) {<br>        return value === this.#inputs[channel];<br>      });<br>    });<br>    return [ ...match.outputs ];<br>  }<br>}</pre><p>Since the object is storing the last set state of inputs, this function can be called at any time without affecting the state of the object. The final mechanism that we need to build is a way of registering event handlers for output channels that can be invoked at any time that the gate state changes. We can do this by defining a callback function that can be registered with a specified output channel using the on() method. The gate object will maintain an array of callbacks for each channel. Let’s do so by redeclaring our class again with a modified constructor and on() method. Finally, we can modify the set() method so that it will call evaluate() each time an input is changed and will invoke the registered event handlers:</p><pre>class TruthTableGate {<br>  #inputs<br>  #outputs<br>  #truth_table<br><br>  constructor(truth_table) {<br>    this.#truth_table = truth_table;<br>    this.#inputs = [ ...truth_table[0].inputs ];<br>    // the outputs callback array will be an array of functions that <br>    // has the same length as the number of output channels.<br>    this.#outputs = truth_table[0].outputs.map(() =&gt; []);<br>  }<br><br>  on(handler, channel = 0) {<br>    this.#outputs[channel].push(handler);<br>  }<br><br>  set(value, channel {<br>    let output;<br>    if(this.#inputs[channel] !== value) {<br>      this.#inputs[channel] = value;<br>      output = this.evaluate();<br>      // for each output channel, we want to invoke all of the handlers that<br>      // are registered for that channel.  We will pass the output value,<br>      // output channel number, and a reference to this gate.<br>      this.#outputs.forEach((channel_outputs, out_channel) =&gt; {<br>        channel_outputs.forEach((handler) =&gt; {<br>          handler(output[out_channel], out_channel, this);<br>        }<br>      }<br>    }<br>    return output;<br>  }<br>}</pre><h4>Defining the Basic Gates</h4><p>Aside from a multitude of error checks that need to be made in the constructor as well as the set() and on() methods, this pretty much defines the class that we can use as a basis for any of the logical gates that can be described using a truth table. We can knock each of these out by defining a new class that extends class TruthTableGate and provides its own constructor that initialises the base class with its truth table:</p><pre>class NotGate extends TruthTableGate {<br>  constructor() {<br>    const truth_table = [<br>      { inputs: [ false ], outputs: [ true ] },<br>      { inputs: [ true ], outputs: [ false ] }<br>    };<br>    super(truth_table);<br>}<br><br>class AndGate extends TruthTableGate {<br>  constructor() {<br>    const truth_table = [<br>      { inputs: [ false, false ], outputs: [ false ] },<br>      { inputs: [ false, true ], outputs: [ false ] },<br>      { inputs: [ true, false ], outputs: [ false ] },<br>      { inputs: [ true, true ], outputs: [ true ] }<br>    ];<br>    super(truth_table);<br>  }<br>}<br><br>class OrGate extends TruthTableGate {<br>  constructor() {<br>    const truth_table = [<br>      { inputs: [ false, false ], outputs: [ false ] },<br>      { inputs: [ false, true ], outputs: [ true ] },<br>      { inputs: [ true, false ], outputs: [ true ] },<br>      { inputs: [ true, true ], outputs: [ true ] }<br>    ];<br>    super(truth_table);<br>  }<br>}<br><br>class NandGate extends TruthTableGate {<br>{<br>  constructor() {<br>    const truth_table = [<br>      { inputs: [ false, false ], outputs: [ true ] },<br>      { inputs: [ false, true ], outputs: [ true ] },<br>      { inputs: [ true, false ], outputs: [ true ] },<br>      { inputs: [ true, true ], outputs: [ false ] }<br>    ];<br>    super(truth_table);<br>  }<br>}<br><br>class NorGate extends TruthTableGate {<br>  constructor() {<br>    const truth_table = [<br>      { inputs: [ false, false ], outputs: [ true ] },<br>      { inputs: [ false, true ], outputs: [ false ] },<br>      { inputs: [ true, false ], outputs: [ false ] },<br>      { inputs: [ true, true ], outputs: [ false ] }<br>    ];<br>    super(truth_table);<br>  }<br>}<br><br>class XorGate extends TruthTableGate {<br>  constructor() {<br>    const truth_table = [<br>      { inputs: [ false, false ], outputs: [ false ] },<br>      { inputs: [ false, true ], outputs: [ true ] },<br>      { inputs: [ true, false ], outputs: [ true ] },<br>      { inputs: [ true, true ], outputs: [ false ] }<br>    ];<br>    super(truth_table);<br>  }<br>}</pre><h4>Putting It All Together: Composed Gates</h4><p>We have now declared all of the basic logical functions that are commonly used. With these basic building blocks, it is now possible to write programs that can create gate objects, register output callbacks, and set the value of inputs. The most powerful thing that we can do, however, is to use these building blocks to compose more complex logical functions. Let’s consider the case where we want a four input AND gate. We could, of course, build this as an extension of TruthTableGate but we can also choose to compose this more complex function from three basic AND gates:</p><pre>class AndGateFour {<br>  #input_layer<br>  #output_gate<br><br>  constructor() {<br>    this.#input_layer = [ new AndGate(), new AndGate() ];<br>    this.#output_gate = new AndGate();<br>    this.#input_layer.forEach((gate, gate_pos) =&gt; gate.set((value, channel) =&gt; {<br>      this.#output_gate.set(value, gate_pos);<br>    });<br>  }<br><br>  /**<br>   * define the set method in terms of the input layer gates<br>   */<br>  set(value, channel) {<br>    return this.#input_layer[channel * 2].set(value, math.Floor(channel / 2));<br>  }<br><br>  /**<br>   * define the on method in terms of the output gate<br>   */<br>  on(handler, channel = 0) {<br>    this.#output_gate.on(handler, 0);<br>  }<br><br>  /**<br>   * define evaluate in terms of the output gate<br>   */<br>  evaluate() {<br>    return this.#output_gate.evaluate();<br>  }<br>}</pre><p>Our composed gate does not extend class TruthTableGate but does define the same methods as that class. Because of JavaScript’s duck typing, this means that AndGateFour can be used in exactly the same way as any of the basic gates and can even be used to compose other gates as well. In this final sample, let’s create code that tests each of the possible input combinations for an AND gate:</p><pre>const gate = new AndGate();<br>let results;<br>gate.on((value) =&gt; console.log(`value changed to ${value}`));<br>gate.set(false, 0);<br>results = gate.set(false, 1);<br>assert(results[0] === false);<br>results = gate.set(true, 0);<br>assert(results[0] === false);<br>gate.set(true, 1);<br>results = gate.set(false, 0);<br>assert(results[0]) === false);<br>results = gate.set(true, 0);<br>assert(results[0] === true);<br></pre><h4>Conclusion</h4><p>All of the code that appears in our samples in this article can be found on GitHub at <a href="https://github.com/jtrauntvein/basic-logic-gates">https://github.com/jtrauntvein/basic-logic-gates</a>. The only real differences between the samples here and that on GitHub, is that I have implemented better error checking in constructors and other methods. It also has a collection of jest unit tests.</p><p>I know that this has been very code heavy and also repeats a lot of what is in my last article. With these tools in place, however, I am now prepared to begin to show how various CPU components can be emulated in JavaScript. In the next article, I am going to present computer memory and registers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc40e3d65478" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cpu-simulation-in-javascript/simulating-boolean-gates-in-javascript-cc40e3d65478">Simulating Boolean Gates in JavaScript</a> was originally published in <a href="https://medium.com/cpu-simulation-in-javascript">CPU Simulation in JavaScript</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Logic Gates]]></title>
            <link>https://medium.com/cpu-simulation-in-javascript/logic-gates-a40e03c0a0f6?source=rss----51b7ca779c92---4</link>
            <guid isPermaLink="false">https://medium.com/p/a40e03c0a0f6</guid>
            <category><![CDATA[cpu]]></category>
            <category><![CDATA[boolean-logic]]></category>
            <dc:creator><![CDATA[Jon Trauntvein]]></dc:creator>
            <pubDate>Sun, 04 Sep 2022 18:14:39 GMT</pubDate>
            <atom:updated>2022-09-04T18:14:39.312Z</atom:updated>
            <content:encoded><![CDATA[<h4>A Brief Explanation for Boolean Logic</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*smQ7OON28PjfvNf5.jpg" /><figcaption>Portrait of George Boole by an unknown author and provided by the Wikimedia Foundation</figcaption></figure><p>Last week, in an attempt to end my overly long hiatus from writing for this publication, I started down the path of describing the role of registers within a computer CPU. The use of registers is so fundamental to how a computer works, no explanation that did not include them would suffice. The further I struggled with that article, the more I realised that, before starting that, I owed it to any reader who is not overly familiar with computer architecture (the very audience that I hope to reach) to first pause and explain some fundamental binary operations. If you are already deeply familiar with this subject matter and are not sufficiently interested to laugh at my most egregious errors, I invite you to wait as I slowly grind out future installments.</p><h4>Boolean Logic</h4><p>Binary logic is also called Boolean logic in honour of George Boole who was an English mathematician, philosopher, and logician who lived between 1815 and 1864 and taught throughout his life at Queen’s College in Cork, Ireland (which also happens to be the ancestral home of my great grandmother’s family). Mr. Boole accomplished much during his career and much of his work was foundation for things like differential equations and algebraic logic systems. But he is most known and honoured by fellow geeks throughout the world as the man who first formalised a system of binary logic and gave us the rules and tools upon which so much of our digital worldwide society is founded. If you happen to be in a pub and are reading this, I would suggest that you raise your glass in his honour as you stare at your cell phone. Cheers George Boole!</p><p>Before I get into the grisly details of what is hopefully a rather short article, it is probably worth it to mention numbering systems. In our distant and long forgotten past, we became accustomed to keeping track of quantities such as the number of sheep one happened to own using the body part most suited to this chore: our fingers. As the field of mathematics evolved from these dim mists of the past, we found other ways to keep track of quantities such as notches on a stick or the knots on a string. This shared experience and, perhaps, evolution itself, has led us to use the decimal system. The term, Deca, is derived from both Latin and Greek roots to signify quantities of ten. This became more firmly ensconced when the symbols for numbers were formalised in medieval times in the Arabic and Hindu symbols for individual digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9. Of course, we need to have the language to express quantities that may be greater than nine and we do so by stringing digits together in increasing powers of ten. This is the decimal, or base 10, number system and many of us take it for granted that it is the ONLY numbering system.</p><p>Of course, evolution of species and languages is rich in quirks and off-shoots and expression of numbers is no different. For instance, the ancient Babylonians, one of the cultures in which mathematics began to be used and developed, did all of their accounting and figures in base 60 (sesegesimal?). The enduring legacy of this particular quirk can be found in the ways that we keep track of seconds, minutes, and hours (likely the bane of every computer programmer, myself included, who is saddled with the task of dealing with these awkward divisions). Some computers have been designed that use the decimal numbering system natively. The most famous of these is probably Babbage’s difference engine: a truly glorious arrangement of wheels, cogs, and levers all driven by a hand crank that was developed to help with calculations and was primarily used to print logarithmic tables for use by naval navigators. IBM also developed a system, called BCD (binary coded decimal) that had its heyday in the era of big iron computers, such the System 360, which were still in use while I was in nappies.</p><p>As entrenched as the decimal system in our daily lives is, its complexity is troublesome to use when designing either mechanical, electric, electronic, or even optic computer systems. The simplest numbering system, base 2 or binary (again a tribute to the Greek language; I feel like I am starting to sound like the father in the film, “My Big Fat Greek Wedding”!). The binary system, as it name implies, has only two digits: zero and one. These values are easily represented using relays, switches, and transistors and it is probably due to this ease of use that it has become dominant in the increasingly computer oriented society of today. That said, a number expressed in binary notation is still “just” a number that can be expressed in any other base system and convey the exact same information.</p><p>This is where the doubtlessly arcane and inaccessible works of George Fabulous Boole come in. Predecessors such as Leibniz had already worked out the mechanics of basic binary math operators (addition, subtraction, multiplication, &amp; division). As both a philosopher and a mathematician, George was drawn to the expression and manipulation of truth values where a symbol could represent either true or false. Borrowing from the language contributions such as “and” and “or” and their meanings in language, Boole set out to devise the rules by which these symbols could be combined and evaluated to produce novel outputs. For me, the most fascinating thing about a computer processor is in how it combines these logical expressions to create something that is truly greater than the sum of its component parts and seems almost life-like.</p><h4>Binary Logic Operators</h4><p>One of the fantastic features of binary logic is that most, if not all, of the proofs are so simple that they can simply be given in brute force (probably something that most mathematicians hate as they seem to delight in long and arcane proofs to the dismay of students everywhere; Oops, did I just say that part out loud?). There are only so many things that you can do with a set of just two digits which is exactly why binary lends itself so well to digital design. And so, with little more adieu, I present to you the most common set of Boolean operators. I will, by the way, make use of the diagrammatic symbols used in schematic diagrams. I will also provide the truth tables associated with these operators. A truth table consists of columns that represent each of a function’s inputs as well as outputs and rows that cover every possible combination of input values.</p><p>Those who may be familiar with counting in binary may recognise that these tables generally represent increasing integers from zero to the maximum number that can be represented by the number of inputs. This value can always be expressed of raising two by the number of inputs and subtracting one. For instance, two inputs can represent four numeric values: 00 (0 decimal), 01 (1d decimal), 10 (2 decimal), and 11 (3 decimal).</p><h4>NOT, Complement, or Inversion Operator</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/0*CYHvtkYVkJ7z65V2.png" /></figure><p>The NOT operator operates on a single binary input and produces a single binary output that is the logical complement to that input. The inversion operator in binary algebra has the same precedence as the sign operator in “normal” algebra.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*Ct1FR9ScJjene120-sc-Yg.png" /><figcaption>Truth table for the NOT or the inversion operator</figcaption></figure><h4>AND Operator</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/0*e_mWoRwOU1u4PYii.png" /><figcaption>Symbol for the logical AND operator</figcaption></figure><p>The AND operator works on two or more operands and produces a single output. The truth output of this operator will only be true when ALL of its input values are true. This operator has the same precedence as the “normal” multiplication operator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*Xkpr6TXtj1mJQwplE5ZBfA.png" /><figcaption>Truth table for the logical AND operator</figcaption></figure><p>If more inputs are added to the same gate, the rule still applies: all inputs must be true in order to produce an output that also evaluates as true. Any other combination will result in an output of false.</p><p>There is one more hopefully useful fact that I would like to add here. Just like traditional arithmetic operations can be chained (a + b + c), logical operations can also be chained in interesting ways. The results of two AND operations can be routed through another AND operation in an expression such as (A AND B) AND (C AND D). Here, since all of the operators are the same, we have just expressed a four input AND gate. Logical combinations such as this are commonly used in digital designs to be able to incorporate standard, inexpensive components.</p><h4>OR Operator</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/0*TvNICNw4TXjedZXd.png" /><figcaption>Symbol for the logical OR operator</figcaption></figure><p>The OR operator takes two or more input values and will return a true value when any of the inputs is asserted as true. In Boolean expressions, this operator has the same precedence as the arithmetic addition operator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*RvnNf3wfaUmOHp0oKrl0UQ.png" /><figcaption>Truth table for the logical OR operator</figcaption></figure><h4>Exclusive OR Operator</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/0*oPHrNYCEEyDJPtzy.png" /><figcaption>Symbol for the logical XOR operator</figcaption></figure><p>The exclusive OR operator is similar to the OR operator in that it evaluates two or more inputs and produces an output of true if any of the inputs are set to true. Where it differs from the OR operator, however, is that its output will be true only if exactly ONE input is set to true and the rest are false. We will become more familiar with this operator when the time comes to implement the ALU (Arithmetic Logic Unit) module for our CPU.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*kHxpnJIaWd3j0ywVstYNYQ.png" /><figcaption>Truth table for the XOR operator</figcaption></figure><h3>Emulating Boolean Operations in Javascript</h3><p>The basic Javascript language defines keywords, “true”, and “false” that are intended to convey a logical state values. Javascript also provides logical operators: and (“&amp;&amp;”),or (“||”), and complement (“!”); that operate on logic values and can be used in flow control statements such as “if”, “for”, and “while”. In addition to these features, Javascript also provides bitwise logical operators: and (&amp;), or (|), xor (“^”), and complement (“~”); that operate on the individual bits contained in integers.</p><p>I would expect that most, if not all, Javascript programmers are familiar with the logic level operators as these are essential for program flow control. Perhaps, many are less familiar with the bitwise operators as these are generally more restricted in their use.</p><p>The combination of these language features are sufficient to implement all of the gate type objects that our computer might need. However, as I started down the path of using these , I became increasingly uncomfortable with this and thought that a truth table driven design, although slower, provides a more clear representation of the actual operator implementation. In addition to this, I would like to introduce an event system that reports cases where the output of a gate has changed based upon that gate’s input values. Finally, I would like to expand logic gates to incorporate more than two inputs when the operator supports that and I want to allow these operator objects be easily chained together in order to create more complex logic “circuits”.</p><h4>Inverse Operator Implementation</h4><p>Let’s begin with the simplest operator, inversion or complement which has exactly one input and exactly one output although that output might be chained to the inputs of multiple gates or represent the output of the circuit:</p><pre>/**<br> * Defines a complement operator<br> */<br>function NotOperator() {<br>  this.value = false;<br>  this.output_handlers = [];<br>}</pre><pre>/**<br> * Adds the specified handler function to the collection of output handlers.<br> * @param handler Specifies an output handler for this operator object.<br> */<br>NotOperator.prototype.add_output_handler = function(handler) {<br>  if(Array.isArray(handler))<br>    this.output_handlers.push(...handler);<br>  else<br>    this.output_handlers.push(handler);<br>}</pre><pre>/**<br> * Triggers an input value for this gate.<br> *<br> * @param value Specifies the boolean value to operate upon.<br> */<br>NotOperator.prototype.set = function(value) {<br>  this.value = value;<br>  this.output_handlers.forEach((handler) =&gt; handler(!value, this));<br>}</pre><p>Basically, the fragment above defines a NotOperator class that maintains a copy of the last value set on its input as well as a collection of handler functions which will report a set event to zero or more outputs that will all receive the same value. Given this declaration, we can use it as shown in the following nonsensical example which inverts a value twice thereby returning the same value as was input:</p><pre>const inverter = new NotOperator();<br>const inverter_inverter = new NotOperator();</pre><pre>inverter.add_output_handler((value) =&gt; {<br>  console.log(`NOT(A) = ${value}`)<br>});<br>// chain the output of the first to the second<br>inverter.add_output_handler((value) =&gt; {<br>  inverter_inverter-&gt;set(value);<br>});<br>inverter_inverter.add_output_handler((value) =&gt; {<br>  console.log(`NOT(NOT(a)) = ${value}`);<br>});</pre><p>In this fragment, I hope to exemplify the methods by which logic operator objects can be chained and also how to handle changes in output in multiple ways (the first chains and the second prints output values)</p><h3>Conclusion</h3><p>These logical operations form the basis Boolean algebra but, just like with its relation, “regular old” algebra there is much more that can be learned when using these operations in symbolic form. In future articles, we will revisit these operations and include some of these more advanced concepts. However, if I have succeeded in piquing your interest and simply cannot wait for my intolerably slow rate of writing, there are many resources that are available. One free resource that I have used and that provides a fantastic amount of detail in an approachable form can be found at <a href="https://www.electronics-tutorials.ws/category/boolean">https://www.electronics-tutorials.ws/category/boolean</a>. I have little doubt that a few moments of searching in google can uncover other equally excellent tutorials.</p><p>There is one final note that I want to share with you. The power of a computer arises from how these basic operators can be chained and combined. So far as mathematical theory is concerned, these functions are extremely simple and, to me, there is a special magic and excitement in seeing the emergent behaviour that can come from these basic building blocks. I hope that you, dear reader, can share that excitement and that this modest and likely incomplete explanation can help to fuel that excitement. Thank you so much for joining me on this voyage of rediscovery and I hope to share again shortly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a40e03c0a0f6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cpu-simulation-in-javascript/logic-gates-a40e03c0a0f6">Logic Gates</a> was originally published in <a href="https://medium.com/cpu-simulation-in-javascript">CPU Simulation in JavaScript</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The System Clock]]></title>
            <link>https://medium.com/cpu-simulation-in-javascript/the-system-clock-197b13c7a08f?source=rss----51b7ca779c92---4</link>
            <guid isPermaLink="false">https://medium.com/p/197b13c7a08f</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[cpu-simulation]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Jon Trauntvein]]></dc:creator>
            <pubDate>Mon, 15 Mar 2021 00:05:36 GMT</pubDate>
            <atom:updated>2021-03-15T00:05:36.379Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Square wave superimposed on a clock face." src="https://cdn-images-1.medium.com/max/374/1*00xdLo4wBORxshpi45pvdA.png" /></figure><p>Computers are, in essence, a mathematical concept that, over the past couple hundred years or so, have been implemented in various physical mediums. Babbage designed his famous difference engine and analytical engine using gears and rods to be hand cranked or driven by steam engines. In the latter part of the 19th century, the vacuum tube was developed as an offshoot technology from the light bulb (this was supposedly an invention of Thomas Edison but, given his modus operandi, was likely noticed by an anonymous engineer in his invention laboratory). The vacuum tube, along with the electromechanical relay formed the basis of equally famous machines such as Turing’s bombe (designed to assist in the decryption of the German enigma codes), and the ENIAC (a general purpose computer designed primarily perform artillery ballistic calculations). The invention of the transistor in the late 1950s proved to be truly revolutionary in computer design and paved the way for purely electronic binary computers. Finally, the creation of integrated circuits and processors on a chip far smaller than you pinky fingernail paved the way for increased computing power at decreased cost both monetary and power consumption that have made computing devices ever more ubiquitous in practically every aspects in our lives. These implementations varied wildly in terms of architecture and design but they all had one thing in common: the need to synchronise the inputs and outputs of the various components that make up the computer.</p><p>Binary computers exist as a combination of logic gates and switches that hold the data (state) and perform the logical operations that make computing possible. There are measurable time delays required for a logic gate’s output to reflect the state of its output. The timing of these delays can vary from component to component although they are within the constraints published on that component’s spec sheet. To humans, these delays are fantastically small, on the order of nano or picoseconds, but a designer must take these delays into account. The time interval between clock pulses must be specified such that all the signals between components have reached a steady state in order for each instruction to execute reliably. In essence, the system clock works much as we envision the role of an orchestra conductor. Her hands provide the critical time signal that the dozens of players need in order to deliver their contributions in coordination with their peers.</p><p>So far, I have spoken about the system clock in the vaguest of terms. So let’s get more specific regarding the exact nature of the system clock. In an electronic computer, the system clock is an oscillator that is designed to produce a signal that alternates between asserted and and non-asserted state on a more or less predictable frequency. Quartz crystals, which have the amazing property of vibrating at their resonant frequency when subjected to an electric current, can be used to set the pace of these oscillations. Another method that I have used in the past is to use a 555 timer IC along with resistors and capacitors that control the frequency and and duty cycle of these signals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*6kDYObKteVFqc_XEx6wIhg.png" /><figcaption>A quartz crystal oscillator with the cap removed. The circular item on the left is the quartz crystal.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*EHFwFkIK-3Dwk_rDKT4Rdw.png" /><figcaption>A 555 timer IC configured as an astable oscillator in a bread board. This has long been my favourite because of its output capabilities and flexibility regarding voltage.</figcaption></figure><p>Devices such as those shown above, with some conditioning, can produce an oscillating voltage such as that shown in the following graph:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*GUg1h2XEWgo60H2R_gDXUQ.png" /><figcaption>A typical “square” wave clock signal time versus logic level</figcaption></figure><p>I have both simplified and distorted aspects of the signal. Typical clock signals will have much shorter rise and fall times relative the the clock interval. I have widened them here to make them more apparent. Also, if your were to examine such a signal on an oscilloscope (something that I have yet to convince myself that I can afford), you would also see signs of smaller, higher frequency sine wave oscillations, called ringing, whenever the signal transitions from one state to another. Apparently, with the exception of quantum effects, nature not only abhors a vacuum but, also, abrupt changes. In addition, there is always a certain amount of noise in the signal that, hopefully, is much less pronounced then the signal itself. These things are part of the burden of having to operate in the physical world. I think that, perhaps, the reason why I am drawn to software development is because it allows me to maintain the blissful illusion that everything that I can do is isolated from the “real world”! Anyway, back to the subject…</p><p>So, looking at the signal, you can observe that it spends approximately half of its time in a low (unasserted) state and roughly the other half of its time in a high (asserted) state. This circumstance, by the way, is called 50% duty cycle. Other signals might have a much narrower on time compared to off time even though the signal works at the same frequency. When dealing with digital circuits, many devices, such as memory, registers, &amp; etc. pay more attention to the areas of the signal where it transitions between asserted and unasserted states. These transitions are typically called “rising edge” (transition from unasserted to asserted) and falling edge (transition from asserted to unasserted). In my design of the virtual CPU, I plan on taking advantage of both transitions when I design modules of the computer.</p><p>On a circuit board, or within a system on a chip such as the ESP32, this clock signal is distributed to all of the components that make up the computer.</p><p>So… How do we go about simulating this signal within our program? Before answering that question with code snippets, let’s take a moment to consider the features that we want our clock module to have:</p><ul><li>I want to be able to control the frequency of the signal</li><li>I want to be able to manually take control of the clock so that I can watch what happens as my CPU executes instructions</li><li>I eventually want my CPU’s logic control unit to allow programmatic control of the clock including stopping it or pausing it at a break point.</li></ul><p>One of the built-in functions available within browser environment is a function called setInterval() which allows your program to specify an action that should occur on a regular interval. This is the perfect candidate to drive our clock signal. This function can be used like this:</p><pre>let timer_id = window.setInterval(() =&gt; {</pre><pre>   // @todo: do actions here<br>}, 3000);</pre><p>All of the code that I am going to discuss from here on out can be found at &lt;<a href="https://github.com/jtrauntvein/js-computersim">https://github.com/jtrauntvein/js-computersim</a>&gt;. This includes the basic logic modules as well as several pages that show the assemblies of the virtual CPU in various stages. For this article’s code, you can load the js-clock.html file into your browser once you have downloaded the code. Here is a fragment of the constructor for my VirtualClock module:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OlwJ-wNX0Jd4lBZuOo_D8A.png" /><figcaption>Constructor for the VirtualClock component.</figcaption></figure><p>This component has the following properties:</p><ul><li>interval (number): Specifies the configured clock interval (1/frequency) for the clock. The units for this value are in milliseconds.</li><li>auto_clock (boolean): Set to false if you want the program to take control of the clock events.</li><li>value (boolean): Set to true if the clock signal is asserted and false if the signal is not asserted.</li><li>rising_edge_clients (function[]): Specifies a collection of functions that will be called in sequence when the clock transitions from an unasserted state to an asserted state.</li><li>falling_edge_clients (function[]): Specifies a collection of functions that will be called in sequence when the clock transitions from an asserted to an unasserted state.</li></ul><p>The clock can be started by calling the start() method. This very simple method simply starts the timer using setInterval() which, in turn, will toggle the clock state each time that the call-back function is called. The clock can also be stopped by calling the stop() function which will clear out the interval set up by start(). Finally, when the clock is in manual mode, the clock can be forced to transition from one state to another (and all clients notified of this event) by calling the somewhat misnamed step() function (I would think of a full clock step would be one clock cycle. This function only performs half of the cycle).</p><p>That’s basically all that the module does. It runs a timer, transitions states, and calls registered client functions on these state transition events. Simples neh?</p><p>The only additional “minor” complication is that I want to be able to see the clock working in real time. After all, what’s a computer without blinkenlights or a story without pirates. To be honest, I spent about 80% of my time coding this part than I did in actually writing the clock module. I would encourage you to look at the source and to load the page into your browser. This is what you will (hopefully) see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6dk1pxAGLptOB9RF8_EUtg.png" /><figcaption>A screen shot of the system clock display</figcaption></figure><p>The code is written using Bootstrap and JQuery. I know that many will cringe at that (what no framework? why do you even need those things? even better: just how old are you?). However, the point of these articles is to discuss the the operation of the non-visible parts of the CPU and how they work. The display serves only to make those non-visible portions visible.</p><p>In the next article, I plan on introducing the topic of CPU registers as these play a critical role in any CPU architecture and they have a lot of fun little blinkenlights. Again, thanks for reading. I hope that I have somewhat held your interest. More importantly, I hope that you will take an opportunity to play and discover.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=197b13c7a08f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cpu-simulation-in-javascript/the-system-clock-197b13c7a08f">The System Clock</a> was originally published in <a href="https://medium.com/cpu-simulation-in-javascript">CPU Simulation in JavaScript</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Primitive JavaScript CPU: Introduction]]></title>
            <link>https://medium.com/cpu-simulation-in-javascript/the-primitive-javascript-cpu-introduction-34d3b9ef1a?source=rss----51b7ca779c92---4</link>
            <guid isPermaLink="false">https://medium.com/p/34d3b9ef1a</guid>
            <category><![CDATA[simulation]]></category>
            <category><![CDATA[lógic]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Jon Trauntvein]]></dc:creator>
            <pubDate>Fri, 29 May 2020 02:43:13 GMT</pubDate>
            <atom:updated>2020-05-29T02:43:39.348Z</atom:updated>
            <cc:license>http://creativecommons.org/publicdomain/zero/1.0/</cc:license>
            <content:encoded><![CDATA[<h3>Introduction</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/212/1*Y2Ps2AjkNreSZXI5MYFEcg.png" /><figcaption>Primitive flip flop forms the core of any memory cell</figcaption></figure><p>This article is an introduction to a series that I intend to write in which I attempt to recreate, within a framework of Browser executable JavaScript, a primitive but functional computer architecture that was largely inspired by a series of videos produced by Ben Eater (see <a href="https://eater.net/8bit">https://eater.net/8bit</a>). This series of videos is fantastic and I am immensely grateful to Mr. Eater for the work that he put into their production as well as his extremely clear descriptions of the functions of electrical and logic circuits.</p><p>Before I delve into the guts of this project, I wanted to spend a little bit of time explaining WHY this project is important to me and, I hope, might be of value to you, my reader.</p><p>I have been suffering for years with major depressive disorder and the recently induced isolation from the COVID19 pandemic has contributed greatly to my symptoms. I found myself losing track of the passage of time as I did my work within the same room in which I slept. I found myself wanting nothing more than to lie on my bed and to manically flip from one article to another on my phone. I was in this state when I came across one of the first of Mr. Eater’s videos on YouTube. I wound up binge watching the entire series. I doubt that a trained counselor would recommend this approach as a method of self-care, but, for me at least, this experience awoke some powerful memories of my first experiences in learning electronics first in high school and then, later on, in college.</p><p>I wanted to reproduce the machine that Ben made but felt constrained to do so as I lack space on a work bench that would allow me to leave a long term project scattered out for weeks at a time. I was also somewhat aghast when I learned that the power requirements for his computer approached 1.2 amps (although, I am sure, the numerous LEDs on the boards might account for a significant amount of this power). Finally, I realised that I could do something very much akin to what Ben created using JavaScript and a web browser. As I thought about this further, I came to the conclusion that such an environment could give rise many opportunities to tinker with processor architecture and that, further, the built-in browser developer tools with the console and the debugger could give me an opportunity to examine portions of the modules without having to necessarily write UI to display them.</p><p>With these thoughts, I further realised that exploring such an architecture would allow for exposure of these low level concepts to others like me who daily write programs to run on computers but that have come to take for granted the power of the abstractions on which we have built our professions. Thus, the idea to author a collection of articles along this line was born. My approach to this will attempt to mirror Ben Eater’s approach with hardware to some extent. I desire not to detract from his great work but to expand its audience.</p><p>Many years ago when I was a scout master, I was attempting to convince my oldest son to join us on a hike and camp out. He had no enthusiasm for such a project and, when I asked him why, he told me: “My ancestors already endured such things so that I wouldn’t have to”. While I was frustrated with him at the time, there was really no way to gainsay his logic. Nonetheless, I am continually drawn to study and experiment with “primitive technology” such as knots and lashings at least in part because it allows me to gain appreciation of the ingenuity of my forebears and also because I can see these things underpinning so much of the infrastructure around me. One hundred and fifty years later, our valley is still using the system of irrigation canals and ditches that was constructed throughout my valley home with shovels, horse drawn scrapers, and blasting powder.</p><p>Years ago, I read an article from E.W. Dijkstra entitled “Under the Spell of Leibnitz’s Dream” (see <a href="https://www.cs.utexas.edu/users/EWD/transcriptions/EWD12xx/EWD1298.html">https://www.cs.utexas.edu/users/EWD/transcriptions/EWD12xx/EWD1298.html</a>). Studying this history of my profession’s past leads me the understanding of how the machines and abstractions that I use daily are literally the fulfillment of the dreams and aspirations of such greats as Leibnitz, Babbage, Lovelace, Turing, Von Nueman, and so many others whose contributions have rightfully been immortalised and whose work form the fundamental foundations of computing. For me, exploring these roots by building a primitive computer helps me to better understand and to appreciate the greatness of their works and to partake in their dreams.</p><p>Finally, I would invite you to share with me the fierce joy that comes from witnessing and guiding the emerging behaviour that comes from combining basic modules. In the end, the whole is quite literally greater than the sum of its parts. As we do so, we can figuratively pry off the plastic and epoxy that hides the marvels of the processors and logic chips that make up our computers. We can strip away the aura of mystery about their operation and replace that with with the joy and satisfaction of a more sound understanding of the abstractions and machines we interact with daily. I hope, dear reader, to entice you to join me on this journey of rediscovery and to share with you an environment that will allow us to tinker and explore, to play and understand, in short, to relive those times in our lives when learning was a joy and to rekindle that joy today.</p><p>Thanks for listening!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34d3b9ef1a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cpu-simulation-in-javascript/the-primitive-javascript-cpu-introduction-34d3b9ef1a">The Primitive JavaScript CPU: Introduction</a> was originally published in <a href="https://medium.com/cpu-simulation-in-javascript">CPU Simulation in JavaScript</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>