基于Verilog用状态机设计交通灯控制器
时间:2023-10-26 10:07:02
1.标题:交通灯控制器采用状态机设计,设计要求:A路和B路有红、黄、绿三种灯,持续时间为45盏红灯s、黄灯5s、绿灯40s。A转移到B路和B路交通灯的状态
(1)A红,B绿色(持续时间40s);
(2)A红,B黄(持续时间5s);
(3)A绿,B红(持续时间40s);
(4)A黄,B红(持续时间5s)。
2.Verilog代码(仅供参考!
module traffic_lights(input clk50M,rst,//时钟,复位输入信号 output reg[5:0] lout);//输出6位2进制数点亮相应的灯 reg[30:0] count;//存计数用约21亿>20亿,基于50M晶振最多可计时40多次s reg state;///灯的状态 parameter S0=2'b00,S1=2'b01,S2=2'b10,S3=2'b11.//灯的四种状态用四种不同的2进制表示 parameter extinguish_all=6'b000000,red_green=6'b100010,red_yellow=6'b100001,green_red=6'b010100,yellow_red=6'b001100;//点亮相应状态的灯程序,不同的FPGA板子可能不一样 //计数 always@(posedge clk50M or posedge rst) begin if(rst) count<=0./如果复位,计数清零 else count<=count 1.//否则,每个时钟上升一次count 1 end //状态机 always@(posedge clk50M or posedge rst) begin if(rst) begin//如果复位 state<=S0;//变成灯状态S0 lout<=extinguish_all;///暂时灯全部熄灭 end else begin case(state) S0:begin lout<=red_green;///输出灯状态为A红灯,B绿灯,让它们保持40s if(count>=2000_000_/如果计时到4000s begin state<=S1;//灯进入S1状态 count<=0;//count归0 end else state<=S0;//否则,灯保持S0状态 end S1:begin lout<=red_yellow;///输出灯状态为A红灯,B黄灯,并让它们保持5s if(count>=250_000_000)/s begin state<=S二、//灯进入S2状态 count<=0;//count归0 end else state<=S1;//否则,灯保持S1状态 end S2:begin lout<=green_red;///输出灯状态为A绿灯,B红灯,让它们保持40s if(count>=2000_000_/如果计时到4000s begin state<=S三、//灯进入S3状态 count<=0;//count归0 end else state<=S2;//否则,灯保持S2状态 end S3:begin lout<=yellow_red;///输出灯状态为A黄灯,B红灯,保持5s if(count>=250_000_000)/s begin state<=S0;//回灯S0状态 count<=0;//count归0 end else state<=S3;//否则,灯保持S3状态 end default: begin//出故障 state<=S0;//变成灯状态S0 count<=0;//计数清零 lout<=extinguish_all;///暂时灯全部熄灭 end endcase end end endmodule