注意:以下是本人学习笔记,仅供参考。如有错误请留言,谢谢。
设计要求:每瓶可乐2.5元,每次只能投入一个硬币(硬币有1元和0.5元),要求投入2.5出可乐投入3元找零0.5。
设计思路:
理论上需要7个状态,但通过绘画状态图只需要5个状态。
通过设置2’b10和2b'01来表示投入1元硬币和投入0.5元硬币。
设计程序:
module mealy_cocl
(
input sys_clk, //系统时钟
input sys_rst_n, //复位信号
input half_money, //投入1元
input one_money, //投入0.5元
output reg cocl, //输出可乐
output reg to_half // 找零0.5元
);
reg [4:0] current_state; //设置状态
wire [1:0] cnt_money; //设置一个输入计数变量,1元和0.5元不能同时投入
//用 01 和 10 来表示投入的1元和0.5元
parameter IDLE = 5'b00001, //每个状态的形式,独热码
HALF = 5'b00010,
ONE = 5'b00100,
ONE_HALF = 5'b01000,
TWO = 5'b10000;
assign cnt_money = {one_money,half_money}; //2b'10表示投入1元
//2b'01表示投入0.5元
always@(posedge sys_clk or negedge sys_rst_n)
if(sys_rst_n == 1'b0)
current_state <= IDLE; //初始状态为IDLE
else case(current_state)
IDLE :if(cnt_money == 2'b01) //投入0.5进入下一个状态
current_state <= HALF;
else if(cnt_money == 2'b10) //投入1进入下两个状态
current_state <= ONE;
else
current_state <= IDLE; //不投入保持当前状态
HALF :if(cnt_money == 2'b01)
current_state <= ONE;
else if(cnt_money == 2'b10)
current_state <= ONE_HALF;
else
current_state <= HALF;
ONE :if(cnt_money == 2'b01)
current_state <= ONE_HALF;
else if(cnt_money == 2'b10)
current_state <= TWO;
else
current_state <= ONE;
ONE_HALF :if(cnt_money == 2'b01)
current_state <= TWO;
else if(cnt_money == 2'b10)
current_state <= IDLE;
else
current_state <= ONE_HALF;
TWO :if(cnt_money == 2'b01)
current_state <= IDLE;
else if(cnt_money == 2'b10)
current_state <= IDLE;
else
current_state <= TWO;
default:current_state <= ONE;
endcase
always@(posedge sys_clk or negedge sys_rst_n) //输出可乐
if(sys_rst_n == 1'b0) //复位信号有效时输出为低
cocl <= 1'b0;
else if((current_state == ONE_HALF) && (cnt_money == 2'b10))
cocl <= 1'b1;
else if((current_state == TWO) && (cnt_money == 2'b01))
cocl <= 1'b1;
else if((current_state == TWO) && (cnt_money == 2'b10))
cocl <= 1'b1;
else
cocl <= 1'b0;
always@(posedge sys_clk or negedge sys_rst_n) //找零
if(sys_rst_n == 1'b0)
to_half <= 1'b0;
else if((current_state == TWO) && (cnt_money == 2'b10))
to_half <= 1'b1;
else
to_half <= 1'b0;
endmodule
仿真设计:
`timescale 1ns / 1ns
module tb_mealy_cocl();
reg sys_clk;
reg sys_rst_n;
reg half_money;
reg one_money;
reg random_state; //设置一个随机数
wire cocl;
wire to_half;
initial // 初始化
begin
sys_clk = 1'b1;
sys_rst_n <= 1'b0;
#20
sys_rst_n <= 1'b1;
end
always #20 sys_clk = ~sys_clk; //每过20ns系统时钟翻转一次
mealy_cocl tb_mealy_cocl //将设计程序与仿真程序接口连接
(
.sys_clk (sys_clk),
.sys_rst_n (sys_rst_n),
.half_money (half_money),
.one_money (one_money),
.cocl (cocl),
.to_half (to_half)
);
always@(posedge sys_clk or negedge sys_rst_n) //生成一个随机数
if(sys_rst_n == 1'b0)
random_state <= 1'b0;
else
random_state <= {$random} % 2;
always@(posedge sys_clk or negedge sys_rst_n) //生成的随机数相当于投入的1元
if(sys_rst_n == 1'b0)
half_money <= 1'b0;
else
half_money <= random_state;
always@(posedge sys_clk or negedge sys_rst_n) //生成的随机数翻转相当于投入的0.5元
if(sys_rst_n == 1'b0)
one_money <= 1'b0;
else
one_money <= ~random_state;
endmodule
仿真图形: