Search code examples
verilogfpgafrequencywave

Using switches to change frequency of square wave in Verilog


I am trying to use the 8 switches on my basys2 board to control the frequency of a square wave, yet I'm having trouble with the input part of it, as I do not know how to divide the clock using the binary value of the register that I have collected the states of the switches in.

I know that I need to divide 25000000/[input value] in order to get the correct value for the counter. My question is:

how can I divide 25000000 by the register which has the switch states stored inside of it such, as input [7:0] SW?


Solution

  • If you can assume your input is always a power of two, you can use shifting to the right. But if you want the full 255 possible resolutions, you need to implement a divider.

    Some synthesis tools just synthesize a divider when you simply write 25000000/inputValue. For some others, you may have to do it yourself.

    Alternatively, if you don't want to waste time for dividing, you can pre-calculate the values beforehand and use a counter:

    case (inputValue)
      8'b0000_00010: counterMax = 25000000/2 ; //Where 25000000/2 can be calculated at compile time or by you
      8'b0000_00011: counterMax = 25000000/3 ; //Where 25000000/3 can be calculated at compile time or by you
    ... 
    endcase
    

    and then just count to the counterMax:

    always @(posedge clock)
    begin
      counter <= counter + 1;
      if(counter == counterMax) begin
        out <= ~out;
        counter <= 0;
      end
    end