Your First Circuit
In this tutorial, you’ll build a simple combinational circuit that performs basic logic operations.
What We’ll Build
Section titled “What We’ll Build”A circuit that takes two 1-bit inputs a and b and outputs:
and_out- a AND bor_out- a OR bxor_out- a XOR b
Step 1: Define the Interface
Section titled “Step 1: Define the Interface”First, we define what signals go in and out of our circuit:
module I = struct type 'a t = { a : 'a; b : 'a } [@@deriving hardcaml]end
module O = struct type 'a t = { and_out : 'a; or_out : 'a; xor_out : 'a } [@@deriving hardcaml]endThe [@@deriving hardcaml] attribute generates boilerplate code for us.
Step 2: Implement the Logic
Section titled “Step 2: Implement the Logic”Now we write the actual circuit logic:
let create _scope (i : _ I.t) : _ O.t = { and_out = i.a &: i.b ; or_out = i.a |: i.b ; xor_out = i.a ^: i.b }Hardcaml provides operators for common logic operations:
&:- bitwise AND|:- bitwise OR^:- bitwise XOR~:- bitwise NOT
Step 3: Write a Test
Section titled “Step 3: Write a Test”Let’s verify our circuit works with all input combinations:
let%expect_test "logic_gates" = let module Sim = Cyclesim.With_interface (Circuit.I) (Circuit.O) in let sim = Sim.create (Circuit.hierarchical (Scope.create ())) in let waves, sim = Waveform.create sim in let inputs = Cyclesim.inputs sim in
(* Test all combinations *) let test a b = inputs.a := Bits.of_int ~width:1 a; inputs.b := Bits.of_int ~width:1 b; Cyclesim.cycle sim in
test 0 0; test 0 1; test 1 0; test 1 1;
Waveform.expect waves; [%expect {| |}]Understanding the Test
Section titled “Understanding the Test”- Create a simulator from our circuit
- Wrap it with Waveform to capture signals
- Set inputs using
inputs.signal := Bits.of_int ... - Run cycles with
Cyclesim.cycle sim - Display results with
Waveform.expect waves
Try It
Section titled “Try It”Go to the IDE and:
- Replace the counter code with the logic gates implementation
- Click Run to see the waveform
- Verify AND, OR, XOR work correctly for all inputs
What’s Next?
Section titled “What’s Next?”- Waveforms - Deep dive into waveform visualization
- Nand2Tetris - Build logic gates from NAND