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.
Showing posts with label verilog. Show all posts
Showing posts with label verilog. Show all posts

Monday, March 21, 2016

Divisor de Frecuencia por Número Impar con Ciclo de Trabajo de 50%

1. INTRODUCCION

En uno de mis artículos expliqué cómo dividir la frequencia de una señal de reloj para crear señales de reloj con frecuencias menores.  El concepto es muy simple, esperamos que cierto número de ciclos del reloj pasen y cambiamos nuestra señal de salida de 0 a 1, o de 1 a 0.  Por ejemplo,  la figura 1 describe el diagrama de tiempo de un divisor de frecuencia por 12.  Por cada 6 ciclos del reloj de entrada, el valor de la señal de salida cambia.


Fig 1. Diagrama de tiempo de divisor de frecuencia por 12


Si observamos el diagrama de tiempo, notamos que el contador de ciclos usa el borde de subida del reloj como referencia (instante en que el reloj cambia de 0 a 1).  Debido a ésto, el circuito es fácil de diseñar si la frecuencia es dividida por un número par.  Sin embargo, el circuito se vuelve más complicado si queremos dividir la frecuencia por un número impar.  Si observamos la figura 2, un divisor de reloj impar necesita usar el borde de subida y el de bajada del reloj.  Por lo tanto, un simple contador de bordes de subida no sirve en estos casos.


Fig 2. Diagrama de tiempo de divisor de frecuencia por 5


2. DESCRIPCION DEL CIRCUITO

Para dividir la frecuencia de un reloj digital por un número impar, necesitamos crear otras señales e implementar lógica secuencial y combinacional.

La forma más sencilla de entender cómo funciona el circuito es observando el diagrama de tiempo en la figura 3 y siguiendo las instrucciones que escribí a continuación:

- Nuestro circuito divide la frecuencia de un reloj por el número impar N.  En este ejemplo, N=5.

- La señal clk_in es nuestro reloj de entrada con frecuencia 500MHz y con ciclos de 2ns.

- El bus de señales Count es un contador de ciclos de entrada clk_in y reinicia a 0 cuando el contador llega a N-1. Para nuestro ejemplo, N-1 = 4, o sea 0100 en binario.

- La señal A es igual a 1 sólo cuando el valor en el contador Count es 0001.  Sino, es 0.

- La señal B es igual a 1 sólo cuando el valor en el contador Count es (N+1)/2.  Para nuestro ejemplo, (5+1)/2 = 3, o 0011 en binario.

- La señal Tff_A es un biestable T (T flip flop) activado por el borde de caída de la señal A.

- La señal Tff_B es un biestable T (T flip flop) activado por el borde de caída del reloj y sólamente cuando la señal B es 1.

- La señal clk_out es nuestro reloj de salida.  Para producir esta señal, usamos una puerta XOR entre las señales Tff_A y Tff_B.  La señal clk_out es alta cuando Tff_A y Tff_B son diferentes (10,01) y baja cuando ambas señas son iguales (11, 00). En nuestro ejemplo creamos una señal con frecuencia de 100MHz y ciclos de 10ns.


Fig 3. Diagrama de tiempo mostrando las señales usadas en divisor frecuencia por 5


Para una explicación más técnica de lo que hice en este circuito, les recomiendo que lean la hoja de aplicación AND8001-D publicada por ON Semiconductors.


3.  Implementación en Verilog

Para crear el circuito descrito en la sección anterior, debemos utilizar lógica secuencial (biestables, registros, etc) y lógica combinacional (puertas lógicas).

A continuación les dejo el código para el divisor de frecuencia por 5, el cual también se encuentra disponible en mi repositorio de Github  https://github.com/sphanlung/FPGA/blob/master/clk_div_odd.v 



module clk_div_odd(
input clk_in,
output  clk_out
    );

reg  [3:0] count = 4'b0;        //4-bit counter
reg    A1 = 0;
reg       B1 = 0;
reg     Tff_A = 0;
reg   Tff_B = 0;
wire   clock_out;
wire   wTff_A;
wire   wTff_B;

//Connects registers to wires for combinational logic
assign   wTff_A  = Tff_A;
assign   wTff_B  = Tff_B;

assign   clk_out = wTff_B ^ wTff_A; //XOR gate 

