端口说明:
Clock:输入时钟信号,上升沿有效。 Reset:复位信号,高电平有效。
Red1、yellow1、green1:分别表示A路的红灯、黄灯、绿灯显示信号,高电平有效。
Red2、yellow2、green2:分别表示B路的红灯、黄灯、绿灯显示信号,高电平有效。
Timea:A路绿灯亮时间,高电平有效。 Timeb:B路红灯亮时间,高电平有效。 Alarm:倒计时信号输出
实现程序:
module
traffic_control(clock,reset,red1,yellow1,green1,red2,yellow2,green2,timea,timeb,alarm); input clock,reset;
output red1,yellow1,green1,red2,yellow2,green2,alarm; output [7:0] timea,timeb; reg [1:0] state=2'b00;
reg [7:0] timea=40; //A路绿灯亮时间 reg [7:0] timeb=45; //B路红灯亮时间
reg red1=1'b0,yellow1=1'b0,green1=1'b1; //A绿灯亮 reg red2=1'b1,yellow2=1'b0,green2=1'b0; //B红灯亮 reg alarm=1'b0;
always @(posedge clock or posedge reset) begin
if (reset) begin
state<=2'b00; timea<=40; timeb<=45; end else begin
case (state) 2'b00: begin
if (timea==0) //A绿灯亮时间40S结束 begin
timea<=5; //A黄灯亮时间5S
red1<=1'b0; yellow1<=1'b1; green1<=1'b0; //A黄灯亮 red2<=1'b1; yellow2<=1'b0; green2<=1'b0; //B红灯继续亮
state<=2'b01; //转到A黄灯,B红灯 end else begin
timea<=timea-1; //A绿灯亮时间40S-- timeb<=timeb-1; //B红灯亮时间45S-- state<=2'b00; end end 2'b01:
begin
if (timea==0) //A黄灯亮5S时间结束 begin
timea<=45; //A红灯亮时间45S timeb<=40; //B绿灯亮时间40S
red1<=1'b1; yellow1<=1'b0; green1<=1'b0; //A红灯亮 red2<=1'b0; yellow2<=1'b0; green2<=1'b1; //B绿灯亮 alarm<=1'b0;
state<=2'b10; //转到A红灯,B绿灯 end else begin
timea<=timea-1; //A黄灯亮时间3S-- timeb<=timeb-1; //B红灯亮时间3S-- alarm<=~alarm; yellow1<=~yellow1;
state<=2'b01; end end
2'b10:
begin
if (timeb==0) //B绿灯亮40S时间结束 begin
timeb<=5; //B灯黄亮时间5S
red1<=1'b1; yellow1<=1'b0; green1<=1'b0; //A红灯亮 red2<=1'b0; yellow2<=1'b1; green2<=1'b0; //B黄灯亮 state<=2'b11; //转到A红灯,B黄灯 end else begin
timea<=timea-1; //A红灯亮时间-- timeb<=timeb-1; //B绿灯亮时间-- state<=2'b10; end end
2'b11: begin
if (timeb==0) //B黄灯亮5S时间结束 begin
timea<=40; //A绿灯亮时间40S timeb<=45; //B绿灯亮时间45S
red1<=1'b0; yellow1<=1'b0; green1<=1'b1; //A绿灯亮 red2<=1'b1; yellow2<=1'b0; green2<=1'b0; //B红灯亮 alarm<=1'b0;
state<=2'b00; //转到A绿灯,B红灯 end else
begin
timea<=timea-1; //A红灯亮时间-- timeb<=timeb-1; //B黄灯亮时间-- alarm<=~alarm; yellow2<=~yellow2; state<=2'b11; end
end endcase end end
Endmodule
编译结果:
此模块是整个系统的核心部分,主要功能是完成四个状态的转换,并且在每个状态里完成相应的控制作用,即控制主干道和支干道的红黄绿灯的点亮和各自数码管倒计时显示。
【bin2bcd转换模块】
该模块将二进制语言转换为BCD码输出,模块如下图:
端口说明:
numin[7..0]:输入8位二进制编码 numa[3..0]:输出高4位BCD码 numb[3..0]:输出低4位BCD码
bin2bcd转换模块实现程序:
module bin2bcd(numin,numa,numb); input[7:0] numin;
output[3:0] numa,numb; reg[3:0] numa,numb; always @(numin) begin
if (numin>=90) begin numa=9; numb=numin-90; end
else if (numin>=80) begin numa=8; numb=numin-80; end else if (numin>=70) begin numa=7; numb=numin-70; end else if (numin>=60) begin numa=6; numb=numin-60; end else if (numin>=50) begin numa=5; numb=numin-50; end else if (numin>=40) begin numa=4; numb=numin-40; end else if (numin>=30) begin numa=3; numb=numin-30; end else if (numin>=20) begin numa=2; numb=numin-20; end else if (numin>=10) begin numa=1; numb=numin-10; end else begin numa=0; numb=numin; end end endmodule
编译结果: