Verilog 分频器代码
`timescale 1ns/1ns
module fenpinqi(div12,clk);
input clk;
output div12;
reg div12;
reg[2:0]cnt;
always @(posedge clk)
begin
if(cnt==3'b101)
begin
div12<=~div12;
cnt<=0;
end
else
begin
cnt<=cnt+1;
end
end
endmodule
`timescale 1ns/1ns;
module fenpinqi_tb;
reg clk;
wire div12;
fenpinqi u3cs(.clk(clk),.div12(div12));
initial
begin clk=0; end
always
begin
#10 clk=1; #10 clk=0;
end
endmodule
还有个问题:我之前自己写的代码,总是在声明处报错near "reg": syntax error, unexpected "reg", expecting ';' 我感觉没错,后来用ISE生成了个TB的模板跟我写的一模一样,然后把对应行代码copy过来就过编译了,为什么?(排除输入法全半角的问题)
多谢各位
因为没有复位操作,给reg信号初始值,所以仿真开始后,所有的reg都是不定态,加法操作依然是不定态,取反操作也是类似的。
楼上说的没错
给你改一下吧
//-------------------------------------
module fenpinqi(div12,clk , Reset); //add reset
input clk;
output div12; input Reset;
reg div12;
reg[2:0]cnt;
always @(posedge clk or negedge Reset) //add negedge reset
if ( ! Reset ) // add reset signal to reset the registers
begin
cnt<=3'b0;
div12<=1'b0;
end
else
begin
if(cnt==3'b101)
begin
div12<=~div12;
cnt<=0;
end
else
begin
cnt<=cnt+1;
end
end
endmodule
//----------------------test bench-------
module fenpinqi_tb;
reg clk;
reg Reset;
wire div12;
fenpinqi u3cs(.clk(clk),.div12(div12), .Reset(Reset));
initial
begin
#0 begin
clk<=0;
Reset<=1; // add the reset signal
end
#1 Reset<=0; // make the negedge of the Reset
#1 Reset<=1;
#1000 $stop; // add the "stop"
end
always
begin
#10 clk=!clk; //the correct way of the clk signal
end
endmodule
正解,所有寄存器最好都要开始的时候赋初值,不然会产生错误!
学习了
嗯
时序电路必须有复位操作,芯片上电后的第一件事就是复位
我是按书上的代码直接敲的,看来书上也不是都对阿~
多谢 学习了
好耐心~ 我是书上代码直接敲的 看来书上的也不是都对阿 多谢啦
不能說書本有錯,仿真要復位給個初值,實際電路在給電后不管有沒有復位,計數器總是會亂數給個數值,因此這個電路是會動的。
你好,那如果通过一个50M的时钟想得到10k,1hz,2.5hz的时钟,代码如下:module ts(clk,rst, clk_10k, clk_1, clk_out);
input clk;
input rst;
output clk_10k;
output clk_1;
output clk_out;
reg clk_10k;
reg clk_1;
reg clk_out;
reg [11:0] n;
reg [8:0] m;
reg [1:0]k;
//-----------------fenpin-----------------------
always@(posedge clk)
begin
if(!rst)
begin
clk_10k <= 1'b0;
n <= 0;
end
else
begin
n <= n + 12'd1;
if( n == 12'd2500)
begin
n <= 12'h0;
clk_10k <= ~clk_10k;
end
end
end
always@(posedge clk_10k)
begin
if(!rst)
begin
clk_1 <= 1'b0;
m <= 0;
end
else
begin
m <= m + 9'd1;
if( m == 9'd500)
begin
m <= 9'h0;
clk_1 <= ~clk_1;
end
end
end
always@( posedge clk_10k)//?
begin
if(!rst)
begin
clk_out <= 1'b0;
k <= 0;
end
else
begin
k <= k + 2'd1;
if( k == 2'd3)
begin
k <= 2'd0;
clk_out <= ~clk_out;
end
end
end
endmodule
测试代码
`timescale 1ns/1ns
module tb1;
reg clk;
reg rst;
wire [11:0]n;
wire [8:0]m;
wire [1:0]k;
wire clk_10k;
wire clk_1;
wire clk_out;
ts i(
.clk(clk),
.rst(rst),
.clk_10k(clk_10k),
.clk_1(clk_1),
.clk_out(clk_out)
);
initial
begin
clk = 0;
rst = 0;
#20 rst = 1;
end
always
begin
#10 clk <= ~clk;
end
endmodule
为什么在modelsim仿真的时候只能得到10k的时钟,其他的时钟是高阻态
