Verilog Code for Traffic Light
Traffic Light:
It is a traffic signal controller for traffic at the intersection of a main highway and country road:
➢ The traffic signal for the main highway gets highest priority because cars are continuously present on the main highway. Thus, the main highway signal remains green by default.
➢ As soon as there are no cars on the country road, the country road traffic signal turns yellow and then red and the traffic signal on the main highway turs green again.
➢ There is a sensor to detect cars waiting on the country road. The sensor sends a signal X as input to the controller. X=1, if there are cars on the country road; otherwise, X=0.
➢ There are delays on transition fromS1 to S2, from S2to S3, and from S4 to S0. The delays must be controllable.
Verilog Code for Traffic Light:
`define TRUE 1'b1
`define FALSE 1'b0
//parameter
`define RED 2'd0
`define YELLOW 2'd1
`define GREEN 2'd2
//STATE DEFINITION HWY CNTRY
`define S0 3'd0 //GREEN RED
`define S1 3'd1 //YELLOW RED
`define S2 3'd2 //RED RED
`define S3 3'd3 //RED GREEN
`define S4 3'd4 //RED YELLOW
//DELAYS
`define Y2RDELAY 3
`define R2GDELAY 2
module traffic_sig_ctrl(hwy,cntry,X,clock,clear);
output[1:0] hwy,cntry; //2-bit output for 3states of signal red,green,yellow
reg[1:0] hwy,cntry; //declared output signals are registers
input X,clear,clock; //if x true, indicate car on cntry road else false
reg[2:0] state,next_state;
initial
begin
state=`S0;
next_state=`S0;
hwy=`GREEN;
cntry=`RED;
end
always@(posedge clock)
state=next_state;
//compute values of main signal and country signal
always@(state)
begin
case(state)
`S1:begin
hwy=`YELLOW;
cntry=`RED;
end
`S2:begin
hwy=`RED;
cntry=`RED;
end
`S3:begin
hwy=`RED;
cntry=`GREEN;
end
`S4:begin
hwy=`RED;
cntry=`YELLOW;
end
endcase
end
//state machine using case statements
always@(state or clear or X)
begin
if(clear)
next_state=`S0;
else
case(state)
`S0:if(X)
next_state=`S1;
else
next_state=`S0;
`S1:begin
repeat(`Y2RDELAY)@(posedge clock)
next_state=`S2;
end
`S2:begin
repeat(`R2GDELAY)@(posedge clock)
next_state=`S3;
end
`S3:if(X)
next_state=`S3;
else
next_state=`S4;
`S4:begin
repeat(`Y2RDELAY)@(posedge clock);
next_state=`S0;
end
default:next_state=`S0;
endcase
end
endmodule
0 Comments