有限状态机实现交通灯
LIBRARY IEEE;
USE IEEE.STD_LOGIC_1164.ALL;USE IEEE.STD_LOGIC_UNSIGNED.ALL;
ENTITY trafficlight IS
PORT(key,clk:IN STD_LOGIC;
LED:OUT STD_LOGIC_VECTOR(0 TO 7);
seg:OUT STD_LOGIC_VECTOR(0 TO 3));
END ENTITY trafficlight;
ARCHITECTURE behave OF trafficlight IS
SIGNAL clk1,clk2:STD_LOGIC;
SIGNAL light1:INTEGER RANGE 0 TO 2 :=1;
SIGNAL light2:INTEGER RANGE 0 TO 2 :=0;
SIGNAL decade:INTEGER RANGE 0 TO 9; --十位
SIGNAL uint:INTEGER RANGE 0 TO 9; --个位
SIGNAL next_status:STD_LOGIC_VECTOR(0 TO 3):="1000"; --次状态
TYPE table1 IS ARRAY (0 TO 9) OF STD_LOGIC_VECTOR(0 TO 7);
SIGNAL tabnumber:table1:=(x"03",x"9f",x"25",x"0d",x"99",x"49",x"41",x"1f",x"01",x"09");
--0-9 显示
TYPE table2 IS ARRAY (0 TO 2) OF STD_LOGIC_VECTOR(0 TO 7);
SIGNAL tablight:table2:=(x"99",x"9f",x"25"); --红绿黄灯显示代码
BEGIN
p1:PROCESS(clk) --对50mhz 系统时钟进行 50m 的分频
VARIABLE count:INTEGER RANGE 0 TO 50000000;
BEGIN
IF (clk'EVENT AND clk='1') THEN
count:=count+1 ;
IF count=25000000 THEN
clk1<='1';
ELSIF count=50000000 THEN
clk1<='0';
count:=0;
END IF;
END IF;
END PROCESS p1;
p2:PROCESS(clk) --对50mhz 系统时钟进行 0.05m 的分频
VARIABLE count:INTEGER RANGE 0 TO 50000;
BEGIN
IF (clk'EVENT AND clk='1') THEN
count:=count+1 ;
IF (count=25000) THEN
clk2<='1';
ELSIF (count=50000) THEN
clk2<='0';
count:=0;
END IF;
END IF;
END PROCESS p2;
p3:PROCESS(clk2) --数码管显示
VARIABLE j:INTEGER RANGE 0 TO 4;
BEGIN
IF (clk2'EVENT AND clk2='1') THEN
j:=j+1;
IF j=4 THEN
j:=0;
END IF;
CASE j IS
WHEN 0 =>seg<="0111";
LED<=tablight(light1); --显示主干道交通灯状态
WHEN 1 =>seg<="1011";
LED<=tablight(light2); --显示次干道交通灯状态
WHEN 2 =>seg<="1101";
LED<=tabnumber(decade); --显示十位
WHEN 3 =>seg<="1110";
LED<=tabnumber(uint); --显示个位
WHEN OTHERS =>seg<="1111"; --关闭显示
END CASE;
END IF;
END PROCESS;
p4:PROCESS(clk1,clk) --交通灯状态控制
VARIABLE uin:INTEGER RANGE 0 TO 10:=1;
VARIABLE dec:INTEGER RANGE 0 TO 10:=1;
BEGIN
IF (clk1'EVENT AND clk1='1') THEN
IF (next_status="1000") THEN --状态1,主干道绿灯,次干道红灯
IF (uin=1 AND dec=1) THEN
IF (key='0') THEN
light1<=2;
light2<=0;
next_status<="0100";
uin:=6;
END IF;
ELSE
uin:=uin-1;
IF (uin=0) THEN
uin:=10;
dec:=dec-1;
END IF;
END IF;
END IF;
IF (next_status="0100") THEN --状态2,主干道黄灯,次干道红灯
IF (uin=1) THEN
light1<=0;
light2<=1;
next_status<="0010";
uin:=6;
dec:=3;
ELSE
uin:=uin-1;
END IF;
END IF;
IF (next_status="0010") THEN --状态3,主干道红灯,次干道绿灯
IF (uin=1 AND dec=1) THEN
light1<=0;
light2<=2;
next_status<="0001";
uin:=6;
ELSE
uin:=uin-1;
IF (uin=0) THEN
uin:=10;
dec:=dec-1;
END IF;
END IF;
IF (key='1') THEN
light1<=0;
light2<=2;
next_status<="0001";
uin:=6;
dec:=1;
END IF;
END IF;
IF (next_status="0001") THEN --状态4,主干道红灯,次干道黄灯
IF (uin=1) THEN
light1<=1;
light2<=0;
next_status<="1000";
dec:=5;
uin:=6;
ELSE
uin:=uin-1;
IF (uin=0) THEN
uin:=10;
dec:=dec-1;
END IF;
END IF;
END IF;
uint<=uin-1;
decade<=dec-1;
END IF;
END PROCESS;
END ARCHITECTURE behave;