规范的操作吗和指令例如ADD、WRITE、IDLE等有利于代码的编写和维护,它比直接使用 'h01 这样的常量使用起来可读性和可维护性更好;
枚举类型enum经常和typedef搭配使用,由此便于用户自定义枚举类型的共享使用;
枚举类型的出现保证了一些非期望值的出现,降低来了设计风险;
enum [data_type] {name1 = value, name2 = value2, ..., nameN = valueN} var_name;
enum {red, yellow, green} light1, light2;
无论是枚举名(red/yellow/…)还是他们的(整型)数值都必须是唯一的。他们的值可以被设置为任意整型常量值,或者从初始值0开始递增(默认情况)。
代码示例:
// enum_example
module test_enum ();
// 默认值:red = 0, yellow = 1, green = 2;
enum {red, yellow, green} light1, light2; // 未命名的枚举类型(int类型)
// 正确使用方法:IDLE = 0, S0 = 2, S1 = 3, S2 = x
enum integer {IDLE, S0 = 'b10, S1 = 'b11, S2 = 'x} state, next;
// 正确定义方法:silver和glod都没有指定大小
enum {bronze = 3, silver, gold} medal; // silver = 4, gold = 5
// c被自动地指定为8
enum {a = 3, b = 7, c} alphabet1;
// d = 0, e = 7, f = 8
enum {d, e = 7, f} alphabet2;
initial begin
light1 = red ;
light2 = green ;
// light1 = gold; // err
$display ("light1 is %0d or %s", light1, light1);
$display ("light2 is %0d or %s", light2, light2);
state = S1;
next = S2;
$display ("state is %0d or %s", state, state);
$display ("next is %0d or %s", next,next);
medal = silver ;
$display ("medal is %0d or %s", medal, medal);
alphabet1 = c ;
$display ("alphabet1 is %0d or %s", alphabet1, alphabet1);
alphabet2 = d ;
$display ("alphabet2 is %0d or %s", alphabet2, alphabet2);
end
// try something else
reg [ 3: 0] err;
initial begin
err = a;
$display ("err is %0d or %s", err, err);
end
endmodule
typedef enum {INIT, DECODE, IDLE} fsmstate_e;
fsmstate_e pstate, nstate; // 声明自定义类型变量
case (pstate)
IDLE: nstate = INIT; // 数据赋值
INIT: nstate = DECODE;
default: nstate = IDLE;
endcase
$display ("Next state is %s", nstate.name());
**枚举类型可以直接赋值给整型,整型不能直接赋值给枚举类型,需要做一个枚举类型的类型转换,这样在仿真的时候更安全。
INT = enum;
enum = ENUM'(INT);
// enum_test
module enum_test ;
// 默认值:red = 0, green = 1, blue = 2;
typedef enum {red, green, blue} Colors;
Colors my_color;
initial begin
my_color = red;
$display ("@0 my_color is %d or %s", my_color, my_color);
my_color = blue;
$display ("@1 my_color is %d or %s", my_color, my_color);
// my_color = int'(2); // err
// // An enum variable 'my_color' of type 'Colors' may only be assigned
// // the same enum typed variable or one of its values.
// // Value '2' requires an explicit cast.
// $display ("@2 my_color is %d or %s", my_color, my_color);
my_color = Colors'(1);
$display ("@2 my_color is %d or %s", my_color, my_color);
end
endmodule
版权声明:本文为CSDN博主「Bunny9__」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/Bunny9__/article/details/122494130