题解 | #交通灯#

交通灯

https://www.nowcoder.com/practice/b5ae79ff08804b61ad61f749eaf157ba

`timescale 1ns/1ns

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 CNT_MAX=75;
    parameter CNT_RED=10;
    parameter CNT_YELLOW=5;
    parameter CNT_GREEN=60;
    parameter idle=2'd0,R=2'd1,Y=2'd2,G=2'd3;
	reg [7:0] cnt;
    reg[1:0] cs,ns;
    
always@(posedge clk or negedge rst_n)begin
    if(!rst_n)
        cs<=idle;
    else 
        cs<=ns;
end

always@(*)begin
    case(cs)

        idle: ns=(cnt>CNT_MAX-2)?idle:R;

        R: begin
            ns= (cnt==CNT_MAX-CNT_RED+1)? Y:R;
        end 

        Y: ns= (cnt==CNT_MAX-CNT_RED-CNT_YELLOW+1)? G:Y;

        G: ns= (cnt==1)? R:G;

        

        default: ns= idle;
    endcase
end

always@(posedge clk or negedge rst_n)begin
    if(!rst_n)begin
        red<=0;
        yellow<=0;
        green<=0;
    end

    else begin
        case(ns)

        idle:begin
                red<=0;
                yellow<=0;
                green<=0; 
            end
            R:begin
                red<=1;
                yellow<=0;
                green<=0;  
            end

            Y:begin
                red<=0;
                yellow<=1;
                green<=0;  
            end

            G:begin
                red<=0;
                yellow<=0;
                green<=1;  
            end

            
        endcase

    end
end

always@(posedge clk or negedge rst_n)begin
    if(!rst_n)
        cnt<=CNT_MAX;
    else if(ns==R & cs==idle)
        cnt<=CNT_MAX;
    else if(cs==idle)begin
        cnt<=cnt-1;
    end
    
    else if(pass_request)begin
        if(cs==G)begin
            if(cnt>10)
                cnt<=10;
            else
                cnt<=cnt-1;
        end

        else 
            cnt<=cnt-1;
    end
    else if(cnt==1)
        cnt<=CNT_MAX;
    else 
        cnt<=cnt-1;

end
assign clock = (cs==idle)?(cnt-CNT_GREEN-CNT_YELLOW) : (cs==R)? (cnt-CNT_GREEN-CNT_YELLOW): (cs==Y)?(cnt-CNT_GREEN):cnt;
endmodule

全部评论

相关推荐

希望被捞的猫头鹰很理智:大概率待遇低怕硕士跑路
点赞 评论 收藏
分享
码农索隆:我寻思你这么激动,拿到offer了呢
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务