「Verilog学习笔记」交通灯

发布时间:2023年12月18日
专栏前言

本专栏的内容主要是记录本人学习Verilog过程中的一些知识点,刷题网站用的是牛客网

`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 idle = 0, s1_red = 1, s2_yellow = 2, s3_green = 3 ;
    reg [7:0] cnt ; 
    reg [1:0] state ; 
    reg p_red, p_yellow, p_green ; //用于缓存信号灯的前一时刻的数值,判断上升沿

    always @ (posedge clk or negedge rst_n) begin 
        if (~rst_n) begin 
            state <= idle ;
            p_red <= 0 ;
            p_green <= 0 ; 
            p_yellow <= 0 ; 
        end
        else case(state) 
            idle : begin 
                p_red <= 0 ; 
                p_green <= 0 ; 
                p_yellow <= 0 ; 
                state <= s1_red ; 
            end
            s1_red : begin 
                p_red <= 1 ; 
                p_green <= 0 ;
                p_yellow <= 0 ;
                if (cnt == 3) state <= s2_yellow ; 
                else state <= s1_red ; 
            end
            s2_yellow : begin
                p_red <= 0 ; 
                p_green <= 0 ; 
                p_yellow <= 1 ; 
                if (cnt == 3) state <= s3_green ; 
                else state <= s2_yellow ; 
            end
            s3_green : begin 
                p_red <= 0 ; 
                p_green <= 1 ; 
                p_yellow <= 0 ; 
                if (cnt == 3) state <= s1_red ; 
                else state <= s3_green ;
            end
        endcase
    end

    always @ (posedge clk or negedge rst_n) begin 
        if (~rst_n) cnt <= 10 ; 
        else if (pass_request && green && (cnt > 10)) cnt <= 10 ; 
        else if (~green && p_green) cnt <= 60 ; 
        else if (~yellow && p_yellow) cnt <= 5 ; 
        else if (~red && p_red) cnt <= 10 ; 
        else cnt <= cnt - 1 ; 
    end

    assign clock = cnt ; 

    always @ (posedge clk or negedge rst_n) begin 
        if (~rst_n) begin 
            yellow <= 0 ; 
            red <= 0 ; 
            green <= 0 ; 
        end
        else begin 
            yellow <= p_yellow ; 
            red <= p_red ; 
            green <= p_green ; 
        end
    end
    
	
endmodule
文章来源:https://blog.csdn.net/m0_54689021/article/details/135059818
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。