3.1.1 Basic gates
3.1.1.8 Truth table
- 组合逻辑电路中输出仅仅是其输入的函数(在数学意义上)
module top_module(
input x3,
input x2,
input x1, // three inputs
output f // one output
);
assign f = (x3 & x1) | (x2 & x1) | ((~x3) & x2);
endmodule
3.1.1.9 Two-bit equality
module top_module (
input [1:0] A,
input [1:0] B,
output z
);
assign z = (A == B) ? 1 : 0;
endmodule
3.1.1.10 Sample circuit A
module top_module (input x, input y, output z);
assign z = (x ^ y) & x;
endmodule
3.1.1.11 Sample circuit B
module top_module ( input x, input y, output z );
assign z = x ~^ y;
endmodule
3.1.1.12 Combine circuit A and B
module top_module (input x, input y, output z);
wire tmp1,tmp2;
assign tmp1 = ((x ^ y) & x) | (x ~^ y);
assign tmp2 = ((x ^ y) & x) & (x ~^ y);
assign z = tmp1 ^ tmp2;
endmodule
3.1.1.13 Ring and vibrate?
- 当有来电时,必须打开铃声(ringer = 1)或震动(motor = 1),但二者不会同时打开
- 如果是震动模式(vibrate_mode = 1),打开震动,关闭铃声
module top_module (
input ring,
input vibrate_mode,
output ringer, // Make sound
output motor // Vibrate
);
assign ringer = ring & ~vibrate_mode;
assign motor = ring & vibrate_mode;
endmodule
3.1.1.14 Thermostat
- 两种模式:制热(mode = 1),制冷(mode = 0)
- 当 too_cold = 1时,打开制热,关闭制冷;
- 当 too_hot = 1时,打开制冷,关闭制热;
- 制热和制冷有一个打开时,打开风扇(fan = 1)
- 制冷和制热都未打开,用户也可通过 fan_on = 1打开风扇
module top_module (
input too_cold,
input too_hot,
input mode,
input fan_on,
output heater,
output aircon,
output fan
);
assign heater = mode & too_cold;
assign aircon = ~mode & too_hot;
assign fan = fan_on | heater | aircon;
endmodule
3.1.1.15 3-bit population count
module top_module(
input [2:0] in,
output [1:0] out );
integer i;
reg [2 :0] tmp;
always @ (*) begin
tmp = 0;
for (i = 0; i < 3; i ++) begin
if(in[i])
tmp = tmp + 1;
end
end
assign out = tmp;
endmodule
3.1.1.16 Gates and vectors
- out_both:与左侧(更高位)相邻的数都为1,输出1,且最高位左侧不存在数
- out_any:与右侧(更低位)相邻的数有一个为1,输出为1,最低位右侧不存在数
- out_different:与左侧(更高位)相邻的数不同,输出为1,最高位左侧为[0]位
module top_module(
input [3:0] in,
output [2:0] out_both,
output [3:1] out_any,
output [3:0] out_different );
assign out_both = in[3:1] & in [2:0];
assign out_any = in[2:0] | in[3:1];
assign out_different = {in[0],in[3:1]} ^ in[3:0];
endmodule
3.1.1.17 Even longer vectors
module top_module(
input [99:0] in,
output [98:0] out_both,
output [99:1] out_any,
output [99:0] out_different );
assign out_both = in[99:1] & in [98:0];
assign out_any = in[98:0] | in[99:1];
assign out_different = {in[0],in[99:1]} ^ in[99:0];
endmodule