//进位不影响补码运算的正确性,溢出影响正确性,溢出的本质就是超过了位宽能表达的范围 module add (a, b, out, t, e); parameter W = 32; input [W-1:0] a, b; output [W-1:0] out; output t, e; reg [W-1:0] a_, b_; //补码 reg [W-1:0] out_; //运算后的补码 reg [W-1:0] out; reg [31:0] i; reg t = 0, e = 0; reg tt = 0; always @ (*) begin //都转为补码 a_ = a; b_ = b; if (a_[W-1] == 1) begin for (i = 0; i < W - 1; i = i + 1) a_[i] = ~a[i]; t = 0; for (i = 0; i < W; i = i + 1) begin if (i == 0) begin tt = a_[i]; a_[i] = a_[i] ^ 1 ^ t; t = (tt & 1) | (t & (tt | 1)); end elsebegin tt = a_[i]; a_[i] = a_[i] ^ 0 ^ t; t = (tt & 0) | (t & (tt | 0)); end end end if (b_[W-1] == 1) begin for (i = 0; i < W - 1; i = i + 1) b_[i] = ~b[i]; t = 0; for (i = 0; i < W; i = i + 1) begin if (i == 0) begin tt = b_[i]; b_[i] = b_[i] ^ 1 ^ t; t = (tt & 1) | (t & (tt | 1)); end elsebegin tt = b_[i]; b_[i] = b_[i] ^ 0 ^ t; t = (tt & 0) | (t & (tt | 0)); end end end //俩补码运算 t = 0; for (i = 0; i < W; i = i + 1) begin out_[i] = a_[i] ^ b_[i] ^ t; t = (a_[i] & b_[i]) | (t & (a_[i] | b_[i])); end //检测是否溢出 if (a_[W-1] == 0 && b_[W-1] == 0 && out_[W-1] == 1) e = 1; elseif (a_[W-1] == 1 && b_[W-1] == 1 && out_[W-1] == 0) e = 1; else e = 0; //将补码转为原码 if (out_[W-1] == 1) begin //变反码 for (i = 0; i < W; i = i + 1) begin a_[i] = out_[i]; b_[i] = 1; end tt = 0; for (i = 0; i < W; i = i + 1) begin out_[i] = a_[i] ^ b_[i] ^ tt; tt = (a_[i] & b_[i]) | (tt & (a_[i] | b_[i])); end //变原码 for (i = 0; i < W - 1; i = i + 1) out_[i] = ~out_[i]; end //赋值 for (i = 0; i < W; i = i + 1) out[i] = out_[i]; end endmodule
// 时钟边沿触发的逻辑 always @(posedge clk orposedge rst_n) begin if (rst_n) begin // 复位逻辑 state <= GREEN_NS_RED_EW; counter <= 4'b0000; endelsebegin // 状态转换逻辑 case (state) GREEN_NS_RED_EW: begin if (counter == 4'b1111) begin// 15时钟周期 state <= YELLOW_NS_RED_EW; counter <= 4'b0000; end end YELLOW_NS_RED_EW: begin if (counter == 4'b0011) begin// 3时钟周期 state <= RED_NS_RED_EW_1; counter <= 4'b0000; end end RED_NS_RED_EW_1: begin if (counter == 4'b0011) begin// 3时钟周期,短暂的全红状态 state <= RED_NS_GREEN_EW; counter <= 4'b0000; end end RED_NS_GREEN_EW: begin if (counter == 4'b1111) begin// 15时钟周期 state <= RED_NS_YELLOW_EW; counter <= 4'b0000; end end RED_NS_YELLOW_EW: begin if (counter == 4'b0011) begin// 3时钟周期 state <= RED_NS_RED_EW_2; counter <= 4'b0000; end end RED_NS_RED_EW_2: begin if (counter == 4'b0011) begin// 3时钟周期 state <= GREEN_NS_RED_EW; counter <= 4'b0000; end end endcase
// 计数器递增 counter <= counter + 1;
// 根据当前状态更新交通灯输出 case (state) GREEN_NS_RED_EW: begin light_NS <= 3'b010; // 南北绿灯 light_EW <= 3'b100; // 东西红灯 end YELLOW_NS_RED_EW: begin light_NS <= 3'b001; // 南北黄灯 light_EW <= 3'b100; // 东西红灯 end RED_NS_RED_EW_1: begin light_NS <= 3'b100; // 南北红灯 light_EW <= 3'b100; // 东西红灯 end RED_NS_GREEN_EW: begin light_NS <= 3'b100; // 南北红灯 light_EW <= 3'b010; // 东西绿灯 end RED_NS_YELLOW_EW: begin light_NS <= 3'b100; // 南北红灯 light_EW <= 3'b001; // 东西黄灯 end RED_NS_RED_EW_2: begin light_NS <= 3'b100; // 南北红灯 light_EW <= 3'b100; // 东西红灯 end endcase end end