"""cocotb tests for dds.sv: every output sample is compared bit-exactly with dds_model.py.""" from __future__ import annotations import random import cocotb from cocotb.clock import Clock from cocotb.triggers import ClockCycles, FallingEdge, ReadOnly, RisingEdge from dds_model import ACC_BITS, PHASE_BITS, dds_samples, phase_to_sample, quarter_lut, tuning_word LATENCY = 3 # cycles from the phase register to the sample output async def reset(dut) -> None: cocotb.start_soon(Clock(dut.clk, 10, unit="ns").start()) dut.rst.value = 1 dut.en.value = 0 dut.tuning_word.value = 0 await ClockCycles(dut.clk, 3) await FallingEdge(dut.clk) dut.rst.value = 0 @cocotb.test() async def constant_tone(dut) -> None: """A 1 MHz tone at a 100 MHz clock matches the model from the first valid sample.""" tw = tuning_word(1e6, 100e6) await reset(dut) dut.tuning_word.value = tw dut.en.value = 1 got: list[int] = [] while len(got) < 2000: await RisingEdge(dut.clk) await ReadOnly() if dut.sample_valid.value == 1: got.append(dut.sample.value.to_signed()) assert got == dds_samples(tw, len(got)) @cocotb.test() async def random_tuning_and_enable(dut) -> None: """Random tuning words and enable gaps: sample(t) is the table value of phase(t - 3).""" rng = random.Random(16) lut = quarter_lut() mask = (1 << ACC_BITS) - 1 await reset(dut) phases: list[int] = [] checked = 0 tw = 0 for cycle in range(3000): await FallingEdge(dut.clk) if cycle % 200 == 0: tw = rng.getrandbits(ACC_BITS) dut.tuning_word.value = tw en = int(rng.random() < 0.9) dut.en.value = en await RisingEdge(dut.clk) await ReadOnly() phase = dut.phase.value.to_unsigned() if phases: # the edge added the tuning word only if en was high assert phase == (phases[-1] + (tw if en else 0)) & mask phases.append(phase) if len(phases) > LATENCY and dut.sample_valid.value == 1: ref = phase_to_sample(phases[-1 - LATENCY] >> (ACC_BITS - PHASE_BITS), lut) assert dut.sample.value.to_signed() == ref, f"cycle {cycle}" checked += 1 assert checked > 2900