- A Logic Circuit Simulation Library in C++





(libLCS Example) 4-bit Counter using D-flipflops


The aim of this example is to build and simulate a 4-bit counter using 4 off-the-shelf D-flipflop modules provided in libLCS. The diagram for the circuit is as below. The bit sequence D3D2D1D0 in that order is the output of our counter circuit.

four_bit_counter.jpg

The code which implements the above circuit is as follows.

#include <iostream>
#include <lcs/bus.h>
#include <lcs/not.h>
#include <lcs/clock.h>
#include <lcs/changeMonitor.h>
#include <lcs/simul.h>
#include <lcs/dflipflop.h>

using namespace lcs;
using namespace std;

int main(void)
{
    // Declare single line busses for each node in the
    // circuit. The flipflop output nodes have been set
    // to zero to start with. The busses are initialised
    // with the default template parameter of 1.
    Bus<> q0(0), q1(0), q2(0), q3(0), d0, d1, d2, d3;

    // Initialise a clock object.
    Clock clk = Clock::getClock();

    // Initialise the NOT gates in the circuit. The NOT
    // gates are initialised with the default template
    // parameter corresponding to a propogation delay of
    // zero.
    Not<> n1(d0, q0), n2(d1, q1), n3(d2, q2), n4(d3, q3);

    // Initialise the 4 positive edge-triggered flipflops
    // using the default template parameters.
    DFlipFlop<> ff1(q0, d0, clk), ff2(q1, d1, q0), ff3(q2, d2, q1), ff4(q3, d3, q2);

    // Initialise a lcs::ChangeMonitor object to monitor
    // the output bit sequence of our counter circuit.
    ChangeMonitor<4> count((d0,d1,d2,d3), string("Count"), DUMP_ON);


    Simulation::setStopTime(4000); // Set the stop time.
    Simulation::start(); // Start the simulation.

    return 0;
}

When the above program is compiled and run, the following output is obtained.

At time: 0,     Count: 1111
At time: 100,   Count: 0000
At time: 300,   Count: 0001
At time: 500,   Count: 0010
At time: 700,   Count: 0011
At time: 900,   Count: 0100
At time: 1100,  Count: 0101
At time: 1300,  Count: 0110
At time: 1500,  Count: 0111
At time: 1700,  Count: 1000
At time: 1900,  Count: 1001
At time: 2100,  Count: 1010
At time: 2300,  Count: 1011
At time: 2500,  Count: 1100
At time: 2700,  Count: 1101
At time: 2900,  Count: 1110
At time: 3100,  Count: 1111
At time: 3300,  Count: 0000
At time: 3500,  Count: 0001
At time: 3700,  Count: 0010
At time: 3900,  Count: 0011

Below is the screenshot of the gtkwave plot of the generated VCD file.

4_bit_counter_using_dff.jpg

Copyright © 2006, 2007 Siva Chandra