# Frequency divider in Verilog

I am trying to implement a clock divider with a 2^8 bit different frequencies. I understand that i need a counter that will count and once it elapses change some variable state and based on that output the sine wave sample. However i don't know how to write the code properly. I have tried several times, but ended up getting errors. My code is given below:

module functionGenerator(Clk,data_out, freq);
//declare input and output
input [7:0] freq;
input Clk;
output [9:0] data_out;
//declare the sine ROM - 30 registers each 8 bit wide.
reg [9:0] sine [0:99];
//Internal signals
integer i;
reg [9:0] data_out;
//Initialize the sine rom with samples.
initial begin
i = 0;
sine = 0;        sine = 10;        sine = 20;        sine = 29;        sine = 39;
sine = 48;       sine = 58;        sine = 67;        sine = 75;        sine = 84;
sine = 92;      sine = 100;      sine = 107;      sine = 114;      sine = 120;
sine = 126;     sine = 132;      sine = 137;      sine = 141;      sine = 145;
sine = 149;     sine = 151;      sine = 153;      sine = 155;      sine = 156;
sine = 156;

end

//At every positive edge of the clock, output a sine wave sample.
always@ (posedge(Clk))
begin
if ( i < 25 )
data_out = sine[i];
else if ( i < 50 )
data_out = sine[50 - i];
else if  ( i < 75 )
data_out = - sine[i - 50];
else
data_out = - sine[100 - i];
i = i+ 1;
if(i == 100)
i = 0;
end
endmodule
$$$$

• i should be a register, and you'd need to use the <= to assign values to registers. Your reg data_out` should throw an error, but probably just silently hides the output of the same name. Did you even try to synthesize this? And, the errors you're getting, have you tried reading them? – Marcus Müller Apr 29 at 9:19
• also, what you're building is not what is usually called a frequency divider; it's more of a DDS. – Marcus Müller Apr 29 at 9:24
• The goal of this is to generate the variable frequency sine wave to the tesbench and yes I have been able to output clean sine wave, but not sure how to implement the clock divider. – RytisBe Apr 29 at 9:28
• as said, there are multiple things that your IDE will warn or error about. And I tried to point these out in my first comment. (and this is still not a clock divider) – Marcus Müller Apr 29 at 9:33
• You vary the frequency by varying the phase increment. You probably want a larger phase register and to look up only the high bits treating the low bits as a fraction. Try writing this as a computer program first and only do the HDL implementation once you thoroughly understand the DDS algorithm, needed rates and widths. – Chris Stratton Apr 29 at 10:47