5. SystemC Tutorial - AND Gate with Testbench

This example demonstrates a 2-input AND gate in SystemC with a complete testbench.

Implementation

#include "systemc.h"

// AND Gate Module
SC_MODULE(and_gate) {
  sc_in<bool> a, b;  // Two input ports
  sc_out<bool> c;    // Output port

  // AND gate functionality
  void and_gate_p() {
    c.write(a.read() & b.read());
  }

  // Constructor
  SC_CTOR(and_gate) {
    SC_METHOD(and_gate_p);
    sensitive << a << b;  // Trigger on either input
  }
};

// Testbench
int sc_main(int argc, char* argv[]) {
  // Signals
  sc_signal<bool> a, b, c;
  sc_trace_file *tf;

  // Instantiate and connect
  and_gate and1("and_gate_and1");
  and1.a(a);
  and1.b(b);
  and1.c(c);

  // Setup VCD tracing
  tf = sc_create_vcd_trace_file("and_gate");
  tf->set_time_unit(1, SC_NS);
  sc_trace(tf, a, "a");
  sc_trace(tf, b, "b");
  sc_trace(tf, c, "c");

  // Test all input combinations
  a = 0; b = 0; sc_start(1.0, SC_NS);  // 0&0 = 0
  a = 0; b = 1; sc_start(1.0, SC_NS);  // 0&1 = 0
  a = 1; b = 0; sc_start(1.0, SC_NS);  // 1&0 = 0
  a = 1; b = 1; sc_start(1.0, SC_NS);  // 1&1 = 1

  sc_stop();
  sc_close_vcd_trace_file(tf);
  cout << "Finished at time " << sc_time_stamp() << endl;

  return 0;
}

Truth Table

ABC (A&B)
000
010
100
111

This concludes the SystemC Tutorial series. You now have the foundation to build more complex SystemC designs!

Author
Mayur Kubavat
VLSI Design and Verification Engineer sharing knowledge about SystemVerilog, UVM, and hardware verification methodologies.

Comments (0)

Leave a Comment