verilog 交通灯实验(使用状态机)
一、实验要求
- 包含一个counter与一个state转换模块
- 当reset为1时,则count为0,state=S0
- 当reset为0时,则开始数数,state切到绿灯
- 每过clk一周期则counter+1
- 绿灯时,当过25周期,则切到黄灯
- 黄灯时,当过2周期,则切到红灯
- 红灯时,每过15周期,则切到绿灯
以此循环。
二、状态机
三、程序实现
1、RTL代码
module traffic_light_ctl(
clk,
reset,
state
);
input clk,reset;
output [1:0]state;
reg [1:0]state_r;
localparam idle=0;
localparam green=1;
localparam yellow=2;
localparam red=3;
/******************************
计数模块
******************************/
reg [5:0]count;
reg clear;
always@(posedge clk or posedge reset)begin
if(reset|clear)
begin
count <= 0;
clear <= 0;
end
else
count <= count + 1;
end
/******************************
状态机
******************************/
reg [1:0]state_c,state_n;
//状态机第一段:对现态state_c进行赋值
always @(posedge clk or posedge reset)begin
if(reset)
state_c <= idle;
else
state_c <= state_n;
end
//状态机第二段:确定下一状态state_n
always @(*)begin
case(state_c)
idle: begin
count <=0;
state_n =green;
end
green: begin
if(count==24)
begin
state_n = yellow;
clear = 1;
end
else
state_n = green;
end
yellow: begin
if(count==1)
begin
state_n = red;
clear = 1;
end
else
state_n = yellow;
end
red: begin
if(count==14)
begin
state_n = green;
clear = 1;
end
else
state_n = red;
end
default:state_n = idle;
endcase
end
//状态机第三段:确定输出信号
always @(posedge clk or posedge reset)begin
if(reset)
state_r <= 0;
else if(state_c==green)
state_r <= 1;
else if(state_c==yellow)
state_r <= 2;
else if(state_c==red)
state_r <= 3;
else state_r <= 0;
end
assign state=state_r;
endmodule
2、仿真程序
`timescale 1ns / 1ps
module tb_traffic_light_ctl;
// traffic_light_ctl Inputs
reg clk= 0 ;
reg reset= 1 ;
// traffic_light_ctl Outputs
wire [1:0] state ;
initial
begin
forever #5 clk=~clk;
end
initial
begin
#10 reset = 0;
end
traffic_light_ctl u_traffic_light_ctl (
.clk ( clk),
.reset ( reset ),
.state ( state [1:0] )
);
endmodule
3、仿真结果