//Counter for division by N
always@(posedge clk_in)
begin
if(count == 4'b0100) //Count to N-1 (4) 
begin // Example: Use 4 to divide by 5        
    count <= 4'b0000;
end
else
begin
count <= count + 1;
end
end

//Set A to high for one clock cycle when counter is 0
always@(posedge clk_in)
begin
if(count == 4'b0000)
A1 <= 1;
else
A1 <= 0;
end

//Sets B to high for one clock cycle when counter is (N+1)/2
always@(posedge clk_in)
begin
if(count == 4'b0011) //Use (N+1)/2
B1 <= 1; //Ex: (5+1)/2 = 3
else
B1 <= 0;
end

//T flip flop toggles 
always@(negedge A1) // Toggle signal Tff_A 
begin  //whenever A1 goes from 1 to 0
Tff_A <= ~Tff_A;
end

always@(negedge clk_in)
begin
if(B1) // Toggle signal Tff_B whenever   
   begin //B1 is 1
Tff_B <= ~Tff_B;
end
end

endmodule




Fig 4. Diagrama de RTL generado por Xilinx ISE

Thursday, March 10, 2016

Frequency Divider by Odd Numbers with 50% Duty Cycle

1. Theory

Frequency or clock dividers are among the most common circuits used in digital systems.  The timing diagram in figure 1 (originally used in this article) describes a circuit that divides the input frequency by 12.  The circuit simply counts the rising edges of 6 input clock cycles(clk) and then toggles the output clock signal from 1 to 0 or vice-versa.



Fig 1. Timing diagram of frequency divider by 12


This works great when your input frequency is divided by an even number.  But things get a little more complicated when we try to divide the frequency by an odd number, since we can't simply divide the number of input clock cycles by 2.  If we observe the timing diagram describing a frequency divider by 5 in figure 2, the output clock toggles in the middle of the 3rd input clock cycle and before we are able to  complete our count.



Fig 2. Timing diagram of frequency divider by 5




2. Circuit Description

To divide a frequency by an odd number we will need to create a few more signals to use both sequential and combinational logic.
The easiest way of understanding the circuit is by observing the timing diagram below (figure 3):

- Assume we want to divide our frequency by N.  For this example, N=5.

- The signal clk_in is our input clock and each cycle is 2ns long, giving us a frequency of 500MHz.

- The signal bus Count is our counter and will reset to 0 after counting (N-1) clk_in cycles. For our example, our counter will count up to 4 (b'0100) since 0 also counts as a number.

- Signal A is set to high (1) whenever the counter is 1 (Count=0001). Otherwise, it stays low (0).

- Signal B is set to high (1) whenever the counter is (N+1)/2. For our example, we used Count=3 (b'0011) since (5+1)/2=3.

- Signal Tff_A is a T flip flop triggered by the falling edge of signal A. Whenever, A goes from 1 to 0, Tff_A is toggled.

- Signal Tff_B is a T flip flop triggered by the falling edge of clk_in only if B is high (1).  Whenever B is high, Tff_B will be toggled at the falling edge of the input clock.

- The signal clk_out is our output clock.  To produce this signal, we use an XOR gate between the signals Tff_A and Tff_B.  The output of an XOR gate is high (1) when the two input signals are different (01, 10) and low (0) if the signals are the same (00, 11).  Each cycle of the output clock takes 10ns, with a frequency of 50MHz.



Fig 3. Timing diagram showing all signals required for frequency divider by 5


A more technical explanation on how to divide clocks by odd numbers can be found in the application note AND8001-D published by ON Semiconductors.



3. Verilog Implementation


In order to create the circuit described in the previous section, we had to use both sequential circuits (flip flops, reg type variables) and combinational logic (gates, wire type variables).

The Verilog code for a Frequency Divider by 5 can also be downloaded from my Github repository at https://github.com/sphanlung/FPGA/blob/master/clk_div_odd.v 



module clk_div_odd(
input clk_in,
output clk_out
    );

reg  [3:0] count = 4'b0;        //4-bit counter
reg  A1 = 0;
reg     B1 = 0;
reg  Tff_A = 0;
reg  Tff_B = 0;
wire  clock_out;
wire  wTff_A;
wire  wTff_B;

//Connects registers to wires for combinational logic
assign wTff_A  = Tff_A;
assign wTff_B  = Tff_B;

assign clk_out = wTff_B ^ wTff_A; //XOR gate 

//Counter for division by N
always@(posedge clk_in)
begin
if(count == 4'b0100) //Count to N-1. 
begin // Example: Use 4 to divide by 5        
    count <= 4'b0000;
end
else
begin
count <= count + 1;
end
end

//Set A to high for one clock cycle when counter is 0
always@(posedge clk_in)
begin
if(count == 4'b0000)
A1 <= 1;
else
A1 <= 0;
end

//Sets B to high for one clock cycle when counter is (N+1)/2
always@(posedge clk_in)
begin
if(count == 4'b0011) //Use (N+1)/2
B1 <= 1; //Ex: (5+1)/2 = 3
else
B1 <= 0;
end

//T flip flop toggles 
always@(negedge A1) // Toggle signal Tff_A 
begin  //whenever A1 goes from 1 to 0
Tff_A <= ~Tff_A;
end

always@(negedge clk_in)
begin
if(B1) // Toggle signal Tff_B whenever   
   begin //B1 is 1
Tff_B <= ~Tff_B;
end
end

endmodule



Fig 4. RTL schematic generated by Xilinx ISE




Thursday, November 12, 2015

Creación de un Proyecto con la Placa de Desarrollo de FPGA Terasic DE0-Nano

El DE0-Nano es una de las placas de desarrollo para FPGA más populares debido a su bajo costo (menos de $100) y porque usa el FPGA Cyclone IV de Altera. El Cyclone IV es un circuito integrado lógico de bajo costo y bajo consumo de poder con más de 22 mil elementos lógicos.

La placa contiene:

- 2 conectores de 20 pines, 72 GPIO (pines de entrada y salida), dos pines de +5V, dos de +3V3 y cuatro de tierra
- 1 conector de 26 pines, 18 GPIO y 8 pines de entrada analógica para el ADC
- 1 ADC (convertidor de señal analógica a digital) de 12 bits
- 1 EEPROM de 2Kb (memoria reprogramable)
- 1 acelerómetro

Fig 1. Placa de Desarrollo de FPGA Terasic DE0-Nano


Terasic también provee programas para facilitar el uso del DE0-Nano: El panel de control (Control Panel) y el creador de sistemas (System Builder). El Control Panel permite comunicaciones y control del DE0-Nano desde una computadora. Desafortunadamente, tuve problemas para instalar el programa en mis 2 computadoras, por lo que no lo incluiré en esta guía.

El System Builder es una herramienta bastante útil que simplemente crea los archivos necesarios para comenzar un proyecto. Los archivos creados incluyen:
- .QPF: Archivo proyecto para Altera Quartus II
- .V: Archivo de Verilog declarando los puertos de entrada y salida del FPGA
- .QSF: Archivo con la asignación y configuración de pines de FPGA
- .SDC: Archivo para verificación y prueba de tiempos
- .HTML: Descripción detallada de cada pin


Fig 2. Mapa físico del DE0-Nano

Toda la información en esta guía puede ser encontrada en la página web de Terasic (en inglés) en la pestaña “Resources”. A continuación les dejo los pasos para crear un proyecto en el DE0-Nano.



1. PREPARACION DEL SOFTWARE


1.1. Software de Altera

Primero, necesitamos descargar Quartus II de la página web de Altera. Quartus II es un ecosistema que nos permite compilar, sintetizar, verificar y analizar nuestro código, además de crear mapas de RTL, simulaciones, entre otras cosas.

A menos que tengas acceso a una licencia pagada, vamos a usar la versión Web Edition.


Fig 3. Altera Quartus II main window


Puedes descargar Quartus II v15.0 y ModelSim en la página web de Altera. El archivo pesa varios GB y tarda entre 10 a 20 minutos en instalar debido a su tamaño.


1.2. Software de Terasic

El DE0-Nano viene acompañado de un CD-ROM con los manuales, proyectos de muestra y los programas necesarios para usar nuestra placa. Si no tienes el CD-ROM, puedes descargar una copia en la página de Terasic.

Es posible crear nuestro proyecto sin utilizar el System Builder. Sin embargo, ese programa nos ahorrará bastante tiempo al crear el archivo QSF de sistema.


1.3. Altera USB Blaster

Para poder conectar el FPGA con Quartus II necesitamos instalar el driver respectivo. Por fortuna, este viene incluido con la descarga de Quartus II, pero tiene que ser instalado manualmente.

Para instalar el driver:

- Conecta el DE0-Nano a tu computadora utilizando un cable de mini-USB.
- Abre el menú de Inicio y escribe “Administrador de Dispositivos” o “Device Manager” dependiendo de tu versión de Windows.
- Una vez abierto el Administrador, busca la opción para “Otros Dispositivos”.
- Haz click con el botón derecho del ratón en el dispositivo con la símbolo amarillo y selecciona “Actualizar software de Controlador...”
- Luego, selecciona Buscar Controlador en mi Computadora y selecciona la carpeta donde Quartus II esta instalado. Asegúrate de seleccionar el cuadrito para Incluir Subcarpetas.



2. CREACION DEL PRIMER PROYECTO

2.1. System Builder

Necesitamos dos archivos para comenzar: El archive de proyecto para Quartus II (QPF) y el archivo de configuración (QSF). Afortunadamente, el System Builder puede crearlos por nosotros.

- En el CD-ROM, abre la carpeta Tools y dentro de ésta, la carpeta DE0_Nano_SystemBuilder. En ella encontrarás el archivo ejecutable DE0_Nano_SystemBuilder.ex
- Una vez abierto el System Builder, nombra tu proyecto,  selecciona “GPIO Default” y crea un nombre genérico para ambos conectores.
- Luego, selecciona “Generate” y escoge dónde quieres guardar tu nuevo proyecto.


Fig 4. Terasic DE0-Nano System Builder


2.2. Quartus II

- Abre la carpeta donde creaste tu Nuevo proyecto y abre el archive QPF. Esto abrirá el programa Quartus II.
- Haz click en el menú Project (proyecto) y luego en Add/Remove Files (agregar/remover archivos) y luego sobre el ícono con los puntos suspensivos (…)
- Busca y elige el archivo con formato .V (Verilog) y luego haz click en Add y luego en OK.
- Double click on the Verilog file to see the template for our project.
- En la ventana principal de Quartus II, busca la pestaña Files para ver los archivos en el proyecto y haz doble click sobre el archivo de Verilog que agregaste.


Fig 5. Agregando archivos a proyecto


Fig 6. Quartus II mostrando los archivos en el proyecto


El archivo de verilog contiene las instancias de cada pin del FPGA gracias al System Builder.

Como nuestro objetivo es simplemente crear un circuito para probar nuestra placa, reemplaza el código en tu archivo Verilog con el código que les dejo a continuación.

NOTA: El módulo principal tiene que tener el mismo nombre que el proyecto. En mi caso, uso el nombre Project1.


module Project1(        // Modulo principal debe tener mismo nombre
input CLOCK_50,         // que el archive de proyecto
output reg [7:0]LED
);

reg   [25:0]count;     
reg   clk2;
reg   state=0;

// divisor de freqcuencia 50MHz a 1Hz
always@(posedge CLOCK_50)
    begin
        if(count==26'd25_000_000)    // cuenta hasta 25M ciclos de reloj
            begin                    // cambia clk2 hi or lo
             count<=0;               
             clk2 <= ~clk2;         
            end
        else
            begin
             count<=count+1;
            end
    end    

// maquina de estados para LEDs
always @(posedge clk2)
      begin
             case(state)
             1'b0:      begin
                  LED[7:0] <= 8'b01010101;
                  state <= 1'b1;
                  end
            1'b1:       begin
                  LED[7:0] = 8'b10101010;
                  state <= 1'b0;
                  end
            Default: begin
                  state <= 1'b0;
                  end
            endcase    
      end
endmodule


El código hace dos cosas, crea un divisor de reloj de 1Hz y crea una máquina de estados para hacer parpadear los LED en la placa.

Si no deseas copiar y pegar el codigo que les deje arriba, puedes descargarlo en un archivo de Verilog desde mi repositorio de Github bajo el nombre Project1.v
Recuerda cambiar el nombre del archivo y del módulo principal con el mismo nombre de tu proyecto. Sólamente necesitas agregarlo a tu proyecto (ver sección 2.2).



2.3. Compilación el Proyecto

- Cuando tu código de Verilog este listo, haz doble click en Compile Design. El proceso normalmente tarde uno o dos minutos dependiendo de tu sistema.
- Asumiento que no hay errores, haz doble click en EDA Netlist Writer para crear un archivo binario para configurar el FPGA.
- Finalmente, haz doble click en Program Device para abrir el programador de Quartus II.


2.4. Configuración el FPGA

- En la ventana principal de Quartus II Programmer debe de aparecer el archivo SOF creado por tu proyecto.
- En la esquina superior izquierda, haz click en Hardware Setup y selecciona “USB-Blaster”. Si no te aparece esa opción, mira la sección 1.3 de esta guía.
- Finalmente, haz click en “Start” en la ventana principal de Programmer y mira tu DE0-Nano en acción.

Nota: Los FPGA son dispositivos volátiles, por lo tanto perderás la configuración apenas desconectes la fuente de poder. Para mantener la configuración, debes de guardarla en la memoria flash montada en la placa.

Fig 7. Seleccionando hardware para programar el dispositivo


Fig 8. Notificación de programación exitosa del FPGA


2.5. Código de Prueba DE0-Nano


Si simplemente deseas probar tu placa, puedes descargar el archivo SOF que he creado para este proyecto y cargarlo en el FPGA usando Quartus II Programmer (ver sección 2.4)




Sunday, October 18, 2015

Creating a Project with the Terasic DE0-Nano FPGA Development Board

The DE0-Nano is one of the most popular development boards due to its low price (less than $100) and the Altera Cyclone IV FPGA, a low-cost, low-power device that provides more than 22K logic elements.

The board features:

- 2 x 20-pin headers, providing a total of 72 GPIO pins, two +5V pins, two +3V3 pins and four GND pins.
- 1 x 26-pin header, providing 18 GPIO pins and 8 pins for analog input.
- 1 x  12-bit ADC
- 1 x 2Kb EEPROM
- 1 x Accelerometer

Fig 1. Terasic DE0-Nano FPGA board


Terasic also provides software with a Control Panel and a System Builder. The Control Panel allows you to communicate with the board using your computer. Unfortunately, I was unable to make the program run in two different computers, so I won't be including it in my tutorials. The System Builder simply creates some basic files to help you starting a project: a QPF file (Quartus II project file), a Verilog file (declaring all I/O), a QSF file (FPGA pin assignment), a SDC file (timing constraints for testing) and an HTML file to view the descriptions of the I/Os.

Fig 2. DE0-Nano device layout


Most of the information in this tutorial can be found in far more detail in Terasic’s website in the Resources tab.

Here are the steps to create a project from scratch:


1. PREPARING THE SOFTWARE


1.1. Altera Software

Unless you have access to a paid license, we will be using the Web Edition of Altera Quartus II. This HDL analysis and synthesis tool provides compilation, timing analysis, RTL diagrams and simulation, among other features. The second tool that we want to install is ModelSim,  a simulation tool.

Fig 3. Altera Quartus II main window


You can download Quartus II v15.0 and ModelSim in Altera's website. 


1.2. Terasic Software

While it is possible to start a project without the software provided by Terasic, I recommend copying it to your computer since it provides the manuals, a few sample projects and the System Builder. 

If you don’t have the CD-ROM that came with the board, you can download the contents from this link.


1.3. Altera USB Blaster

In order to interface our DE0-Nano with our computer, we need to install its respective driver. Fortunately, no downloads are necessary if you already installed Quartus II.

To install the driver:

- Connect the DE0-Nano to your computer using a mini-USB cable.
- Go to Start Menu, type “Device Manager” and click on it once it appears under Control Panel.
- In the Device Manager, expand the Other Devices branch.
- Right-click on Unknown Device and click on Update Driver Software.
- Select “Browse my computer for driver software”, click on “Search for driver software in this location” and select the folder where Quartus II is installed. Make sure “Include subfolders” is marked.


2. CREATING YOUR FIRST PROJECT


2.1. System Builder

We need two files to start a project: The Quartus II project file (QPF) and the Settings File (QSF), which contains the PIN assignments, constraints, I/O settings and the pin timings.
Out of convenience, we are going to use the System Builder to create a Settings File specific to the DE0-Nano, the project file and template Verilog file:

- In the CD-ROM provided by Terasic, find the Tools folder, then the DE0_Nano_SystemBuilder folder and open DE0_Nano_SystemBuilder.exe
- In the System Builder, give a name to your project, select GPIO Default for both GPIO headers and give a prefix name for each header.
- Next, click on Generate and select a folder to place the new files.


Fig 4. Terasic DE0-Nano System Builder


2.2. Quartus II

- Open the QPF file that you created using the System Builder. This will open our project in Altera Quartus II.
- Click on the Project menu, then  Add/Remove Files in Project and click on the icon with the 3 dots (…)  
- Find the Verilog (.v) file created by the System Builder, click on Add and then OK.
The Verilog file should now appear in the Files window in Quartus II.
- Double click on the Verilog file to see the template for our project.
The Verilog file will have instantiations for all the FPGA pins available through the DE0-Nano board.


Fig 5. Adding files to project

Fig 6. Quartus II showing files in project



Since we want to create a simple project to test our board, we will delete the code in the Verilog file and paste the following code. 

NOTE: The top module must match the name of the project. I used Project1 in my example, so make sure that you change it accordingly. 

module Project1(        // The top-level module must match the name
input CLOCK_50,         // of the project file
output reg [7:0]LED
);

reg   [25:0]count;     
reg   clk2;
reg   state=0;

// clock divider 50MHz to 1Hz
always@(posedge CLOCK_50)
    begin
        if(count==26'd25_000_000)    // counts 25M clk cycles and
            begin                    // toggles clk2 hi or lo
             count<=0;               
             clk2 <= ~clk2;         
            end
        else
            begin
             count<=count+1;
            end
    end    

// state machine blinks on-board LEDs
always @(posedge clk2)
      begin
             case(state)
             1'b0:      begin
                  LED[7:0] <= 8'b01010101;
                  state <= 1'b1;
                  end
            1'b1:       begin
                  LED[7:0] = 8'b10101010;
                  state <= 1'b0;
                  end
            Default: begin
                  state <= 1'b0;
                  end
            endcase    
      end
endmodule


The code does two things. It creates a clock divider to create a 1Hz clock, and a state machine to make the on-board LEDs blink.

Note: If you do not want to copy and paste the code provided above, you can get a copy of my Project1.v Verilog file from my Github repository. Just make sure that you change the name of the file and the top-module to match the name of your project. All you need to do is add the file through the Projects menu.


2.3. Compiling the Design

- Once you Verilog file is ready, double-click on Compile Design. The compilation process should take a minute or two.
- Assuming there are no errors, double-click on EDA Netlist Writer.
- Finally, double-click on Program Device to open the Quartus II Programmer.


2.4. Configuring the FPGA

- In the Quartus II Programmer main window you should be able to see the SOF file for your project and the model number of your FPGA.
- In the top left, click on Hardware Setup and select “USB-Blaster” in the drop down menu. If you don’t see that option, read up section 1.3.
- Finally, press Start and the DE0-Nano should be configured.

Note: You are configuring the FPGA only. FPGAs are volatile devices, and will lose their configuration as soon as you power cycle it. To make your configuration permanent, you’ll have to create a file using Quartus II to configure the flash memory on the DE0-Nano.

Fig 7. Selecting programming hardware

Fig 8. Board programmed successfully






2.5. Test Code for the DE0-Nano

If you simply want to test your DE0-Nano board, here’s the SOF file that I created. Simply load it in the Quartus II Programmer (no need to open the compiler) and repeat section 2.4.

Wednesday, June 25, 2014

Máquina de Estado Finita en Verilog - Usando botón para transiciones

Este código es un ejemplo de una máquina de estado en Verilog y puede ser usado en la placa de FPGA  Mojo.

El código enciende uno de los 8 LEDs a la vez en el Mojo. El LED encendido cambia cada vez que el botón de reinicio (Reset) en el Mojo es presionado.


module LED_state_machine1(

    input   clk,          
// reloj de 50MHz   
    input   nRst,
          // entrada de botón reset   
    input   cclk,         
// reloj del microcontrolador AVR
    output  reg[7:0]led,   // salida a 8 LEDs en tarjeta  
    


  // las siguientes conexiones son para el microcontrolador en el Mojo
    output  spi_miso,          // conexiones SPI para AVR
    input   spi_ss,
    input   spi_mosi,
    input   spi_sck,

    output  [3:0] spi_channel, // AVR selección de canal
    input   avr_tx,            // AVR Tx => FPGA Rx
    output  avr_rx,            // AVR Rx => FPGA Tx
    input   avr_rx_busy        // AVR Rx buffer lleno
    );

// sólo para Mojo. asignar alta impedancia si pines no son usados.
assign  spi_miso = 1'bz;
assign  avr_rx = 1'bz;
assign  spi_channel = 4'bzzzz;


reg       rst;     // crea registro para botón

reg  [3:0]state=0; // crea registros para estados

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


//beginning of state-machine
// inicio de máquina de estado
always@(posedge rst)  // máquina transiciona si rst es presionado
   begin              // comenzar secuencia de máquina de estado
    case(state)
     3'd0: begin
            led[7:0]<=8'b0000_0001;  //
sólo led[1] encendido
            state <= 3'd1;           // saltar a estado 3'd0
           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; // 

            state <= 3'd0;          // volver a estado 0
           end
     default: state <= 3'b0; 
    endcase
   end

  end

endmodule