Suyun 2023. 10. 6. 11:45

Conditions

I want to join the game with dice. During the clock cycle, between 1 to 6 numbers will be shown randomly. When BTNC is pressed, it should be clear. 

 

 

Design Sources

`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company: 
// Engineer: 
// 
// Create Date: 2023/10/04 13:07:07
// Design Name: 
// Module Name: Dice
// Project Name: 
// Target Devices: 
// Tool Versions: 
// Description: 
// 
// Dependencies: 
// 
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
// 
//////////////////////////////////////////////////////////////////////////////////


module Dice(
    input CLK,
    input BTNL, BTNR, BTNC,
    output reg [3:0] Random_L, Random_R
    );
    reg [3:0] random;
    
    always @(posedge CLK) begin
    if(BTNC) begin
    random <=4'b0000;
    Random_L <=random;
    Random_R <=random;
    end
    else if(BTNL) begin
    random <= $urandom_range(1, 6);
    Random_L <=random;
    end
    else if(BTNR) begin
    random <= $urandom_range(1, 6);
    Random_R <=random;
    end
    end
    
    
    
endmodule

Use the '$unrandom_range(X, Y)' function. X would be the minimum and Y would be the maximum.

 

 

Simulation Sources

`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company: 
// Engineer: 
// 
// Create Date: 2023/10/05 21:19:29
// Design Name: 
// Module Name: Dice_tb
// Project Name: 
// Target Devices: 
// Tool Versions: 
// Description: 
// 
// Dependencies: 
// 
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
// 
//////////////////////////////////////////////////////////////////////////////////


module Dice_tb;
    reg CLK;
    reg BTNL, BTNR, BTNC;
    wire [3:0] Random_L, Random_R;
    
    Dice UUT(.CLK(CLK), .BTNL(BTNL), .BTNR(BTNR), .BTNC(BTNC), .Random_L(Random_L), .Random_R(Random_R));
    
    always 
    begin
    #1 CLK <= ~CLK;
    end
    
    initial
    begin
    CLK=0;
    #5 BTNL <= 1;
    #5 BTNL <= 0;
    #5 BTNR <= 1;
    #5 BTNR <= 0;
    #5 BTNC <= 1;
    #5 BTNC <= 0;
    #5;
    $finish;
    end
  
endmodule

 

Testbench Waveform

If you want to control this code with the board, you have to add a constraint file too. However this time I just wanted to try the function which shows me random numbers, so I dropped the constraint file.