一、功能
功能描述
:
1
)初始状态:主路绿灯、支路红灯;
2
)检测到支路有车
(X=1),灯状态的变化过程为:
①主路变黄灯、支路红灯
②主路变红灯、支路红灯
③主路红灯、支路变绿灯
3)当支路没车(X=0),灯状态的变化过程为:
①主路红灯、支路绿灯
②主路红灯、
支路变黄灯
③主路绿灯、支路变红灯
道路示意图如下:
![](https://img-blog.csdnimg.cn/0c4c1c48143440bda53d502b01a3bb9d.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA5LiN5Lya5YaZ5Luj56CB55qE6I-c6bih,size_8,color_FFFFFF,t_70,g_se,x_16)
二、状态分析
对于以上转换过程,可以采用状态机电路来描述:
状态描述:
S0:主路绿灯亮,支路红灯亮; 检测到支路有车
(X=1),
进入
S1;
S1:主路黄灯亮,支路红灯亮, 延时进入
S2
;
S2:主路红灯亮,支路红灯亮, 延时进入
S3
;
S3:主路红灯亮,支路绿灯亮;检测到支路没车(X=0)进入S4;
S4:主路红灯亮,支路黄灯亮;延时进入S0;
S0:主路绿灯亮,支路红灯亮
![](https://img-blog.csdnimg.cn/a27e6d841f32403da18700a8f7bd1350.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA5LiN5Lya5YaZ5Luj56CB55qE6I-c6bih,size_10,color_FFFFFF,t_70,g_se,x_16)
三、verilog实现
用三段式状态机实现交通灯电路,设计和TB代码如下:
// Design Name: traffic_light
// Module Name: traffic_light
// Description: ↓ ↓ ↓
// Create Date: 2022/3/28
/*
state:
s0: main-green, branch-red, when x=1 s0->s1
s1: main-yellow, branch-red, delay s1->s2
s2: main-red, branch-red, delay s2->s3
s3: main-red, branch-green, when x=0 s3->s4
s4: main-red, branch-yellow, delay s4->s1
port:
input: clk,rst_n,x
output: main, branch
*/
`timescale 1ns / 1ps
module traffic_light(
input clk,
input rst_n,
input x,
output reg [1:0] main,
output reg [1:0] branch
);
parameter green = 2'd1,
yellow = 2'd2,
red = 2'd3;
parameter s0 = 3'd0,
s1 = 3'd1,
s2 = 3'd2,
s3 = 3'd3,
s4 = 3'd4;
reg [3:0] state;
reg [3:0] next_state;
//state transfer
always @(posedge clk or negedge rst_n) begin
if(!rst_n)
state <= s0;
else
state <= next_state;
end
//transfer logic
always @(*)begin
case(state)
s0: next_state = x ? s1 : s0;
s1: #600 next_state = s2;
s2: #600 next_state = s3;
s3: next_state = x ? s3 : s4;
s4: #600 next_state = s0;
default: next_state = state;
endcase
end
//output
always @(posedge clk or negedge rst_n)begin
if(!rst_n)begin
main <= green;
branch <= red;
end
else begin
case(state)
s0: begin main <= green; branch <= red; end
s1: begin main <= yellow; branch <= red; end
s2: begin main <= red; branch <= red; end
s3: begin main <= red; branch <= green; end
s4: begin main <= red; branch <= yellow; end
default: begin main <= green; branch <= red; end
endcase
end
end
endmodule
testbench:
`timescale 1ns / 1ps
module tb_traffic_light();
parameter period = 10; //100mhz
reg clk;
reg rst_n;
reg x;
wire [1:0] main;
wire [1:0] branch;
always #(period/2) clk = ~clk;
initial begin
clk = 1'b0;
rst_n = 1'b0;
x = 0;
#60
rst_n = 1'b1;
#1234
x = 1;
#1234
x = 0;
end
traffic_light u_traffic_light(clk,rst_n,x,main,branch);
endmodule
四、仿真&综合
仿真结果:
综合结果: