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

Wednesday, February 10, 2016

Contador de Presiones de Botón Usando Pantalla de 7 Segmentos con 4 Dígitos y el Tiva C Launchpad

En el artículo anterior, explicamos cómo funciona una pantalla de siete segmentos simple y usamos el Tiva C Launchpad  y Keil µVision para demostrar un contador incremental.  En esta guía, vamos a usar el Launchpad para diseñar un contador de presiones de botón y mostrar la cuenta en una pantalla de 7 segmentos con 4 dígitos.


Fig 1.  Pantalla de 7 segmentos y 4 dígitos


1.  PANTALLA DE SIETE SEGMENTOS Y 4 DIGITOS

Si recordamos el artículo anterior, necesitamos 8 pines del microcontrolador para controlar una pantalla de siete segmentos simple (7 para los LEDs y 1 para conectar a la fuente de poder o tierra).  Esto significa que necesitaríamos 32 pines para controlar 4 pantallas.

La pantalla de 4 dígitos funciona de manera parecida, pero sólamente utiliza 11 pines (o más si la pantalla tiene puntos, dos puntos, etc).  Para lograr ésto, usamos 7 pines para controlar los 7 LEDs en los 4 dígitos al mismo tiempo.  Los otro 4 pines controlan cuál de los dígitos se va a encender.  Esto es más fácil de observar en el diagrama de circuito mostrado en la figura 2.

Para mostrar todos los números al mismo tiempo, el microcontrolador simplemente enciende continuamente cada uno de los dígitos por una fracción de segundo.  Cuando esto ocurre lo suficientemente rápido, nuestros ojos sólo detectan una imagen.  Este es el mismo concepto usado en las películas, donde varias imágenes son alternadas a alta velocidad para darnos la ilusión que la imagen se está moviendo.


Fig 2.  Mapa de pines y diagrama de circuito de pantalla de 7 segmentos, 4 dígitos y de anodo común 5641BH



2.  PROBANDO EL NUESTRA PANTALLA CON EL TIVA C LAUNCHPAD

2.1  DESCRIPCION

Para este proyecto vamos a usar el Tiva C Launchpad para diseñar una contador de presiones de botón y mostrar la cuenta en nuestra pantalla de 7 segmentos y 4 dígitos.

2.2  MATERIALES

- Tiva C Launchpad
- Placa de prueba (breadboard)
- 4 x Transistores NPN 2N3904
- 1 x pantalla 5641BH (pantalla de 7 segmentos y 4 dígitos de ánodo común)
- 4 x resistores 1KΩ
- 7 x resistores 47Ω


2.3  HARDWARE

El sistema utiliza 11 pines de salida del Launchpad para controlar la pantalla.  7 de esos pines van conectados directamente a la pantalla para controlar los 7 LED y los 4 pines van conectados a los transistores para conectar el riel de 3.3V a los pines de selección de dígito en la pantalla.  También vamos a usar el botón SW2 montado en el Launchpad.

La datasheet para la parte 5641BH puede ser descargada en este vínculo.

En la figura 3 tenemos el diagrama del circuito.  Noten que el botón no está incluído porque viene montado en el Launchpad.


Fig 3. Diagrama de circuito para contador de presiones de botón con pantalla 5641BH


2.4  SOFTWARE

Entra a mi repositorio en Github y encuentra el archivo SevenSegment2.c para descargar el código del microcontrodor a tu proyecto. Una vez más, las instrucciones para crear el proyecto se pueden encontrar en el artículo anterior.

El diagrama de flujo en figura 4 explica el funcionamiento del programa para el microcontrolador.


Fig 4.  Diagrama de flujo para código de microcontrolador









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.

Thursday, April 2, 2015

Parpadeando un LED con el Tiva C Series LaunchPad y Keil µVision v4

Una de las mayores dificultades para aquellos que empiezan a usar microcontroladores es crear y configurar un proyecto nuevo desde cero. Esto se debe a que, a diferencia de la plataforma de Arduino, normalmente debemos de instalar y configurar distintos controladores de dispositivos (drivers) y archivos con código específico para cada tipo de microcontrolador. Arduino normalmente incluye todos estos archivos en su propia plataforma, por lo que es un excelente microcontrolador para principiantes y entusiastas.

