4. SystemC Tutorial - OR Gate with Testbench

This example demonstrates a 2-input OR gate in SystemC with a complete testbench that exercises all input combinations.

Implementation

#include "systemc.h"

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

  // OR gate functionality
  void or_gate_p() {
    c.write(a.read() | b.read());
  }

  // Constructor
  SC_CTOR(or_gate) {
    SC_METHOD(or_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
  or_gate or1("or_gate_or1");
  or1.a(a);
  or1.b(b);
  or1.c(c);

  // Setup VCD tracing
  tf = sc_create_vcd_trace_file("or_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 = 1
  a = 1; b = 0; sc_start(1.0, SC_NS);  // 1|0 = 1
  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
011
101
111

Next: Continue to Part 5 - AND Gate

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

Comments (0)

Leave a Comment