Home › Practice › Design Verification › cocotb first steps 3: Test a 4-bit counter with enable

cocotb first steps 3: Test a 4-bit counter with enable

EasycocotbPythonDV

To test a circuit over many clock cycles, keep a small Python model of what it should do, and compare after every cycle.

cocotb cheat sheet
await ClockCycles(dut.clk, 3)    # wait for 3 rising clock edges
await FallingEdge(dut.clk)       # then read outputs here (they are steady)
expected = (expected + 1) % 16   # your Python model of a 4-bit counter
for i in range(40):              # repeat for many cycles

Worked example. A counter that always counts: reset it, wait 3 cycles, expect 3.

import cocotb
from cocotb.clock import Clock
from cocotb.triggers import ClockCycles, FallingEdge

@cocotb.test()
async def test_count(dut):
    cocotb.start_soon(Clock(dut.clk, 10, units="ns").start())
    dut.rst.value = 1
    dut.en.value = 1
    await ClockCycles(dut.clk, 2)
    dut.rst.value = 0
    await ClockCycles(dut.clk, 3)
    await FallingEdge(dut.clk)
    assert int(dut.q.value) == 3

Your task. Test module counter4 (input clk, rst, en, output reg [3:0] q): it counts up on each rising edge while en is 1, holds when en is 0, wraps from 15 to 0, and resets to 0. Run at least 40 cycles, turn en off for some of them, and compare q with your model every cycle.

Solve in your browser →

No install and no sign-up needed. You write your answer in the editor and Nishkam checks it.

More in this track

← cocotb first steps 2: Test a D flip-flop with resetcocotb first steps 4: Random tests for an 8-bit adder →