El objetivo de este artículo es el de introducir la placa Tiva C Series Launchpad y el programa de desarrollo embebido (IDE)  Keil µVision, y utilizarlos para hacer parpadear un LED.

Este artículo muestra los pasos para instalar el IDE, crear un proyecto y cargar el programa al LaunchPad. Debido a que no hay una versión en español de Keil, se necesitará un conocimiento básico del inglés para utilizar el programa.

TIVA C SERIES LAUNCHPAD & KEIL µVISION

Los Tiva C Series LaunchPad son una  familia de microcontroladores de bajo costo desarrollados por Texas Instruments. Para este proyecto, usaremos el LaunchPad TM4C (EK-TM4C123GXL). Esta placa lleva un CPU ARM Cortex-M4 con 32 bits, reloj de 80MHz, punto flotante, 256kB de memoria flash con 100,000 ciclos de escritura y borrado, además de sistemas periféricos como PWM, 1-MSPS ADC, 8 UARTs, 4 SPI, 4 I2C, USB y hasta 27 relojes. La placa también incluye para la interfaz de usuario 2 botones de uso general, un botón de reinicio, un LED de poder y un LED RGB programable.

Para más detalles sobre el Tiva C Launchpad, visita la página de Texas Instruments 


Fig 1.  Tiva C Series Placa de Evaluación

µVision es una plataforma de desarrollo embebido para procesadores ARM creada por Keil. La plataforma provee administración de proyectos, edición de código, compilador, depuración (debugging) y simulación. Para este proyecto usaremos la versión 4 de µVision, ya que es más estable, cuenta con más soporte en línea que la reciente versión 5 y sobretodo, es la versión con la que tengo más experiencia.

Para más información sobre µVision, visita la página de Keil.

Fig 2. Imagen de inicio de Keil µVision 4


2. INSTALACION DEL SOFTWARE (IDE)

a. Primero, necesitamos instalar Keil µVision v4. Visita https://www.keil.com/demo/eval/armv4.htm, ingresa tu información de contacto y descarga el archivo MDK474.exe para instalar el IDE. El tamaño del archivo es de aproximadamente 590MB.

b. Ejecuta el instalador de MDK-ARM v4. En las siguientes ventanas acepta los Términos de Uso, elige donde quieres instalar el programar, ingresa tu información de contacto y espera que el IDE se instale. Después, marca la casilla “Add example projects…” y en la última ventana remueve la marca en la casilla “Launch Driver Installation” y presiona Finalizar.

c. Después de instalar Keil, necesitamos instalar los controladores (drivers) para nuestro microcontrolador. Para este paso, vamos a necesitar el LaunchPad. Primero, visita http://www.ti.com/tool/stellaris_icdi_drivers y descarga el archivo Stellaris ICDI Drivers.
Puedes usar las instrucciones de Texas Instruments siguiendo este vínculo.

3. CREANDO UN PROYECTO NUEVO

Después de instalar Keil y los controladores podremos comenzar nuestro proyecto nuevo.

a. Abre Keil µVision v4, haz click en el menú Project >> New µVision Project y escribe el nombre del proyecto nuevo.

b. En la siguiente ventana, tienes que elegir el microcontrolador que será usado en este proyecto. Para nuestra placa, selecciona de la lista Texas Instruments y el dispositivo TM4C123GH6PM.


Fig 3. Seleccionando microcontrolador para el proyecto

c. Luego acepta te pregunten si deseas copiar el archivo de inicio (startup) del microcontrolador a tu proyecto. 

Fig 4. Pregunta del sistema para copiar archivo de inicio de microcontrolador


d. Tras aceptar, el archivo de inicio debe de aparecer bajo Target1 >> Source Group en la ventana de proyecto.

Fig 5. Vista de Keil con archivo de inicio


e. Para el siguiente paso, tenemos que copiar el archivo system_TM4C123.c a nuestra carpeta de proyecto. Este archivo contiene código para configurar los relojes para nuestro modelo microcontrolador y puede ser encontrado en la carpeta de instalación de Keil. En mi caso, el archivo se encuentra en C:\Keil\ARM\Startup\TI\TM4C123\system_TM4C123.c

