Verilog HDL 基本文法回顧
打算設計一個簡單的微程式控制CPU模型,下面是VHDL文法回顧。
module的結構
/*
VHDL是由子產品組成,嵌在module endmodule之間,其他語句均由 ';' 結束
*/
module add(a,b,c,sum,count); //子產品端口定義
input [2:0] a,b;
input cin;
output [2:0] sum;
output count; //IO 定義
//内部變量定義
assign {count,sum} = a + b + cin; // 功能定義
endmodule
功能塊
常用的是
assign
(組合邏輯電路)和
always
(時序電路)
//簡單的計數器
module count (clk,reset,x,num);
input reset,clk,x;
output [1:0]num;
reg [1:0]num;
always @ (posedge clk) //上升沿
begin
if(reset)
num=2'b00;
else
case (num)
2'b00 : if(x==0) num<=2'b01;
else num<=2'b11;
2'b01 : if(x==0) num<=2'b10;
else num<=2'b00;
2'b10 : if(x==0) num<=2'b11;
else num<=2'b01;
2'b11 : if(x==0) num<=2'b00;
else num<=2'b10;
endcase
end
endmodule
assign
和
always
塊的邏輯功能是同時進行(并行)的,
always
内的邏輯是順序執行的.
Verilog HDL中沒有以
{ }
取代
begin end
資料類型
數字的表達方式
<位寬>’<進制><對應的進制數字>
不同位寬應分别定義
8'b0001_0101 //位寬為8位的二進制數字表示,使用下劃線可以提高可讀性(對數字的大小沒有影響)
8'h15 //位寬為8位的十六進制數字表示
變量類型
wire型
wire
類型用以
assign
操作的組合邏輯信号
預設為wire型
wire a; //1位的wire型變量
wire[7:0] b; //8位的wire型變量
wire[7:0] c,d; //兩個8位的wire型變量
寄存器類型 reg型
寄存器類型是對資料存儲單元的抽象,在
always
塊内定義的變量都必須是reg型,可以這麼了解:reg型就是在always内使用的變量類型,并不一定是寄存器或者觸發器的輸出
運算符
基本算術運算符: + - * / %
關系運算符: > < >= <= ==
指派運算符: = <=
邏輯運算符: && || !(非)
位運算符: & | ~(反) `(亦或)
拼接符: { }
非阻塞指派<= : 塊結束後,才完成指派;值不是立即改變的;在always塊中常使用此種方法。
阻塞指派 : 立即完成指派,指派結束後才能結束塊。可能會産生意想不到的錯誤。
基本流程語句
條件語句
if else
case
case(變量)
變量值1:
begin
執行語句
end
變量值2:
default:
endcase
循環語句
for()
Exemple
//模4計數器
module counter4(X,clk,Z,L);
input X,clk;
output Z,L;
reg[1:0] L;
parameter S0=2'b00,S1=2'b01,S2=2'b10,S3=2'b11;
always @(posedge clk)
begin
if(X==1)
case(L)
S0: L<=S1;
S1: L<=S2;
S2: L<=S3;
S3: L<=S0;
endcase
else
case(L)
S0: L<=S3; /*仿真時間、always語句和assign的位置*/
S1: L<=S0;
S2: L<=S1;
S3: L<=S2;
endcase
end
assign Z=((X==1&&L==S3)?1:0)|((X==0&&L==S0)?1:0);
endmodule
//010序列檢查器
module test010(in,out,state,clk,reset);
input in,clk,reset;
output out;
output[2:0]state;
reg[2:0]state;
reg out;
parameter s0='d0,s1='d1,s2='d2;
always @(posedge clk)
begin
if(reset) begin state<=s0; out<=0; end /*控制in的輸入*/
else case(state)
s0:begin
if(in==0) begin state<=s1; out<=0; end
else begin state<=s0; out<=0; end
end
s1:begin
if(in==1) begin state<=s2; out<=0; end
else begin state<=s0; out<=0; end
end
s2:begin
if(in==0) begin state<=s0; out<=1; end
else begin state<=s0; out<=0; end
end
default: state<=s0;
endcase
end
endmodule