Welcome to IDI Electronica!!!



Welcome!!! IDI Electronica is a blog for my personal projects and articles to help electronics enthusiasts like me.

Bienvenidos!!! IDI Electronica es un blog con mis proyectos personales y artículos con el fin de ayudar a entusiastas de la electrónica como yo.

Saturday, June 21, 2014

Finite State-Machine in Verilog - Using button toggle

This is a code sample for a finite state-machine using Verilog and was tested using the Mojo FPGA board.

The code turns on one of the 8 LED in the Mojo board at a time. The lit LED transitions using the on-board Reset button.


Code Sample:

module LED_state_machine(

    input   clk,    
// 50MHz clock input
    input   nRst,
    // input from reset button
    input   cclk,   
// clock input from AVR microcontroller
    output  reg[7:0]led,  
// output 8 onboard LEDs  
    

    // all connection below are for the microcontroller in Mojo

    output  spi_miso,          // SPI connections for AVR
    input   spi_ss,
    input   spi_mosi,
    input   spi_sck,

    output  [3:0] spi_channel, // AVR ADC channel select   
    input   avr_tx,            // AVR Tx => FPGA Rx
    output  avr_rx,            // AVR Rx => FPGA Tx
    input   avr_rx_busy        // AVR Rx buffer full
    );

// for Mojo only. these signals should be high-z when not used.


assign  spi_miso = 1'bz;
assign  avr_rx = 1'bz;
assign  spi_channel = 4'bzzzz;


reg       rst;     // create registers for button press and state

reg  [3:0]state=0;

always@(posedge clk)
 rst <= ~nRst;     // connects reset button to rst register


//beginning of state-machine
always@(posedge rst)  // state-machine will respond with rst press
begin
    case(state)
        3'd0: begin
                led[7:0]<=8'b0000_0001;  // only led[0] is hi
                state <= 3'd1;           // jump to state 3'd1
              end
        3'd1: begin
                led[7:0]<=8'b0000_0010;  

                state <= 3'd2;          
              end           
        3'd2: begin
                led[7:0]<=8'b0000_0100;
                state <= 3'd3;
              end
        3'd3: begin
                led[7:0]<=8'b0000_1000;
                state <= 3'd4;
              end
        3'd4: begin
                led[7:0]<=8'b0001_0000;
                state <= 3'd5;
              end
        3'd5: begin
                led[7:0]<=8'b0010_0000;
                state <= 3'd6;
              end
        3'd6: begin
                led[7:0]<=8'b0100_0000;
                state <= 3'd7;
              end
        3'd7: begin
                led[7:0]<=8'b1000_0000; // back to state 0
                state <= 3'd0;          

              end
     default: state <= 3'b0; 
    endcase
end

endmodule

   

No comments:

Post a Comment