From eb7caaf2c51566cde01d90941d750023fb69037b Mon Sep 17 00:00:00 2001 From: Joppe Blondel Date: Sun, 19 Oct 2025 15:36:55 +0200 Subject: [PATCH 1/5] Added PLL/clock generator and SD RC model --- boards/mimas_v1/constraints.ucf | 3 + boards/mimas_v1/ip/clk_gen.xco | 226 ++++++++++++++++++++++++++++++ project.cfg | 35 +++-- rtl/arch/spartan-6/clk_gen.v | 148 +++++++++++++++++++ rtl/core/clk_gen.v | 12 ++ rtl/core/mul_const.v | 65 +++++++++ rtl/core/sigmadelta_rcmodel_q15.v | 47 +++++++ rtl/toplevel/top_generic.v | 10 +- rtl/util/rc_alpha_q15.vh | 70 +++++++++ sim/overrides/clk_gen.v | 15 ++ 10 files changed, 615 insertions(+), 16 deletions(-) create mode 100644 boards/mimas_v1/ip/clk_gen.xco create mode 100755 rtl/arch/spartan-6/clk_gen.v create mode 100644 rtl/core/clk_gen.v create mode 100644 rtl/core/mul_const.v create mode 100644 rtl/core/sigmadelta_rcmodel_q15.v create mode 100644 rtl/util/rc_alpha_q15.vh create mode 100644 sim/overrides/clk_gen.v diff --git a/boards/mimas_v1/constraints.ucf b/boards/mimas_v1/constraints.ucf index 534d841..612afd7 100644 --- a/boards/mimas_v1/constraints.ucf +++ b/boards/mimas_v1/constraints.ucf @@ -2,6 +2,9 @@ NET "aclk" LOC = P126; NET "aclk" TNM_NET = "SYS_CLK_PIN"; TIMESPEC TS_SYS_CLK_PIN = PERIOD "SYS_CLK_PIN" 10 ns HIGH 50 %; +# Generated clocks +NET "clk_15" TNM_NET = "SYS_CLK_15"; +TIMESPEC TS_SYS_CLK_15 = PERIOD "SYS_CLK_15" 13.334 ns HIGH 50%; # Boards button row NET "aresetn" LOC = P120; diff --git a/boards/mimas_v1/ip/clk_gen.xco b/boards/mimas_v1/ip/clk_gen.xco new file mode 100644 index 0000000..e917723 --- /dev/null +++ b/boards/mimas_v1/ip/clk_gen.xco @@ -0,0 +1,226 @@ +SELECT Clocking_Wizard xilinx.com:ip:clk_wiz:3.6 + +CSET calc_done=DONE +CSET clk_in_sel_port=CLK_IN_SEL +CSET clk_out1_port=CLK_OUT1 +CSET clk_out1_use_fine_ps_gui=false +CSET clk_out2_port=CLK_OUT2 +CSET clk_out2_use_fine_ps_gui=false +CSET clk_out3_port=CLK_OUT3 +CSET clk_out3_use_fine_ps_gui=false +CSET clk_out4_port=CLK_OUT4 +CSET clk_out4_use_fine_ps_gui=false +CSET clk_out5_port=CLK_OUT5 +CSET clk_out5_use_fine_ps_gui=false +CSET clk_out6_port=CLK_OUT6 +CSET clk_out6_use_fine_ps_gui=false +CSET clk_out7_port=CLK_OUT7 +CSET clk_out7_use_fine_ps_gui=false +CSET clk_valid_port=CLK_VALID +CSET clkfb_in_n_port=CLKFB_IN_N +CSET clkfb_in_p_port=CLKFB_IN_P +CSET clkfb_in_port=CLKFB_IN +CSET clkfb_in_signaling=SINGLE +CSET clkfb_out_n_port=CLKFB_OUT_N +CSET clkfb_out_p_port=CLKFB_OUT_P +CSET clkfb_out_port=CLKFB_OUT +CSET clkfb_stopped_port=CLKFB_STOPPED +CSET clkin1_jitter_ps=100.0 +CSET clkin1_ui_jitter=0.010 +CSET clkin2_jitter_ps=100.0 +CSET clkin2_ui_jitter=0.010 +CSET clkout1_drives=BUFG +CSET clkout1_requested_duty_cycle=50.000 +CSET clkout1_requested_out_freq=15.000 +CSET clkout1_requested_phase=0.000 +CSET clkout2_drives=BUFG +CSET clkout2_requested_duty_cycle=50.000 +CSET clkout2_requested_out_freq=100.000 +CSET clkout2_requested_phase=0.000 +CSET clkout2_used=false +CSET clkout3_drives=BUFG +CSET clkout3_requested_duty_cycle=50.000 +CSET clkout3_requested_out_freq=100.000 +CSET clkout3_requested_phase=0.000 +CSET clkout3_used=false +CSET clkout4_drives=BUFG +CSET clkout4_requested_duty_cycle=50.000 +CSET clkout4_requested_out_freq=100.000 +CSET clkout4_requested_phase=0.000 +CSET clkout4_used=false +CSET clkout5_drives=BUFG +CSET clkout5_requested_duty_cycle=50.000 +CSET clkout5_requested_out_freq=100.000 +CSET clkout5_requested_phase=0.000 +CSET clkout5_used=false +CSET clkout6_drives=BUFG +CSET clkout6_requested_duty_cycle=50.000 +CSET clkout6_requested_out_freq=100.000 +CSET clkout6_requested_phase=0.000 +CSET clkout6_used=false +CSET clkout7_drives=BUFG +CSET clkout7_requested_duty_cycle=50.000 +CSET clkout7_requested_out_freq=100.000 +CSET clkout7_requested_phase=0.000 +CSET clkout7_used=false +CSET clock_mgr_type=AUTO +CSET component_name=clk_gen +CSET daddr_port=DADDR +CSET dclk_port=DCLK +CSET dcm_clk_feedback=1X +CSET dcm_clk_out1_port=CLKFX +CSET dcm_clk_out2_port=CLK0 +CSET dcm_clk_out3_port=CLK0 +CSET dcm_clk_out4_port=CLK0 +CSET dcm_clk_out5_port=CLK0 +CSET dcm_clk_out6_port=CLK0 +CSET dcm_clkdv_divide=2.0 +CSET dcm_clkfx_divide=20 +CSET dcm_clkfx_multiply=3 +CSET dcm_clkgen_clk_out1_port=CLKFX +CSET dcm_clkgen_clk_out2_port=CLKFX +CSET dcm_clkgen_clk_out3_port=CLKFX +CSET dcm_clkgen_clkfx_divide=1 +CSET dcm_clkgen_clkfx_md_max=0.000 +CSET dcm_clkgen_clkfx_multiply=4 +CSET dcm_clkgen_clkfxdv_divide=2 +CSET dcm_clkgen_clkin_period=10.000 +CSET dcm_clkgen_notes=None +CSET dcm_clkgen_spread_spectrum=NONE +CSET dcm_clkgen_startup_wait=false +CSET dcm_clkin_divide_by_2=false +CSET dcm_clkin_period=10.000 +CSET dcm_clkout_phase_shift=NONE +CSET dcm_deskew_adjust=SYSTEM_SYNCHRONOUS +CSET dcm_notes=None +CSET dcm_phase_shift=0 +CSET dcm_pll_cascade=NONE +CSET dcm_startup_wait=false +CSET den_port=DEN +CSET din_port=DIN +CSET dout_port=DOUT +CSET drdy_port=DRDY +CSET dwe_port=DWE +CSET feedback_source=FDBK_AUTO +CSET in_freq_units=Units_MHz +CSET in_jitter_units=Units_UI +CSET input_clk_stopped_port=INPUT_CLK_STOPPED +CSET jitter_options=UI +CSET jitter_sel=No_Jitter +CSET locked_port=LOCKED +CSET mmcm_bandwidth=OPTIMIZED +CSET mmcm_clkfbout_mult_f=4.000 +CSET mmcm_clkfbout_phase=0.000 +CSET mmcm_clkfbout_use_fine_ps=false +CSET mmcm_clkin1_period=10.000 +CSET mmcm_clkin2_period=10.000 +CSET mmcm_clkout0_divide_f=4.000 +CSET mmcm_clkout0_duty_cycle=0.500 +CSET mmcm_clkout0_phase=0.000 +CSET mmcm_clkout0_use_fine_ps=false +CSET mmcm_clkout1_divide=1 +CSET mmcm_clkout1_duty_cycle=0.500 +CSET mmcm_clkout1_phase=0.000 +CSET mmcm_clkout1_use_fine_ps=false +CSET mmcm_clkout2_divide=1 +CSET mmcm_clkout2_duty_cycle=0.500 +CSET mmcm_clkout2_phase=0.000 +CSET mmcm_clkout2_use_fine_ps=false +CSET mmcm_clkout3_divide=1 +CSET mmcm_clkout3_duty_cycle=0.500 +CSET mmcm_clkout3_phase=0.000 +CSET mmcm_clkout3_use_fine_ps=false +CSET mmcm_clkout4_cascade=false +CSET mmcm_clkout4_divide=1 +CSET mmcm_clkout4_duty_cycle=0.500 +CSET mmcm_clkout4_phase=0.000 +CSET mmcm_clkout4_use_fine_ps=false +CSET mmcm_clkout5_divide=1 +CSET mmcm_clkout5_duty_cycle=0.500 +CSET mmcm_clkout5_phase=0.000 +CSET mmcm_clkout5_use_fine_ps=false +CSET mmcm_clkout6_divide=1 +CSET mmcm_clkout6_duty_cycle=0.500 +CSET mmcm_clkout6_phase=0.000 +CSET mmcm_clkout6_use_fine_ps=false +CSET mmcm_clock_hold=false +CSET mmcm_compensation=ZHOLD +CSET mmcm_divclk_divide=1 +CSET mmcm_notes=None +CSET mmcm_ref_jitter1=0.010 +CSET mmcm_ref_jitter2=0.010 +CSET mmcm_startup_wait=false +CSET num_out_clks=1 +CSET override_dcm=false +CSET override_dcm_clkgen=false +CSET override_mmcm=false +CSET override_pll=false +CSET platform=lin +CSET pll_bandwidth=OPTIMIZED +CSET pll_clk_feedback=CLKFBOUT +CSET pll_clkfbout_mult=4 +CSET pll_clkfbout_phase=0.000 +CSET pll_clkin_period=10.0 +CSET pll_clkout0_divide=128 +CSET pll_clkout0_duty_cycle=0.500 +CSET pll_clkout0_phase=0.000 +CSET pll_clkout1_divide=1 +CSET pll_clkout1_duty_cycle=0.500 +CSET pll_clkout1_phase=0.000 +CSET pll_clkout2_divide=1 +CSET pll_clkout2_duty_cycle=0.500 +CSET pll_clkout2_phase=0.000 +CSET pll_clkout3_divide=1 +CSET pll_clkout3_duty_cycle=0.500 +CSET pll_clkout3_phase=0.000 +CSET pll_clkout4_divide=1 +CSET pll_clkout4_duty_cycle=0.500 +CSET pll_clkout4_phase=0.000 +CSET pll_clkout5_divide=1 +CSET pll_clkout5_duty_cycle=0.500 +CSET pll_clkout5_phase=0.000 +CSET pll_compensation=SYSTEM_SYNCHRONOUS +CSET pll_divclk_divide=1 +CSET pll_notes=None +CSET pll_ref_jitter=0.010 +CSET power_down_port=POWER_DOWN +CSET prim_in_freq=100.000 +CSET prim_in_jitter=0.010 +CSET prim_source=Global_buffer +CSET primary_port=CLK_IN1 +CSET primitive=MMCM +CSET primtype_sel=PLL_BASE +CSET psclk_port=PSCLK +CSET psdone_port=PSDONE +CSET psen_port=PSEN +CSET psincdec_port=PSINCDEC +CSET relative_inclk=REL_PRIMARY +CSET reset_port=RESET +CSET secondary_in_freq=100.000 +CSET secondary_in_jitter=0.010 +CSET secondary_port=CLK_IN2 +CSET secondary_source=Single_ended_clock_capable_pin +CSET ss_mod_freq=250 +CSET ss_mode=CENTER_HIGH +CSET status_port=STATUS +CSET summary_strings=empty +CSET use_clk_valid=false +CSET use_clkfb_stopped=false +CSET use_dyn_phase_shift=false +CSET use_dyn_reconfig=false +CSET use_freeze=false +CSET use_freq_synth=true +CSET use_inclk_stopped=false +CSET use_inclk_switchover=false +CSET use_locked=false +CSET use_max_i_jitter=false +CSET use_min_o_jitter=false +CSET use_min_power=false +CSET use_phase_alignment=true +CSET use_power_down=false +CSET use_reset=false +CSET use_spread_spectrum=false +CSET use_spread_spectrum_1=false +CSET use_status=false + +GENERATE diff --git a/project.cfg b/project.cfg index 10ba9b3..439cbbf 100644 --- a/project.cfg +++ b/project.cfg @@ -12,38 +12,43 @@ pubkey = /home/joppe/.ssh/id_rsa.pub [target.synth] toolchain = ISE -# Toolchain settings family = spartan6 device = xc6slx9 package = tqg144 speedgrade = -2 toplevel = top_generic -xst_opts = -vlgincdir rtl -#ngdbuild_opts = -#map_opts = -#par_opts = -#netgen_opts = -#bitgen_opts = -#trce_opts = -# Files -#files_vhdl = +xst_opts = -vlgincdir rtl/util files_verilog = rtl/toplevel/top_generic.v rtl/core/nco_q15.v rtl/core/sigmadelta_sampler.v + rtl/core/sigmadelta_rcmodel_q15.v + rtl/core/mul_const.v rtl/arch/spartan-6/lvds_comparator.v + rtl/arch/spartan-6/clk_gen.v files_con = boards/mimas_v1/constraints.ucf files_other = rtl/util/conv.vh + rtl/util/rc_alpha_q15.vh + +[target.ip] +toolchain = ISE_IP +family = spartan6 +device = xc6slx9 +package = tqg144 +speedgrade = -2 +files_xco = boards/mimas_v1/ip/clk_gen.xco + [target.sim] toolchain = iverilog runtime = all toplevel = tb_nco_q15 -ivl_opts = -Irtl -#vvp_opts = -# Files -#files_sysverilog = +ivl_opts = -Irtl/util files_verilog = sim/tb/tb_nco_q15.v rtl/core/nco_q15.v rtl/core/lvds_comparator.v + rtl/core/sigmadelta_rcmodel_q15.v + rtl/core/mul_const.v sim/overrides/sigmadelta_sampler.v -files_other = rtl/util/conv.vh \ No newline at end of file + sim/overrides/clk_gen.v +files_other = rtl/util/conv.vh + rtl/util/rc_alpha_q15.vh \ No newline at end of file diff --git a/rtl/arch/spartan-6/clk_gen.v b/rtl/arch/spartan-6/clk_gen.v new file mode 100755 index 0000000..d70b97f --- /dev/null +++ b/rtl/arch/spartan-6/clk_gen.v @@ -0,0 +1,148 @@ +// file: clk_gen.v +// +// (c) Copyright 2008 - 2011 Xilinx, Inc. All rights reserved. +// +// This file contains confidential and proprietary information +// of Xilinx, Inc. and is protected under U.S. and +// international copyright and other intellectual property +// laws. +// +// DISCLAIMER +// This disclaimer is not a license and does not grant any +// rights to the materials distributed herewith. Except as +// otherwise provided in a valid license issued to you by +// Xilinx, and to the maximum extent permitted by applicable +// law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND +// WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES +// AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING +// BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON- +// INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and +// (2) Xilinx shall not be liable (whether in contract or tort, +// including negligence, or under any other theory of +// liability) for any loss or damage of any kind or nature +// related to, arising under or in connection with these +// materials, including for any direct, or any indirect, +// special, incidental, or consequential loss or damage +// (including loss of data, profits, goodwill, or any type of +// loss or damage suffered as a result of any action brought +// by a third party) even if such damage or loss was +// reasonably foreseeable or Xilinx had been advised of the +// possibility of the same. +// +// CRITICAL APPLICATIONS +// Xilinx products are not designed or intended to be fail- +// safe, or for use in any application requiring fail-safe +// performance, such as life-support or safety devices or +// systems, Class III medical devices, nuclear facilities, +// applications related to the deployment of airbags, or any +// other applications that could lead to death, personal +// injury, or severe property or environmental damage +// (individually and collectively, "Critical +// Applications"). Customer assumes the sole risk and +// liability of any use of Xilinx products in Critical +// Applications, subject only to applicable laws and +// regulations governing limitations on product liability. +// +// THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS +// PART OF THIS FILE AT ALL TIMES. +// +//---------------------------------------------------------------------------- +// User entered comments +//---------------------------------------------------------------------------- +// None +// +//---------------------------------------------------------------------------- +// "Output Output Phase Duty Pk-to-Pk Phase" +// "Clock Freq (MHz) (degrees) Cycle (%) Jitter (ps) Error (ps)" +//---------------------------------------------------------------------------- +// CLK_OUT1____15.000______0.000______50.0_____1533.333____150.000 +// +//---------------------------------------------------------------------------- +// "Input Clock Freq (MHz) Input Jitter (UI)" +//---------------------------------------------------------------------------- +// __primary_________100.000____________0.010 + +`timescale 1ps/1ps + +(* CORE_GENERATION_INFO = "clk_gen,clk_wiz_v3_6,{component_name=clk_gen,use_phase_alignment=true,use_min_o_jitter=false,use_max_i_jitter=false,use_dyn_phase_shift=false,use_inclk_switchover=false,use_dyn_reconfig=false,feedback_source=FDBK_AUTO,primtype_sel=DCM_SP,num_out_clk=1,clkin1_period=10.0,clkin2_period=10.0,use_power_down=false,use_reset=false,use_locked=false,use_inclk_stopped=false,use_status=false,use_freeze=false,use_clk_valid=false,feedback_type=SINGLE,clock_mgr_type=AUTO,manual_override=false}" *) +module clk_gen + (// Clock in ports + input clk_in, + // Clock out ports + output clk_out_15 + ); + + // Input buffering + //------------------------------------ + // BUFG clkin1_buf + // (.O (clkin1), + // .I (clk_in)); + + assign clkin1 = clk_in; + + // Clocking primitive + //------------------------------------ + + // Instantiation of the DCM primitive + // * Unused inputs are tied off + // * Unused outputs are labeled unused + wire psdone_unused; + wire locked_int; + wire [7:0] status_int; + wire clkfb; + wire clk0; + wire clkfx; + + DCM_SP + #(.CLKDV_DIVIDE (2.000), + .CLKFX_DIVIDE (20), + .CLKFX_MULTIPLY (3), + .CLKIN_DIVIDE_BY_2 ("FALSE"), + .CLKIN_PERIOD (10.0), + .CLKOUT_PHASE_SHIFT ("NONE"), + .CLK_FEEDBACK ("1X"), + .DESKEW_ADJUST ("SYSTEM_SYNCHRONOUS"), + .PHASE_SHIFT (0), + .STARTUP_WAIT ("FALSE")) + dcm_sp_inst + // Input clock + (.CLKIN (clkin1), + .CLKFB (clkfb), + // Output clocks + .CLK0 (clk0), + .CLK90 (), + .CLK180 (), + .CLK270 (), + .CLK2X (), + .CLK2X180 (), + .CLKFX (clkfx), + .CLKFX180 (), + .CLKDV (), + // Ports for dynamic phase shift + .PSCLK (1'b0), + .PSEN (1'b0), + .PSINCDEC (1'b0), + .PSDONE (), + // Other control and status signals + .LOCKED (locked_int), + .STATUS (status_int), + .RST (1'b0), + // Unused pin- tie low + .DSSEN (1'b0)); + + + // Output buffering + //----------------------------------- + BUFG clkf_buf + (.O (clkfb), + .I (clk0)); + + BUFG clkout1_buf + (.O (clk_out_15), + .I (clkfx)); + + + + +endmodule + diff --git a/rtl/core/clk_gen.v b/rtl/core/clk_gen.v new file mode 100644 index 0000000..5b647d7 --- /dev/null +++ b/rtl/core/clk_gen.v @@ -0,0 +1,12 @@ +`timescale 1ns/1ps + +// ============================================================================= +// Clock generator/PLL +// Simple pass through +// ============================================================================= +module clk_gen( + input wire clk_in, + output wire clk_out_15 +); + assign clk_out_15 = clk_in; +endmodule diff --git a/rtl/core/mul_const.v b/rtl/core/mul_const.v new file mode 100644 index 0000000..8205ee6 --- /dev/null +++ b/rtl/core/mul_const.v @@ -0,0 +1,65 @@ +`timescale 1ns/1ps + +// ============================================================================= +// Multiply a value by a constant +// Use a shift-add algorithm instead of a multiplier +// parameters: +// -- W : data width +// -- C : constant +// inout: +// -- x : input of width W +// -- y : output of widht 2W +// ============================================================================= +module mul_const_shiftadd#( + parameter integer W = 16, + parameter integer C = 16'sh7fff +)( + input wire signed [W-1:0] x, + output wire signed [2*W-1:0] y +); + // Absolute value and sign of C + localparam integer C_NEG = (C < 0) ? 1 : 0; + localparam integer C_ABS = (C < 0) ? -C : C; + + // Find MSB index of C_ABS to size the network + function integer msb_index; + input integer v; + integer i; + begin + msb_index = -1; + for (i = 0; i < 32; i = i + 1) + if (v >> i) msb_index = i; + end + endfunction + localparam integer I_MAX = (C_ABS == 0) ? 0 : msb_index(C_ABS); + + // Partial products + wire signed [W+I_MAX:0] part [0:I_MAX]; + genvar i; + generate + for (i = 0; i <= I_MAX; i = i + 1) begin : GEN_PARTS + assign part[i] = (C_ABS[i]) ? ($signed(x) <<< i) : { (W+I_MAX+1){1'b0} }; + end + endgenerate + + // Adder chain (simple; replace with tree if you want higher performance) + wire signed [W+I_MAX:0] sum [0:I_MAX]; + generate + if (I_MAX == 0) begin + assign sum[0] = part[0]; + end else begin + assign sum[0] = part[0]; + for (i = 1; i <= I_MAX; i = i + 1) begin : GEN_SUM + assign sum[i] = sum[i-1] + part[i]; + end + end + endgenerate + + // Apply sign of C + wire signed [W+I_MAX:0] mag = (I_MAX==0) ? part[0] : sum[I_MAX]; + wire signed [W+I_MAX:0] prod = C_NEG ? -mag : mag; + + // Stretch to fixed y width (truncate/extend as you wish outside) + assign y = prod; + +endmodule \ No newline at end of file diff --git a/rtl/core/sigmadelta_rcmodel_q15.v b/rtl/core/sigmadelta_rcmodel_q15.v new file mode 100644 index 0000000..9644ef8 --- /dev/null +++ b/rtl/core/sigmadelta_rcmodel_q15.v @@ -0,0 +1,47 @@ +`timescale 1ns/1ps + +// ============================================================================= +// RC model to convert sigma delta samples to Q1.15 +// Models the RC circuit on the outside of the FPGA +// Uses: Yn+1 = Yn + (sd - Yn)*(1-exp(-T/RC)) +// parameters: +// -- alpha_q15 : the 1-exp(-T/RC), defaults to R=3k3, C=220p and T=1/15MHz +// rounded to only use two bits (0b3b -> 0b00), the less +// bits the better +// inout: +// -- clk : input clock +// -- resetn : reset signal +// -- sd_sample : 1 bit sample output from sd sampler +// -- sample_q15 : output samples in q1.15 +// ============================================================================= +module sigmadelta_rcmodel_q15 #( + parameter integer alpha_q15 = 16'sh0b00 +)( + input wire clk, + input wire resetn, + input wire sd_sample, + output wire [15:0] sample_q15 +); + reg signed [15:0] y_q15; + wire signed [15:0] sd_q15 = sd_sample ? 16'sh7fff : 16'sh0000; + wire signed [15:0] e_q15 = sd_q15 - y_q15; + wire signed [31:0] prod_q30; + // Use shift-add algorithm for multiplication + mul_const_shiftadd #(.C(alpha_q15)) alpha_times_e (e_q15, prod_q30); + wire signed [15:0] y_next_q15 = y_q15 + (prod_q30>>>15); + + // clamp to [0, 0x7FFF] (keeps signal view tidy) + function signed [15:0] clamp01_q15(input signed [15:0] v); + if (v < 16'sd0000) clamp01_q15 = 16'sd0000; + else if (v > 16'sh7FFF) clamp01_q15 = 16'sh7FFF; + else clamp01_q15 = v; + endfunction + + always @(posedge clk or negedge resetn) begin + if (!resetn) y_q15 <= 16'sd0000; + else y_q15 <= clamp01_q15(y_next_q15); + end + + assign sample_q15 = y_q15; + +endmodule diff --git a/rtl/toplevel/top_generic.v b/rtl/toplevel/top_generic.v index 85d8d8d..c33ef9b 100644 --- a/rtl/toplevel/top_generic.v +++ b/rtl/toplevel/top_generic.v @@ -9,10 +9,18 @@ module top_generic( output wire[5:0] r2r ); - `include "util/conv.vh" + `include "conv.vh" assign led_green = 1'b0; assign led_red = 1'b0; + // Clocking + wire clk_100; + wire clk_15; + assign clk_100 = aclk; + clk_gen clocking( + .clk_in(clk_100), + .clk_out_15(clk_15) + ); reg [11:0] count; localparam integer DIV_MAX = 100_000 - 1; // 1 ms tick at 100 MHz diff --git a/rtl/util/rc_alpha_q15.vh b/rtl/util/rc_alpha_q15.vh new file mode 100644 index 0000000..5ab0e69 --- /dev/null +++ b/rtl/util/rc_alpha_q15.vh @@ -0,0 +1,70 @@ +// rc_alpha_q15.vh +// Plain Verilog-2001 constant function: R(ohm), C(pF), Fs(Hz) -> alpha_q15 (Q1.15) +// Uses fixed-point approximation: 1 - exp(-x) ≈ x - x^2/2 + x^3/6, where x = 1/(Fs*R*C) +// All integer math; suitable for elaboration-time constant folding (e.g., XST). + +`ifndef RC_ALPHA_Q15_VH +`define RC_ALPHA_Q15_VH + +function integer alpha_q15_from_rc; + input integer R_OHM; // resistance in ohms + input integer C_PF; // capacitance in picofarads + input integer FS_HZ; // sampling frequency in Hz + + integer N; // fractional bits for x (QN) + reg [127:0] num_1e12_sllN; + reg [127:0] denom_u; + reg [127:0] x_qN; // x in QN + reg [255:0] x2; // x^2 in Q(2N) + reg [383:0] x3; // x^3 in Q(3N) + + integer term1_q15; // x -> Q1.15 + integer term2_q15; // x^2/2 -> Q1.15 + integer term3_q15; // x^3/6 -> Q1.15 + integer acc; // accumulator for result +begin + // Choose QN for x. N=24 is a good balance for accuracy/width. + N = 24; + + // x = 1 / (Fs * R * C) with C in pF ==> x = 1e12 / (Fs * R * C_PF) + // x_qN = round( x * 2^N ) = round( (1e12 << N) / denom ) + num_1e12_sllN = 128'd1000000000000 << N; + + // denom = Fs * R * C_PF (fits in 64..96 bits for typical values) + denom_u = 0; + denom_u = denom_u + FS_HZ[127:0]; + denom_u = denom_u * R_OHM[127:0]; + denom_u = denom_u * C_PF[127:0]; + + // rounded divide for x_qN + x_qN = (num_1e12_sllN + (denom_u >> 1)) / denom_u; + + // Powers + x2 = x_qN * x_qN; // 128x128 -> 256 + x3 = x2 * x_qN; // 256x128 -> 384 + + // term1 = x -> shift from QN to Q15 + term1_q15 = (x_qN >> (N - 15)) & 16'hFFFF; + + // term2 = x^2 / 2 -> shift from Q(2N) to Q15 and divide by 2 + term2_q15 = (x2 >> (2*N - 15 + 1)) & 16'hFFFF; + + // term3 = x^3 / 6 -> shift from Q(3N) to Q15, then divide by 6 (rounded) + begin : gen_term3 + reg [383:0] tmp_q15_wide; + reg [383:0] tmp_div6; + tmp_q15_wide = (x3 >> (3*N - 15)); + tmp_div6 = (tmp_q15_wide + 6'd3) / 6; // +3 for rounding + term3_q15 = tmp_div6[15:0]; + end + + // Combine: alpha_q15 = x - x^2/2 + x^3/6 ; clamp to [0, 0x7FFF] + acc = term1_q15 - term2_q15 + term3_q15; + if (acc < 0) acc = 0; + else if (acc > 16'h7FFF) acc = 16'h7FFF; + + alpha_q15_from_rc = acc; +end +endfunction + +`endif diff --git a/sim/overrides/clk_gen.v b/sim/overrides/clk_gen.v new file mode 100644 index 0000000..3087fc4 --- /dev/null +++ b/sim/overrides/clk_gen.v @@ -0,0 +1,15 @@ +`timescale 1ns/1ps + +// ============================================================================= +// Clock generator/PLL +// Simple direct generation for simulation purposes +// ============================================================================= +module clk_gen( + input wire clk_in, + output wire clk_out_15 +); + reg clk_15; + initial clk_15 <= 1'b0; + always #6.667 clk_15 <= !clk_15; + assign clk_out_15 = clk_15; +endmodule From b2858ac5eea0571ed3309c91c19a05dc6f5510a1 Mon Sep 17 00:00:00 2001 From: Joppe Blondel Date: Sun, 19 Oct 2025 16:18:40 +0200 Subject: [PATCH 2/5] Added mul tb and fixed --- project.cfg | 4 +- rtl/core/mul_const.v | 34 +++++++++------ rtl/core/sigmadelta_rcmodel_q15.v | 5 ++- sim/tb/tb_mul_const.v | 72 +++++++++++++++++++++++++++++++ sim/tb/tb_sigmadelta.v | 38 ++++++++++++++++ 5 files changed, 136 insertions(+), 17 deletions(-) create mode 100644 sim/tb/tb_mul_const.v create mode 100644 sim/tb/tb_sigmadelta.v diff --git a/project.cfg b/project.cfg index 439cbbf..2f0e66b 100644 --- a/project.cfg +++ b/project.cfg @@ -41,9 +41,11 @@ files_xco = boards/mimas_v1/ip/clk_gen.xco [target.sim] toolchain = iverilog runtime = all -toplevel = tb_nco_q15 +toplevel = tb_sigmadelta ivl_opts = -Irtl/util files_verilog = sim/tb/tb_nco_q15.v + sim/tb/tb_sigmadelta.v + sim/tb/tb_mul_const.v rtl/core/nco_q15.v rtl/core/lvds_comparator.v rtl/core/sigmadelta_rcmodel_q15.v diff --git a/rtl/core/mul_const.v b/rtl/core/mul_const.v index 8205ee6..06dc8ce 100644 --- a/rtl/core/mul_const.v +++ b/rtl/core/mul_const.v @@ -17,11 +17,11 @@ module mul_const_shiftadd#( input wire signed [W-1:0] x, output wire signed [2*W-1:0] y ); - // Absolute value and sign of C - localparam integer C_NEG = (C < 0) ? 1 : 0; - localparam integer C_ABS = (C < 0) ? -C : C; + // Sign and magnitude of constant + localparam integer C_NEG = (C < 0) ? 1 : 0; + localparam integer C_ABS = (C < 0) ? -C : C; - // Find MSB index of C_ABS to size the network + // MSB index of |C| (0-based). Keeps network minimal. function integer msb_index; input integer v; integer i; @@ -31,19 +31,26 @@ module mul_const_shiftadd#( if (v >> i) msb_index = i; end endfunction + localparam integer I_MAX = (C_ABS == 0) ? 0 : msb_index(C_ABS); - // Partial products - wire signed [W+I_MAX:0] part [0:I_MAX]; + // Width big enough for the largest partial product: W bits shifted by I_MAX + localparam integer PPW = W + I_MAX + 1; + + // Pre-extend x to PPW so shifts don’t truncate high/sign bits + wire signed [PPW-1:0] x_ext = {{(PPW-W){x[W-1]}}, x}; + + // Partial products (only where C’s bit is 1) + wire signed [PPW-1:0] part [0:I_MAX]; genvar i; generate for (i = 0; i <= I_MAX; i = i + 1) begin : GEN_PARTS - assign part[i] = (C_ABS[i]) ? ($signed(x) <<< i) : { (W+I_MAX+1){1'b0} }; + assign part[i] = C_ABS[i] ? (x_ext <<< i) : {PPW{1'b0}}; end endgenerate - // Adder chain (simple; replace with tree if you want higher performance) - wire signed [W+I_MAX:0] sum [0:I_MAX]; + // Adder chain (you can replace with a balanced tree for speed) + wire signed [PPW-1:0] sum [0:I_MAX]; generate if (I_MAX == 0) begin assign sum[0] = part[0]; @@ -56,10 +63,9 @@ module mul_const_shiftadd#( endgenerate // Apply sign of C - wire signed [W+I_MAX:0] mag = (I_MAX==0) ? part[0] : sum[I_MAX]; - wire signed [W+I_MAX:0] prod = C_NEG ? -mag : mag; - - // Stretch to fixed y width (truncate/extend as you wish outside) - assign y = prod; + wire signed [PPW-1:0] mag = (I_MAX == 0) ? part[0] : sum[I_MAX]; + wire signed [PPW-1:0] prod = C_NEG ? -mag : mag; + // Stretch/extend to 2W result width + assign y = {{((2*W)-PPW){prod[PPW-1]}}, prod}; endmodule \ No newline at end of file diff --git a/rtl/core/sigmadelta_rcmodel_q15.v b/rtl/core/sigmadelta_rcmodel_q15.v index 9644ef8..7b737c8 100644 --- a/rtl/core/sigmadelta_rcmodel_q15.v +++ b/rtl/core/sigmadelta_rcmodel_q15.v @@ -12,7 +12,7 @@ // -- clk : input clock // -- resetn : reset signal // -- sd_sample : 1 bit sample output from sd sampler -// -- sample_q15 : output samples in q1.15 +// -- sample_q15 : output samples in q.15 // ============================================================================= module sigmadelta_rcmodel_q15 #( parameter integer alpha_q15 = 16'sh0b00 @@ -25,9 +25,10 @@ module sigmadelta_rcmodel_q15 #( reg signed [15:0] y_q15; wire signed [15:0] sd_q15 = sd_sample ? 16'sh7fff : 16'sh0000; wire signed [15:0] e_q15 = sd_q15 - y_q15; + // wire signed [31:0] prod_q30 = $signed(e_q15) * $signed(alpha_q15); wire signed [31:0] prod_q30; // Use shift-add algorithm for multiplication - mul_const_shiftadd #(.C(alpha_q15)) alpha_times_e (e_q15, prod_q30); + mul_const_shiftadd #(.C($signed(alpha_q15))) alpha_times_e ($signed(e_q15), prod_q30); wire signed [15:0] y_next_q15 = y_q15 + (prod_q30>>>15); // clamp to [0, 0x7FFF] (keeps signal view tidy) diff --git a/sim/tb/tb_mul_const.v b/sim/tb/tb_mul_const.v new file mode 100644 index 0000000..2f9028b --- /dev/null +++ b/sim/tb/tb_mul_const.v @@ -0,0 +1,72 @@ +`timescale 1ns/1ps + +module tb_mul_const(); + + // ------------------------------------------------------------------------- + // Parameters + // ------------------------------------------------------------------------- + localparam integer W = 16; + localparam integer C = 16'sh0B3B; // alpha_q15 ≈ 0.08774 + localparam signed [W-1:0] C_S = C[W-1:0]; + + // ------------------------------------------------------------------------- + // DUT I/O + // ------------------------------------------------------------------------- + reg signed [W-1:0] x; + wire signed [(2*W)-1:0] y; + + // Instantiate DUT + mul_const_shiftadd #( + .W(W), + .C(C) + ) dut ( + .x(x), + .y(y) + ); + + // ------------------------------------------------------------------------- + // Reference and verification + // ------------------------------------------------------------------------- + reg signed [(2*W)-1:0] expected; + integer i; + integer errors; + + initial begin + $display("------------------------------------------------------"); + $display(" Testbench: mul_const_shiftadd"); + $display(" W = %0d, C = %0d (0x%0h)", W, $signed(C_S), C_S); + $display("------------------------------------------------------"); + + errors = 0; + + // Exhaustively test all 16-bit signed values + for (i = -(1<<(W-1)); i < (1<<(W-1)); i = i + 1) begin + x = i; + #1; // let combinational logic settle + + expected = $signed(x) * $signed(C_S); + + if (y !== expected) begin + $display("FAIL: x=%6d (0x%04h) * C=%6d -> y=%10d (0x%08h), expected=%10d (0x%08h)", + $signed(x), x, $signed(C_S), + $signed(y), y, $signed(expected), expected); + errors = errors + 1; + // Uncomment next line if you want to stop on first mismatch + // $stop; + end + + // progress message every 4096 iterations + if (((i + (1<<(W-1))) % 4096) == 0) + $display("Progress: %5d / %5d values tested...", + i + (1<<(W-1)), (1< Date: Sun, 19 Oct 2025 17:02:29 +0200 Subject: [PATCH 3/5] Added K IIR lpf filter --- project.cfg | 2 + rtl/core/lpf_iir_q15_k.v | 64 +++++++++++++++++++ .../bode_compare_Ks_lpf_iir_q15_k.py | 42 ++++++++++++ sim/tb/tb_sigmadelta.v | 8 ++- 4 files changed, 115 insertions(+), 1 deletion(-) create mode 100644 rtl/core/lpf_iir_q15_k.v create mode 100644 scripts/filter_design/bode_compare_Ks_lpf_iir_q15_k.py diff --git a/project.cfg b/project.cfg index 2f0e66b..53bc7fc 100644 --- a/project.cfg +++ b/project.cfg @@ -23,6 +23,7 @@ files_verilog = rtl/toplevel/top_generic.v rtl/core/sigmadelta_sampler.v rtl/core/sigmadelta_rcmodel_q15.v rtl/core/mul_const.v + rtl/core/lpf_iir_q15_k.v rtl/arch/spartan-6/lvds_comparator.v rtl/arch/spartan-6/clk_gen.v files_con = boards/mimas_v1/constraints.ucf @@ -50,6 +51,7 @@ files_verilog = sim/tb/tb_nco_q15.v rtl/core/lvds_comparator.v rtl/core/sigmadelta_rcmodel_q15.v rtl/core/mul_const.v + rtl/core/lpf_iir_q15_k.v sim/overrides/sigmadelta_sampler.v sim/overrides/clk_gen.v files_other = rtl/util/conv.vh diff --git a/rtl/core/lpf_iir_q15_k.v b/rtl/core/lpf_iir_q15_k.v new file mode 100644 index 0000000..346124f --- /dev/null +++ b/rtl/core/lpf_iir_q15_k.v @@ -0,0 +1,64 @@ +`timescale 1ns/1ps + +// ============================================================================= +// Low-Pass IIR Filter (Q1.15) +// Simple first-order infinite impulse response filter, equivalent to an +// exponential moving average. Provides an adjustable smoothing factor based +// on parameter K. +// +// Implements: +// Y[n+1] = Y[n] + (X[n] - Y[n]) / 2^K +// +// This is a purely digital one-pole low-pass filter whose time constant +// approximates that of an analog RC filter, where alpha = 1 / 2^K. +// +// The larger K is, the slower the filter responds (stronger smoothing). +// The smaller K is, the faster it reacts to changes. +// +// parameters: +// -- K : filter shift factor (integer, 4..14 typical) +// cutoff frequency ≈ Fs / (2π * 2^K) +// larger K → lower cutoff +// +// inout: +// -- clk : input clock +// -- rst_n : active-low reset +// -- x_q15 : signed 16-bit Q1.15 input sample (e.g., 0..0x7FFF) +// -- y_q15 : signed 16-bit Q1.15 filtered output +// +// Notes: +// - The arithmetic right shift implements division by 2^K. +// - Internal arithmetic is Q1.15 fixed-point with saturation +// to [0, 0x7FFF] (for non-negative signals). +// - Useful for smoothing noisy ADC / sigma-delta data streams +// or modeling an RC envelope follower. +// ============================================================================= +module lpf_iir_q15_k #( + parameter integer K = 10 // try 8..12; bigger = more smoothing +)( + input wire clk, + input wire rst_n, + input wire signed [15:0] x_q15, // Q1.15 input (e.g., 0..0x7FFF) + output reg signed [15:0] y_q15 // Q1.15 output +); + wire signed [15:0] e_q15 = x_q15 - y_q15; + wire signed [15:0] delta_q15 = e_q15 >>> K; // arithmetic shift + wire signed [15:0] y_next = y_q15 + delta_q15; // clamp to [0, 0x7FFF] (handy if your signal is non-negative) + + function signed [15:0] clamp01; + input signed [15:0] v; + begin + if (v < 16'sd0) + clamp01 = 16'sd0; + else if (v > 16'sh7FFF) + clamp01 = 16'sh7FFF; + else + clamp01 = v; + end + endfunction + + always @(posedge clk or negedge rst_n) begin + if (!rst_n) y_q15 <= 16'sd0; + else y_q15 <= clamp01(y_next); + end +endmodule diff --git a/scripts/filter_design/bode_compare_Ks_lpf_iir_q15_k.py b/scripts/filter_design/bode_compare_Ks_lpf_iir_q15_k.py new file mode 100644 index 0000000..c34b51c --- /dev/null +++ b/scripts/filter_design/bode_compare_Ks_lpf_iir_q15_k.py @@ -0,0 +1,42 @@ +import numpy as np +import matplotlib.pyplot as plt + +def bode_mag_phase(Fs, K, n=4096): + """Return frequency, magnitude (dB), and phase (deg) for 1-pole IIR.""" + alpha = 2.0 ** (-K) + a = 1.0 - alpha + w = np.linspace(0, np.pi, n) + ejw = np.exp(-1j * w) + H = alpha / (1 - a * ejw) + f = (w / (2 * np.pi)) * Fs + mag_db = 20 * np.log10(np.abs(H) + 1e-20) + phase_deg = np.unwrap(np.angle(H)) * 180 / np.pi + return f, mag_db, phase_deg + +if __name__ == "__main__": + Fs = 15e6 + Ks = [10, 8, 6, 4] + + fig, (ax_mag, ax_phase) = plt.subplots(2, 1, sharex=True, figsize=(8, 6)) + + for K in Ks: + f, mag_db, phase_deg = bode_mag_phase(Fs, K, n=32768) + ax_mag.semilogx(f, mag_db, label=f"K={K}") + ax_phase.semilogx(f, phase_deg, label=f"K={K}") + + # ---- Styling ---- + f_max = 40e3 # 40 kHz + ax_mag.set_xlim(10, f_max) # start at 10 Hz for nicer log scaling + ax_mag.set_ylim(-60, 1) + ax_mag.set_title("Ideal Bode Response vs K") + ax_mag.set_ylabel("Magnitude [dB]") + ax_mag.grid(True, which='both') + ax_mag.legend() + + ax_phase.set_xlabel("Frequency [Hz]") + ax_phase.set_ylabel("Phase [deg]") + ax_phase.grid(True, which='both') + ax_phase.set_xlim(10, f_max) + + plt.tight_layout() + plt.show() \ No newline at end of file diff --git a/sim/tb/tb_sigmadelta.v b/sim/tb/tb_sigmadelta.v index c6653ad..1948a80 100644 --- a/sim/tb/tb_sigmadelta.v +++ b/sim/tb/tb_sigmadelta.v @@ -27,7 +27,6 @@ module tb_sigmadelta(); .o(sd_o) ); - wire signed [15:0] sample_q15; sigmadelta_rcmodel_q15 rc_model( .clk(clk), .resetn(resetn), @@ -35,4 +34,11 @@ module tb_sigmadelta(); .sample_q15(sample_q15) ); + wire signed [15:0] y_q15; + lpf_iir_q15_k #(8) lpf( + .clk(clk), .rst_n(resetn), + .x_q15(sample_q15), + .y_q15(y_q15) + ); + endmodule From 165faefa59d6dd69a246376efc083ae2e489f5bc Mon Sep 17 00:00:00 2001 From: Joppe Blondel Date: Sun, 19 Oct 2025 17:19:08 +0200 Subject: [PATCH 4/5] Added decimation --- project.cfg | 2 + rtl/core/decimate_by_r_q15.v | 74 ++++++++++++++++++++++++++++++++++++ sim/tb/tb_sigmadelta.v | 11 +++++- 3 files changed, 85 insertions(+), 2 deletions(-) create mode 100644 rtl/core/decimate_by_r_q15.v diff --git a/project.cfg b/project.cfg index 53bc7fc..7098231 100644 --- a/project.cfg +++ b/project.cfg @@ -24,6 +24,7 @@ files_verilog = rtl/toplevel/top_generic.v rtl/core/sigmadelta_rcmodel_q15.v rtl/core/mul_const.v rtl/core/lpf_iir_q15_k.v + rtl/core/decimate_by_r_q15.v rtl/arch/spartan-6/lvds_comparator.v rtl/arch/spartan-6/clk_gen.v files_con = boards/mimas_v1/constraints.ucf @@ -52,6 +53,7 @@ files_verilog = sim/tb/tb_nco_q15.v rtl/core/sigmadelta_rcmodel_q15.v rtl/core/mul_const.v rtl/core/lpf_iir_q15_k.v + rtl/core/decimate_by_r_q15.v sim/overrides/sigmadelta_sampler.v sim/overrides/clk_gen.v files_other = rtl/util/conv.vh diff --git a/rtl/core/decimate_by_r_q15.v b/rtl/core/decimate_by_r_q15.v new file mode 100644 index 0000000..60df0c3 --- /dev/null +++ b/rtl/core/decimate_by_r_q15.v @@ -0,0 +1,74 @@ +`timescale 1ns/1ps + +// ============================================================================= +// Decimator by R +// Reduces the effective sample rate by an integer factor R by selecting every +// R-th input sample. Generates a one-cycle 'out_valid' pulse each time a new +// decimated sample is produced. +// +// Implements: +// For each valid input sample: +// if (count == R-1): +// count <= 0 +// out_q15 <= in_q15 +// out_valid <= 1 +// else: +// count <= count + 1 +// +// parameters: +// -- R : integer decimation factor (e.g., 400) +// output sample rate = input rate / R +// -- CNT_W : counter bit width, must satisfy 2^CNT_W > R +// +// inout: +// -- clk : input clock (same rate as 'in_valid') +// -- rst_n : active-low synchronous reset +// -- in_valid : input data strobe; assert 1'b1 if input is always valid +// -- in_q15 : signed 16-bit Q1.15 input sample (full-rate) +// -- out_valid : single-cycle pulse every R samples (decimated rate strobe) +// -- out_q15 : signed 16-bit Q1.15 output sample (decimated stream) +// +// Notes: +// - This module performs *pure downsampling* (sample selection only). +// It does not include any anti-alias filtering; high-frequency content +// above the new Nyquist limit (Fs_out / 2) will alias into the baseband. +// - For most applications, an anti-alias low-pass filter such as +// lpf_iir_q15 or a FIR stage should precede this decimator. +// - The output sample rate is given by: +// Fs_out = Fs_in / R +// - Typical usage: interface between high-rate sigma-delta or oversampled +// data streams and lower-rate processing stages. +// ============================================================================= +module decimate_by_r_q15 #( + parameter integer R = 400, // decimation factor + parameter integer CNT_W = 10 // width so that 2^CNT_W > R (e.g., 10 for 750) +)( + input wire clk, + input wire rst_n, + input wire in_valid, // assert 1'b1 if always valid + input wire signed [15:0] in_q15, // Q1.15 sample at full rate + output reg out_valid, // 1-cycle pulse every R samples + output reg signed [15:0] out_q15 // Q1.15 sample at decimated rate +); + reg [CNT_W-1:0] cnt; + + always @(posedge clk or negedge rst_n) begin + if (!rst_n) begin + cnt <= {CNT_W{1'b0}}; + out_valid <= 1'b0; + out_q15 <= 16'sd0; + end else begin + out_valid <= 1'b0; + + if (in_valid) begin + if (cnt == R-1) begin + cnt <= {CNT_W{1'b0}}; + out_q15 <= in_q15; + out_valid <= 1'b1; + end else begin + cnt <= cnt + 1'b1; + end + end + end + end +endmodule diff --git a/sim/tb/tb_sigmadelta.v b/sim/tb/tb_sigmadelta.v index 1948a80..3adeb5a 100644 --- a/sim/tb/tb_sigmadelta.v +++ b/sim/tb/tb_sigmadelta.v @@ -13,7 +13,7 @@ module tb_sigmadelta(); initial begin $dumpfile("out.vcd"); $dumpvars; - #1_000_000 + #2_000_000 $finish; end; @@ -35,10 +35,17 @@ module tb_sigmadelta(); ); wire signed [15:0] y_q15; - lpf_iir_q15_k #(8) lpf( + lpf_iir_q15_k #(10) lpf( .clk(clk), .rst_n(resetn), .x_q15(sample_q15), .y_q15(y_q15) ); + wire signed [15:0] decimated_q15; + decimate_by_r_q15 #(400, 10) decimate( + .clk(clk), .rst_n(resetn), + .in_valid(1'b1), .in_q15(y_q15), + .out_valid(), .out_q15(decimated_q15) + ); + endmodule From 49b8a774807a867e46abd824d6713c2d63d2d369 Mon Sep 17 00:00:00 2001 From: Joppe Blondel Date: Sun, 19 Oct 2025 20:03:51 +0200 Subject: [PATCH 5/5] Combined all sigmadelta things to one input block --- project.cfg | 2 + rtl/core/sigmadelta_input_q15.v | 58 ++++++++++++++++++ rtl/util/conv.vh | 7 ++- rtl/util/rc_alpha_q15.vh | 101 +++++++++++++++++++------------- sim/tb/tb_sigmadelta.v | 35 ++++------- 5 files changed, 137 insertions(+), 66 deletions(-) create mode 100644 rtl/core/sigmadelta_input_q15.v diff --git a/project.cfg b/project.cfg index 7098231..f1973a1 100644 --- a/project.cfg +++ b/project.cfg @@ -22,6 +22,7 @@ files_verilog = rtl/toplevel/top_generic.v rtl/core/nco_q15.v rtl/core/sigmadelta_sampler.v rtl/core/sigmadelta_rcmodel_q15.v + rtl/core/sigmadelta_input_q15.v rtl/core/mul_const.v rtl/core/lpf_iir_q15_k.v rtl/core/decimate_by_r_q15.v @@ -51,6 +52,7 @@ files_verilog = sim/tb/tb_nco_q15.v rtl/core/nco_q15.v rtl/core/lvds_comparator.v rtl/core/sigmadelta_rcmodel_q15.v + rtl/core/sigmadelta_input_q15.v rtl/core/mul_const.v rtl/core/lpf_iir_q15_k.v rtl/core/decimate_by_r_q15.v diff --git a/rtl/core/sigmadelta_input_q15.v b/rtl/core/sigmadelta_input_q15.v new file mode 100644 index 0000000..f6e8c37 --- /dev/null +++ b/rtl/core/sigmadelta_input_q15.v @@ -0,0 +1,58 @@ +`timescale 1ns/1ps + +module sigmadelta_input #( + parameter integer R_OHM = 3300, + parameter integer C_PF = 220 +)( + input wire clk_15, + input wire resetn, + + input wire adc_a, + input wire adc_b, + output wire adc_o, + + output wire signed [15:0] signal_q15, + output wire signal_valid +); + `include "rc_alpha_q15.vh" + + wire sd_signal; + wire signed [15:0] raw_sample_q15; + wire signed [15:0] lpf_sample_q15; + + sigmadelta_sampler sd_sampler( + .clk(clk_15), + .a(adc_a), .b(adc_b), + .o(sd_signal) + ); + assign adc_o = sd_signal; + + localparam integer alpha_q15_int = alpha_q15_from_rc(R_OHM, C_PF, 15000000); + localparam signed [15:0] alpha_q15 = alpha_q15_int[15:0]; + localparam signed [15:0] alpha_q15_top = alpha_q15 & 16'hff00; + sigmadelta_rcmodel_q15 #( + .alpha_q15(alpha_q15_top) + ) rc_model ( + .clk(clk_15), .resetn(resetn), + .sd_sample(sd_signal), + .sample_q15(raw_sample_q15) + ); + + lpf_iir_q15_k #( + .K(10) + ) lpf ( + .clk(clk_15), .rst_n(resetn), + .x_q15(raw_sample_q15), + .y_q15(lpf_sample_q15) + ); + + decimate_by_r_q15 #( + .R(375), // 15MHz/375 = 40KHz + .CNT_W(10) + ) decimate ( + .clk(clk_15), .rst_n(resetn), + .in_valid(1'b1), .in_q15(lpf_sample_q15), + .out_valid(signal_valid), .out_q15(signal_q15) + ); + +endmodule diff --git a/rtl/util/conv.vh b/rtl/util/conv.vh index 8a6c268..b59628b 100644 --- a/rtl/util/conv.vh +++ b/rtl/util/conv.vh @@ -1,3 +1,6 @@ +`ifndef CONV_VH +`define CONV_VH + // ============================================================================= // Convert Q1.15 to a biased UQ0.16 signal // ============================================================================= @@ -8,4 +11,6 @@ begin biased = q15 + 17'sd32768; q15_to_uq16 = biased[15:0]; end -endfunction \ No newline at end of file +endfunction + +`endif \ No newline at end of file diff --git a/rtl/util/rc_alpha_q15.vh b/rtl/util/rc_alpha_q15.vh index 5ab0e69..27e6804 100644 --- a/rtl/util/rc_alpha_q15.vh +++ b/rtl/util/rc_alpha_q15.vh @@ -7,61 +7,82 @@ `define RC_ALPHA_Q15_VH function integer alpha_q15_from_rc; - input integer R_OHM; // resistance in ohms - input integer C_PF; // capacitance in picofarads - input integer FS_HZ; // sampling frequency in Hz + input integer R_OHM; // ohms + input integer C_PF; // picofarads + input integer FS_HZ; // Hz - integer N; // fractional bits for x (QN) - reg [127:0] num_1e12_sllN; - reg [127:0] denom_u; - reg [127:0] x_qN; // x in QN - reg [255:0] x2; // x^2 in Q(2N) - reg [383:0] x3; // x^3 in Q(3N) - - integer term1_q15; // x -> Q1.15 - integer term2_q15; // x^2/2 -> Q1.15 - integer term3_q15; // x^3/6 -> Q1.15 - integer acc; // accumulator for result -begin // Choose QN for x. N=24 is a good balance for accuracy/width. - N = 24; + integer N; - // x = 1 / (Fs * R * C) with C in pF ==> x = 1e12 / (Fs * R * C_PF) + // We'll keep everything as unsigned vectors; inputs copied into vectors first. + reg [63:0] R_u, C_u, FS_u; + + // x = 1 / (Fs * R * C) with C in pF -> x = 1e12 / (Fs*R*C_pf) // x_qN = round( x * 2^N ) = round( (1e12 << N) / denom ) - num_1e12_sllN = 128'd1000000000000 << N; - - // denom = Fs * R * C_PF (fits in 64..96 bits for typical values) - denom_u = 0; - denom_u = denom_u + FS_HZ[127:0]; - denom_u = denom_u * R_OHM[127:0]; - denom_u = denom_u * C_PF[127:0]; - - // rounded divide for x_qN - x_qN = (num_1e12_sllN + (denom_u >> 1)) / denom_u; + reg [127:0] NUM_1E12_SLLN; // big enough for 1e12 << N + reg [127:0] DENOM; // Fs*R*C + reg [127:0] X_qN; // x in QN // Powers - x2 = x_qN * x_qN; // 128x128 -> 256 - x3 = x2 * x_qN; // 256x128 -> 384 + reg [255:0] X2; // x^2 in Q(2N) + reg [383:0] X3; // x^3 in Q(3N) - // term1 = x -> shift from QN to Q15 - term1_q15 = (x_qN >> (N - 15)) & 16'hFFFF; + integer term1_q15; + integer term2_q15; + integer term3_q15; + integer acc; - // term2 = x^2 / 2 -> shift from Q(2N) to Q15 and divide by 2 - term2_q15 = (x2 >> (2*N - 15 + 1)) & 16'hFFFF; +begin + N = 24; - // term3 = x^3 / 6 -> shift from Q(3N) to Q15, then divide by 6 (rounded) - begin : gen_term3 + // Copy integer inputs into 64-bit vectors (no bit-slicing of integers) + R_u = R_OHM[31:0]; + C_u = C_PF[31:0]; + FS_u = FS_HZ[31:0]; + + // Denominator = Fs * R * C_pf (fits in < 2^64 for typical values) + DENOM = 128'd0; + DENOM = FS_u; + DENOM = DENOM * R_u; + DENOM = DENOM * C_u; + + // // Guard: avoid divide by zero + // if (DENOM == 0) begin + // alpha_q15_from_rc = 0; + // disable alpha_q15_from_rc; + // end + + // Numerator = (1e12 << N). 1e12 * 2^24 ≈ 1.6777e19 (fits in 2^64..2^65), + // so use 128 bits to be safe. + NUM_1E12_SLLN = 128'd1000000000000 << N; + + // x_qN = rounded division + X_qN = (NUM_1E12_SLLN + (DENOM >> 1)) / DENOM; + + // Powers + X2 = X_qN * X_qN; + X3 = X2 * X_qN; + + // Convert terms to Q1.15: + // term1 = x -> shift from QN to Q15 + term1_q15 = (X_qN >> (N - 15)) & 16'hFFFF; + + // term2 = x^2 / 2 -> Q(2N) to Q15 and /2 + term2_q15 = (X2 >> (2*N - 15 + 1)) & 16'hFFFF; + + // term3 = x^3 / 6 -> Q(3N) to Q15, then /6 with rounding + begin : gen_t3 reg [383:0] tmp_q15_wide; reg [383:0] tmp_div6; - tmp_q15_wide = (x3 >> (3*N - 15)); - tmp_div6 = (tmp_q15_wide + 6'd3) / 6; // +3 for rounding + tmp_q15_wide = (X3 >> (3*N - 15)); + tmp_div6 = (tmp_q15_wide + 6'd3) / 6; term3_q15 = tmp_div6[15:0]; end - // Combine: alpha_q15 = x - x^2/2 + x^3/6 ; clamp to [0, 0x7FFF] + // Combine and clamp acc = term1_q15 - term2_q15 + term3_q15; - if (acc < 0) acc = 0; - else if (acc > 16'h7FFF) acc = 16'h7FFF; + if (acc < 0) acc = 0; + else if (acc > 16'h7FFF) acc = 16'h7FFF; alpha_q15_from_rc = acc; end diff --git a/sim/tb/tb_sigmadelta.v b/sim/tb/tb_sigmadelta.v index 3adeb5a..4d09fd2 100644 --- a/sim/tb/tb_sigmadelta.v +++ b/sim/tb/tb_sigmadelta.v @@ -20,32 +20,17 @@ module tb_sigmadelta(); wire sd_a; wire sd_b; wire sd_o; - // 3K3R 220PC 15MHZT - sigmadelta_sampler sd_sampler( - .clk(clk), - .a(sd_a), .b(sd_b), - .o(sd_o) - ); - - wire signed [15:0] sample_q15; - sigmadelta_rcmodel_q15 rc_model( - .clk(clk), .resetn(resetn), - .sd_sample(sd_o), - .sample_q15(sample_q15) - ); - - wire signed [15:0] y_q15; - lpf_iir_q15_k #(10) lpf( - .clk(clk), .rst_n(resetn), - .x_q15(sample_q15), - .y_q15(y_q15) - ); - wire signed [15:0] decimated_q15; - decimate_by_r_q15 #(400, 10) decimate( - .clk(clk), .rst_n(resetn), - .in_valid(1'b1), .in_q15(y_q15), - .out_valid(), .out_q15(decimated_q15) + wire decimated_valid; + + sigmadelta_input #( + .R_OHM(3300), + .C_PF(220) + ) dut( + .clk_15(clk), .resetn(resetn), + .adc_a(sd_a), .adc_b(sd_b), .adc_o(sd_o), + .signal_q15(decimated_q15), + .signal_valid(decimated_valid) ); endmodule