注意的点:
1.交通灯是按红——黄——绿——红这样的顺序来循环变化的
2.复位之后需要延迟两个时钟再跳转到红灯,当处在延时暂停态时,三盏灯均不亮
3.红灯倒计时10-1,黄灯倒计时5-1,绿灯倒计时60-1(行人按钮没有按下时)
4.用次态(nstate)来判断灯的状态,采用现态(state)来判断的话,灯的状态会延迟一拍
module triffic_light ( input rst_n, //异位复位信号,低电平有效 input clk, //时钟信号 input pass_request, output wire[7:0]clock, //交通灯倒数 output reg red, output reg yellow, output reg green ); parameter IDLE_delay2 = 2'd0; parameter ONE_RED = 2'd1; parameter TWO_YELLOW = 2'd2; parameter THREE_GREEN = 2'd3; reg [1:0] state,nstate; reg [6:0] sys_cnt; always @(posedge clk or negedge rst_n) begin if(!rst_n) begin state <= IDLE_delay2; end else begin state <= nstate; end end always @(*)(1444584) begin case(state) IDLE_delay2 : nstate = (sys_cnt == 7'd8) ? ONE_RED : IDLE_delay2; ONE_RED : nstate = (sys_cnt == 7'd1) ? TWO_YELLOW : ONE_RED; TWO_YELLOW : nstate = (sys_cnt == 7'd1) ? THREE_GREEN : TWO_YELLOW; THREE_GREEN : nstate = (sys_cnt == 7'd1) ? ONE_RED : THREE_GREEN; default : nstate = IDLE_delay2; endcase end always @(posedge clk or negedge rst_n) begin if(!rst_n) begin red <= 1'b0; yellow <= 1'b0; green <= 1'b0; end else begin case(nstate) IDLE_delay2 : begin red <= 1'b0; yellow <= 1'b0; green <= 1'b0; end ONE_RED : begin red <= 1'b1; yellow <= 1'b0; green <= 1'b0; end TWO_YELLOW : begin red <= 1'b0; yellow <= 1'b1; green <= 1'b0; end THREE_GREEN : begin red <= 1'b0; yellow <= 1'b0; green <= 1'b1; end default : begin red <= 1'b0; yellow <= 1'b0; green <= 1'b0; end endcase end end always @(posedge clk or negedge rst_n) begin if(!rst_n) begin sys_cnt <= 7'd10; end else if(state == IDLE_delay2) begin sys_cnt <= (sys_cnt == 7'd8) ? 7'd10 : sys_cnt - 1; end else if(state == ONE_RED) begin sys_cnt <= (sys_cnt == 7'd1) ? 7'd5 :sys_cnt - 1; end else if(state == TWO_YELLOW) begin sys_cnt <= (sys_cnt == 7'd1) ? 7'd60 :sys_cnt - 1; end else if(state == THREE_GREEN) begin if(pass_request && sys_cnt>10) sys_cnt <= 7'd10; else sys_cnt = (sys_cnt == 7'd1) ? 7'd10 : sys_cnt - 1; end end assign clock = sys_cnt; endmodule
(本人初学小白,还有很多不懂的地方,如果有错误或者不足的地方,还请各位在评论区多多指出)