f. Después copiar el archivo a tu carpeta de proyecto, haz click con el botón derecho en Source Group 1 en la ventana Project y luego haz click en Add existing files to Group ‘Source Group 1’ y selecciona el archivo system_TM4C123.c. Esto nos permite agregar archivos con código en diferentes formatos a nuestro proyecto.

Fig 6. Agregando archivos a proyecto en Keil 


g. Finalmente, haz click con el botón derecho a Source Group 1 nuevamente y selecciona Add New Item to Group ‘Source Group 1’ para agregar un archivo nuevo al proyecto. Selecciona C File(.c), dale un nombre a tu archivo y haz click en Add para crear el archivo. Este va a ser tu archivo principal para el código de programación.

f. El IDE debe mostrar ahora el archivo startup, system y el archivo en blanco que acabas de crear bajo Source Group 1.

Fig 7. Imagen de Keil después de agregar los archivos necesarios


4. PROGRAMACION

a. Visita https://github.com/sphanlung/TivaC/blob/master/LedBlink.c y copia el código en esa página al archivo en C que creaste. El vínculo te llevará a mi repositorio en Github.

b. Luego, haz click en el menú Project y en Build Target. Este comando hará que Keil compile el código para el microcontrolador. En la parte de abajo también podremos ver el resultado de la compilación, errores y advertencias en la ventana Build Output.

Fig 8. Compilando el código en Keil


c. Ahora, necesitamos configurar Keil para poder cargar el programa en el microcontrolador. Haz click en Project y luego Options for Target ‘Target 1’. Cuando se abra la ventana de opciones, busca la pestaña Utilities y bajo Configure Flash Menu Command, y desmarca la casilla Use Debug Driver. Luego, bajo Use Target Driver for Flash Programming selecciona el controlador Stellaris ICDI y presiona OK.


Fig 9. Configuración del controlador para el LaunchPad


d. Finalmente, haz click en Flash y luego Download para cargar el programa en el microcontrolador 

5. PRUEBA EN LA PLACA

a. Cuando el código termina de cargar, presiona el botón Reset en el LaunchPad para iniciar el programa.

b. Cuando ningún botón es presionado, el LED azul estará encendido. Si presionas el botón SW1, los LEDs azul y verde parpadearán. Si presionas el botón SW2, los LEDs rojo y azul parpadearán.


Fig 10. Prueba del código en el LauchPad 

Wednesday, April 1, 2015

Blinking an LED Using the Tiva C LaunchPad and Keil µVision 4

One of the most frustrating things for people new to microcontrollers is starting a new project from scratch. The main reason being that, unlike the Arduino platform, you have to install and configure different drivers and configuration files before you can even start your project. Arduino already includes all these files and settings in its platform, which is why it is so appealing to hobbyists.

The purpose of this project is to introduce the Tiva C Series LaunchPad and the Keil µVision embedded development tool to make the on-board LED blink.

This article will show you the steps to install the IDE, create a project and load the code to the LaunchPad board. 

TIVA C SERIES LAUNCHPAD AND KEIL µVISION 4

The Tiva C Series LaunchPad is a family of low-cost microcontroller evaluation boards developed by Texas Instruments. For this project, we will be using the TM4C LaunchPad (EK-TM4C123GXL). This board features an 80-MHz, 32-bit ARM Cortex-M4 CPU with floating point, 256 kBytes of 100,000 write-erase cycles of flash memory, and a wide range of peripherals including motion control PWMs, 1-MSPS ADCs, eight UARTs, four SPIs, four I2Cs, USB, and up to 27 timers. The board includes two general purpose switches, a reset switch, a power LED, and user programmable RGB LEDs for user interface.

For more details about the Tiva C Launchpad, you can visit Texas Instruments’ website 


Fig 1.  Tiva C Series Evaluation Board


µVision v4 is an ARM embedded development platform created by Keil that provides project management, code editing, compilation, debugging, and simulation. Even though µVision v5 has recently been released, we’ll be using v4 because it is more stable, you’ll find more online resources to support this version and more importantly, it’s the one I know how to use better.

For more information about Keil µVision 4.0 you can visit Keil’swebsite 

Fig 2. Opening image for Keil µVision 4


2. INSTALLING THE SOFTWARE (IDE)

