题解 | #交通灯#
交通灯
https://www.nowcoder.com/practice/b5ae79ff08804b61ad61f749eaf157ba
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 ); reg [7:0] clock_idle, clock_g, clock_y, clock_r; parameter IDLE = 0, GREEN = 1, YELLOW = 2, RED = 3; reg [1:0] state, nstate; // 初始态时钟 always @(posedge clk or negedge rst_n) begin if (!rst_n) begin clock_idle <= 10; end else if (state == IDLE) begin clock_idle <= clock_idle == 8 ? 10 : clock_idle - 1; end end // 绿灯时钟 always @(posedge clk or negedge rst_n) begin if (!rst_n) begin clock_g <= 60; end else if (state == GREEN) begin clock_g <= clock_g == 1 ? 60 : clock_g - 1; if (pass_request) clock_g <= clock_g > 10 ? 10 : clock_g; end end // 黄灯时钟 always @(posedge clk or negedge rst_n) begin if (!rst_n) begin clock_y <= 5; end else if (state == YELLOW) begin clock_y <= clock_y== 1 ? 5 : clock_y - 1; end end // 红灯时钟 always @(posedge clk or negedge rst_n) begin if (!rst_n) begin clock_r <= 10; end else if (state == RED) begin clock_r <= clock_r == 1 ? 10 : clock_r - 1; end end // clock update assign clock = state == IDLE ? clock_idle : state == GREEN ? clock_g : state == YELLOW ? clock_y : clock_r; // state update always @(posedge clk or negedge rst_n) begin if (!rst_n) begin state <= IDLE; end else begin state <= nstate; end end // state transfer always @(*) begin case(state) IDLE: nstate <= clock_idle == 8 ? RED : IDLE; RED: nstate <= clock_r == 1 ? YELLOW : RED; YELLOW: nstate <= clock_y == 1 ? GREEN : YELLOW; GREEN: nstate <= clock_g == 1 ? RED : GREEN; default: nstate <= IDLE; endcase end // output always @(posedge clk or negedge rst_n) begin if (!rst_n) begin green <= 0; yellow <= 0; red <= 0; end else begin green <= nstate == GREEN; yellow <= nstate == YELLOW; red <= nstate == RED; end end endmodule