课上作业
问题
实现0-100的循环计数器,clock的上升沿和下降沿都加1
code
module counter(
input clock,
input reset,
output reg [6:0] out
);
reg [6:0] out_r;
reg [6:0] out_rr;
always @(*) begin
if(clock)
out = out_rr;
else
out = out_r;
end
always @(posedge clock or posedge reset) begin
if(reset)
out_r <= 7'd0;
else
out_r <= out_rr + 1'b1;
end
always @(negedge clock or posedge reset) begin
if(reset)
out_rr <= 7'd0;
else if(out_rr == 7'd99)
out_rr <= 7'd0;
else
out_rr <= out_r + 1'b1;
end
endmodule
波形图
订正版本
上一个code是不正确的,因为在设计过程中要保证CLK和rstn信号干净,没有其他信号的干扰,只能用在时序电路中或复位电路。
module counter(
input clock,
input rstn,
output reg [6:0] out
);
reg [6:0] out_r;
reg [6:0] out_rr;
always @(*) begin
if(out_rr == 50 && out_r == 1)
out = 0;
else
out = out_r + out_rr;
end
always @(posedge clock or negedge rstn) begin
if(!rstn)
out_r <= 7'd0;
else if(out_r == 7'd50)
out_r <= 7'd1;
else
out_r <= out_r + 1'b1;
end
always @(negedge clock or negedge rstn) begin
if(!rstn)
out_rr <= 7'd0;
else if(out_rr == 7'd50)
out_rr <= 7'd0;
else
out_rr <= out_rr + 1'b1;
end
endmodule
在编写RTL代码中,需要谨记的原则有:
- CLK信号不能来作为MUX的选择,尽可能的不要碰CLK和RESETn
- rstn不能用于组合逻辑电路的复位,组合逻辑不需要复位信号
- always敏感列表中不能既有posedge clk,也有negedge clk
- clk信号别去碰!!!别让他去干除了时序之外的其他事情!!!
- 组合逻辑电路中的赋值只能用=
- always 组合逻辑不能生成latch
- 注意多驱动问题,一个reg信号只能存在一个always块中