a. First, we need to install Keil µVision v4. Go to  https://www.keil.com/demo/eval/armv4.htm. Enter your contact information and then download the file MDK474.exe to install the IDE. The download file size is approximately 590MB.

b. Run the MDK-ARM v4 installer, in the next screens accept the License Agreement, select the installation folder, enter your contact information and wait until the IDE installs. Next, check the box to “Add example projects…” and in the last screen, uncheck the “Launch Driver Installation” box.  

c. After installing Keil, we need to install the drivers to be able to interface the microcontroller with our computer. You will need the LaunchPad board for this step. First, go to http://www.ti.com/tool/stellaris_icdi_drivers to download the drivers for the Tiva C LaunchPad. At the bottom of the page you’ll find a PDF file with instructions on how to install the drivers for different operating systems. You can also access the PDF using this link

3. CREATING A NEW PROJECT

After Keil and the drivers are installed, we can start our new project.

a. Open Keil µVision v4. Click on Project >> New µVision Project and enter a name for the project

b. You’ll be asked to select a target microcontroller. For our board, select Texas Instruments and the device number TM4C123GH6PM


Fig 3. Selecting a microcontroller for new project

c. Accept copying the Startup project file when prompted

Fig 4. System prompt to install project startup file


d. Your Project window should now show the startup file under Target1 >> Source Group

Fig 5. Screenshot of Keil with startup file


e. Next, we need to copy the file system_TM4C123.c to our project folder. This file contains microcontroller specific code to enable the system clocks. The file can be found in the Keil installation folder. In my case, I found it in  C:\Keil\ARM\Startup\TI\TM4C123\system_TM4C123.c

f. After the file has been copied to your project folder, right-click on Source Group 1 in the Project window, click on Add existing files to Group ‘Source Group 1’ and select the file system_TM4C123.c

Fig 6. Adding files to Keil project


g. Finally, right-click on Source Group 1 again and click Add New Item to Group ‘Source Group 1’. Then select C File(.c), enter file name at the bottom and click Add. This will be your main program file.

f. The IDE should show the startup, system and main file that you created under Source Group 1

Fig 7. Screenshot of Keil after project files were added


4. PROGRAMMING

a. Go to https://github.com/sphanlung/TivaC/blob/master/LedBlink.c and copy the code to the C file that you created.  The link will take you to my Github repository.

b. Click on Project and Build Target. This command will compile your code and report any errors or warnings in the Build Output window.

Fig 8. Screenshot of Keil with command to compile code


c. Click on Project and Options for Target ‘Target 1’. Find the Utilities tab and under Configure Flash Menu Command, uncheck the Use Debug Driver box. Then, under Use Target Driver for Flash Programming select the Stellaris ICDI driver and hit OK. This will allow us to program the board through USB.

Fig 9. Configuring drivers to load code into LaunchPad


d. Click on Flash and then Download. This will load the compiled code to the microcontroller. The Build Output window will report the status of the process or any errors.

5. BOARD TEST

a. Once the code is loaded, press the reset button in the LaunchPad to start the program.

b. The blue LED should be on. If you hold SW1, the blue and green LEDs will blink. If you hold SW2, the blue and red LEDs will blink.


Fig 10. Testing the code in the LauchPad 


Thursday, July 3, 2014

Arduino UNO - Placa de Desarrollo

Arduino es una plataforma de electrónica abierta para la creación de prototipos basada en software y hardware flexibles y fáciles de usar. Se creó para artistas, diseñadores, aficionados y cualquiera interesado en crear entornos u objetos interactivos.
El Arduino se ha convertido en una de las plataformas de microcontroladores más populares entre los aficionados y entusiastas de la electrónica en los últimos años.  A diferencia de la mayoría de plataformas de desarrollo, el ambiente de Arduino provee un lenguaje de programación y carga de fácil uso.

El Arduino UNO es una placa de desarrollo que incluye:

- Microcontrolador Atmel ATmega328
- 14 pines de entrada/salida digital (I/O)
- 6 entradas análogas
- Reloj de 16MHz
- 1 conector USB
- 2KB SRAM (parte del ATmega328)
- 1KB EEPROM (parte del ATmega328)
- 32KB Memoria Flash (parte del ATmega328)
- 1 LED de uso genérico
- 1 Botón de Reinicio

Para más información, pueden visitar la página de Arduino (inglés)