I have written this code to get the frequency of the input on seven segment display. This is only at early stages that is why I have used only one digit for the display. I am taking input through signal generator and using Basys2 board for the output. The problem I am facing is that the frequency displayed on the board is fluctuating a lot even though I am applying constant frequency input through signal generator. Below is my code:
module frequencyCounter(clk, in, frequency, rst, C, AN, DP);
input clk, in, rst;
output reg [3:0] frequency;
output [6:0] C;
output [3:0] AN;
output DP;
reg [32:0] counter = 0;
reg [3:0] cur_dig_AN;
reg [3:0] current_digit;
reg [6:0] segments;
reg [3:0] frequency_reg;
assign AN = cur_dig_AN;
assign DP = 1;
assign C = ~segments;
always@(posedge clk) begin
if(rst) begin
frequency <= 0;
frequency_reg <= 0;
counter <=0;
cur_dig_AN <=0;
current_digit <=0;
end
else if (counter < 50000000) begin
counter <= counter +1;
if(in)
frequency_reg <= frequency_reg + 1;
end
else begin
counter <= 0;
frequency_reg <= 0;
frequency <= frequency_reg;
if (frequency < 10) begin
cur_dig_AN <= 4'b1110;
current_digit <= frequency;
end
end
end
// the hex-to-7-segment decoder
always @ (current_digit)
case (current_digit)
4'b0000: segments = 7'b111_1110; // 0
4'b0001: segments = 7'b011_0000; // 1
4'b0010: segments = 7'b110_1101; // 2
4'b0011: segments = 7'b111_1001; // 3
4'b0100: segments = 7'b011_0011; // 4
4'b0101: segments = 7'b101_1011; // 5
4'b0110: segments = 7'b101_1111; // 6
4'b0111: segments = 7'b111_0000; // 7
4'b1000: segments = 7'b111_1111; // 8
4'b1001: segments = 7'b111_0011; // 9
4'b1010: segments = 7'b111_0111; // A
4'b1011: segments = 7'b001_1111; // b
4'b1100: segments = 7'b000_1101; // c
4'b1101: segments = 7'b011_1101; // d
4'b1110: segments = 7'b100_1111; // E
4'b1111: segments = 7'b100_0111; // F
default: segments = 7'bxxx_xxxx;
endcase
endmodule
The way it works is that it counts number of inputs in one second. I am using 50Mhz clock (thus 50000000). Some registers like cur_dig_AN might seem redundant but as I said I was just testing at this stage. Moreover, is there any effective way of eliminating noise if it is of any concern at all in my case?
I got the solution to my problem. The problem I was facing was that once there is an input I counted it as many times as there was clk signal and that input was there instead of just counting it once therefore I had to introduce another variable so that I don't count same input twice:
reg in_reg;
if(in && ~in_reg) begin
frequency_reg <= frequency_reg + 1; //increasing freq reg for each input with in one second
in_reg <= 1;
end
else if (~in) //makes sure it is not counting same input twice
in_reg <= 0;
This way I am getting my correct frequency!