Forum Discussion

Altera_Forum's avatar
Altera_Forum
Icon for Honored Contributor rankHonored Contributor
12 years ago

how to write a counter? verilog~~~

Hi,

Anybody can teach me about counter?

Here is my code~

always @(posedge clk)

begin

if (reset==1)

begin

readdata <=16'd0;//output

x<=8'd0;//output

selA<=3'd0;//output

ld<=1'd0;//output

end

else if(chipselect)

begin

c<=c+1; //c is a reg

case (c)

(0|2|4|6|8) :

begin

x <= writedata[7:0];

selA <= writedata[10:8];

ld <= writedata[11];

end

(1|3|5|7|9) :

readdata[15:0] <= Q;

endcase

end

end

2 Replies

  • Altera_Forum's avatar
    Altera_Forum
    Icon for Honored Contributor rankHonored Contributor

    This is clearly the same as another thread you've opened. Close one and post all your questions, on the same subject, to the same thread

  • Altera_Forum's avatar
    Altera_Forum
    Icon for Honored Contributor rankHonored Contributor

    use the altera template:

    // UP/DN binary counter with all of the register secondary

    // hardware. (1 cell per bit)

    module cntr_updn (clk,ena,rst,sload,sdata,sclear,inc_not_dec,q);

    parameter WIDTH = 16;

    input clk,ena,rst,sload,sclear,inc_not_dec;

    input [WIDTH-1:0] sdata;

    output [WIDTH-1:0] q;

    reg [WIDTH-1:0] q;

    always @(posedge clk or posedge rst) begin

    if (rst) q <= 0;

    else begin

    if (ena) begin

    if (sclear) q <= 0;

    else if (sload) q <= sdata;

    else q <= q + (inc_not_dec ? 1'b1 : {WIDTH{1'b1}});

    end

    end

    end

    endmodule