上传一个例程,有助于学习Verilog:
(附件:102497)
代码分析:
在这里的LED闪烁频率是可调的,按一下KEY会使LED2状态翻转,同时会减小LED3闪烁的频率。
这个代码比较烂,仅仅是用来演示verilog的基本特性
module LED(CLK,KEY,GPIO);
input CLK; //输入信号
input KEY;
output reg[3:0] GPIO = 4'd0; //输出寄存器
reg[1:0] KEY_prev; //内部寄存器
reg[1:0] KEY_status;
reg[23:0] KEY_count;
reg[1:0] Status;
reg[31:0] Count; //32位长度(0~31位)
reg[31:0] limit = 32'd2500000; // 50MHz / 2500000 = 0.05s
always@(posedge CLK) //实现上升沿触发
begin
//process for keyscan
KEY_count <= KEY_count+24'd1; // 建立时序逻辑模型时,采用非阻塞赋值语句。组合逻辑用阻塞赋值
if(KEY_count >= 24'd100000) //50MHz / 100000 -> 50ms //always里面是顺序执行的
begin
KEY_count <= 24'd0;
KEY_status <= KEY_prev & (~KEY);
KEY_prev <= ~KEY;
end
end
always@(posedge KEY_status[0]) //几个always,还有assign之间是同时执行的
begin
limit <= limit + 32'd2000000;
GPIO[2] <= ~GPIO[2];
end
always@(posedge CLK)
begin
Count<=Count+32'd1;
if(Count >= limit) //这里是一个“不小于”号
//注意区别 “不大于”和非阻塞赋值
begin
case(Status)
2'b00:
begin
GPIO[0] <= 1;GPIO[1] <= 1;GPIO[3] <= 1;
end
2'b01:
begin
GPIO[0] <= 1;GPIO[1] <= 1;GPIO[3] <= 1;
end
2'b10:
begin
GPIO[0] <= 0;GPIO[1] <= 0;GPIO[3] <= 0;
end
2'b11:
begin
GPIO[0] <= 0;GPIO[1] <= 0;GPIO[3] <= 0;
end//注意begin-end块
default;//最好写上default
endcase //注意与C的区别
GPIO[3] <= ~GPIO[3];
Status<=Status+1'b1;
Count<=32'd0;
end
end
endmodule