Verilog语法

发布时间 2023-03-28 22:41:13作者: anzg256

1、整数 integer

  • 整数(正数 0 负数)是一种通用的寄存器数据类型,用于对数量进行操作,整数的默认位宽为宿主机的字的位数,与具体实现有关,最小为32位。
  • reg和integer:reg的寄存器类型变量为无符号数
           integer的寄存器类型变量为有符号数
  • 举例
     integer counter; //作为计数器定义
     initial
       counter = -1;  //将-1存储到计数器中
    

2、函数:关键字 function-----endfunction

举例:

//计算二进制位宽
function integer clogb2 (input integer bit_depth);              
begin                                                           
  for(clogb2 = 0; bit_depth > 0; clogb2 = clogb2 + 1)                   
	    bit_depth = bit_depth >> 1;                                 
  end                                                           
endfunction      

3、关于Verilog的编译指令,使用方式为`keyword

(1)`timescale

用法:`timescale <reference_time_unit>/<time_precision>
说明:<reference_time_unit> (参考时间单位):指定时间和延迟的测量单位。
   <time_precision>(时间精度):指定仿真过程中延迟值进位取整的精度。
   只有1,10,100才是合法的说明时间单位和时间精度的整数。

举例
`timescale 1ns / 1ps
#10      表示延迟10ns
#6.231678   因为精度为1ps,在6.232时赋值语句生效

(2)`define

说明::定义Verilog中的文本宏,类似C语言中的#define
举例

a. 规定子长的文本宏: `define WORD_SIZE 32            //代码中用`WORD_SIZE表示
b. 定义别名:        `define S $stop                 //代码中用`S来代替$stop
c.定义字符串:       `define WORD_REG reg [31:0]     //用`WORD_REG reg 32来定义一个32位的寄存器变量

(3)`include

说明:可以在编译期间将一个Verilog源文件包含在另一个Verilog文件中,作用类似于C语言中的#include结构
举例
可以提前将VGA数据,比如颜色的数据存放在一个源文件中(起名为VGA_Para.v或者VGA_Para.h)
在VGA的driver和display模块可以直接调用这个文件VGA_Para.v

`include "VGA_Para.v"	

module VGA_Dispaly(
	port1,
  port2
    );

endmodule

(4)条件编译`ifdef

说明:条件编译指令可以根据指定条件来生成对应的电路,可以减少电路面积并提高代码的复用性。
用法:在Verilog文件中,条件编译标志可以用`define语句设置。
举例一:有条件的编译模块

`ifdef XOR            //若设置NOR标志,则编译design_xor模块  
module design_xor;
······
endmodule  
`elsif AND           //若设置AND标志,则编译design_and模块
module design_and;
······
endmodule 	
`else                //默认执行design_or模块
module design_or;
······
endmodule 		
`endif
 

举例二:有条件的编译语句

`define	XOR			    //执行该语句
//`define	AND			 
//`define	OR  
 
module test(
	input		i_data_a,
	input		i_data_b,
	output	o_data_result	
);
 
`ifdef XOR
	assign o_data_result = i_data_a ^ i_data_b;	
`elsif AND
	assign o_data_result = i_data_a & i_data_b;	
`else 
	assign o_data_result = i_data_a | i_data_b;		
`endif
 
endmodule

**举例三:ifndef的用法** 它的作用和ifdef 是相反的----当其后的标识符未被定义时,则编译后续的代码段

//`define	XOR       //注释掉,相当于标识符未被定义
 
module test(
	input		i_data_a,
	input		i_data_b,
	output	o_data_result	
);
 
`ifndef XOR                                       
	assign o_data_result = i_data_a ^ i_data_b;	   //XOR未被定义,执行该语句
`else 
	assign o_data_result = i_data_a | i_data_b;		
`endif
 
endmodule