Verilog实现交通灯及仿真

要求实现一个简单功能十字路口交通灯
功能描述如下:
Verilog实现交通灯及仿真_第1张图片
S1状态25s,S2状态5s,S3状态25秒,S4状态5秒

一、源代码

  1. 状态机
module traffic2 (
    input clk,
    input rst_n,
    output reg [2:0] light1, //[green, red, yellow] 
    output reg [2:0] light2, //[green, red, yellow] 
    output [5:0] count
);

    reg [2:0] state ;
    parameter Idle = 3'd0 ;
    parameter S1 = 3'd1 ;
    parameter S2 = 3'd2 ;
    parameter S3 = 3'd3 ;
    parameter S4 = 3'd4 ;

    always @(posedge clk or negedge rst_n) begin
        if ( !rst_n ) begin
            state <= Idle;
            light1 = 3'b010;
            light2 = 3'b010;
        end
    end

    always @(*) begin
        case (state)
            Idle: if ( !rst_n ) begin
                state <= S1;
                light1 = 3'b100;
                light2 = 3'b010;
            end
            S1: if (count == 'd25) begin
                state <= S2;
                light1 = 3'b001;
                light2 = 3'b010;
            end
            S2: if (count == 'd30) begin
                state <= S3;
                light1 = 3'b010;
                light2 = 3'b100;
            end
            S3: if (count == 'd55) begin
                state <= S4;
                light1 = 3'b010;
                light2 = 3'b001;
            end
            S4: if (count == 'd0) begin
                state <= S1;
                light1 = 3'b100;
                light2 = 3'b010;
            end
        endcase
    end

    counter60 counter1(
        .clk(clk),
        .rst_n(rst_n),
        .count(count)
    );

endmodule
  1. 计数器
module counter60 (
    input clk,
    input rst_n,
    output reg [5:0] count
);

always @(negedge clk or negedge rst_n) begin
    if (!rst_n) begin
        count <= 'd0;
    end
    else if (count == 'd59) begin
        count <= 'd0;
    end
    else
        count <= count + 1;    
end

    
endmodule
  1. 顶层
`include "traffic2.v"
`include "counter60.v"

module top (
   input clk,
   input rst_n,
   output [2:0] light1, //[green, red, yellow] 
   output [2:0] light2, //[green, red, yellow] 
   output [5:0] count
);
   
   counter60 counter(
       .clk(clk),
       .rst_n(rst_n),
       .count(count)
   );

   traffic2 traffic(
       .clk(clk),
       .rst_n(rst_n),
       .light1(light1),
       .light2(light2),
       .count(count)
   );
   
endmodule`
  1. testbench
`timescale 1ns/1ps
module traffic_2_tb;

parameter timecycle = 10;

reg clk;
reg rst_n;
wire [2:0] light1;
wire [2:0] light2;
wire [5:0] count;

initial begin
    clk   = 0;
    rst_n = 1;
    #timecycle rst_n = ~rst_n;
    #timecycle rst_n = ~rst_n;
end
 
always #(timecycle/2) clk = ~clk;

top traffic_tb(
    .clk(clk),
    .rst_n(rst_n),
    .light1(light1),
    .light2(light2),
    .count(count)
);
    
endmodule

二、仿真结果

在这里插入图片描述

参考: https://blog.csdn.net/xunzhaotadeyingzi/article/details/80052902

你可能感兴趣的:(一位数字ICer的成长之路,fpga开发,verilog)