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.

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 


Friday, March 20, 2015

Diseño de Circuito con LEDs

Los LED (del acrónimo Diodo Emisor de Luz en inglés) se han convertido uno de los componentes electrónicos más utilizados en el mundo. Los LED son más baratos que otros tipos de fuente de luz, consumen menos poder, producen menos calor, y su tamaño los hace ideales para un sin fin de aplicaciones.


CONCEPTOS BASICOS

1. Los LEDs son semiconductores. La Ley de Ohm (V=iR) todavía aplica, pero tenemos que considerar la caída de voltaje de conducción (Vf por Forward voltage en inglés) del LED cuando hacemos nuestros cálculos.

2. Los LEDs tienen 2 regiones básicas de operación: De conducción (forward region en inglés) y de corte (reverse region en inglés). En la región de conducción, el LED actúa como un conductor. La corriente fluye de sólamente del ánodo al cátodo y el LED se enciende. En la región de corte, el LED se convierte en un aislante y por lo tanto no hay flujo de corriente. También existe la región de ruptura, causada por el exceso de voltaje en sentido opuesto, donde la corriente fluye de cátodo a ánodo. Sin embargo, esta región normalmente daña el LED.

Fig. 1. Símbolo de esquemática de un LED mostrando el ánodo y el cátodo


3. El LED entra en la región de conducción cuando el voltaje de alimentación (Vs por voltage source en inglés) es mayor a la caída de voltaje de conducción del LED (Vf). Este valor se puede encontrar en la datasheet (hoja de detalles técnicos del producto).

4. En LEDs comunes, el cátodo está normalmente marcado por un contacto más corto y por una ranura plana en el cuerpo del LED.

Fig. 2. Dimensiones físicas de un LED


5. El brillo del LED es proporcional al flujo de corriente directa. Demasiada corriente puede dañar o quemar el LED; poca corriente hará que apenas se vea la luz. Como el LED puede funcionar como un conductor, necesitamos colocar una resistencia en serie para controlar el flujo de corriente.

Fig. 3. Circuito simple con un LED 


6. La ecuación para calcular la resistencia del circuito es simple. Tomamos el voltaje de fuente (Vs) y sustraemos el voltaje de conducción (Vf) del LED, luego dividimos ese número por la corriente directa (If) deseada y el resultado nos da la resistencia que necesitamos.


Eq. 1. Ley de Ohm usada para calcular la resistencia de un circuito con LED

7. Idealmente, queremos usar la corriente directa recomendada por el fabricante en la datasheet del LED. Más corriente nos da más brillo, pero también reduce el tiempo de vida del LED.



Diseño de Circuito de LED

Para este ejemplo, utilizamos un LED blanco fabricado por Vishay [Datasheet].

1. Primero, usamos el datasheet para encontrar el voltaje de conducción (Vf) y la corriente directa recomendada (If). Estos valores se encuentran normalmente en la sección Electrical Characteristics del datasheet.



Fig. 4. Fragmento del datasheet de un LED

Para nuestro LED, Vf tiene un rango de 2.8V a 3.6V. Esto, debido a que los LEDs nunca son perfectamente idénticos a la hora de ser fabricados. La única forma de saber el Vf exacto del LED es midiéndolo con un multimetro una vez que el circuito es construído. En este ejemplo, usaremos Vf=3.2V.

Vf = 3.2V
If = 20mA

2. Encontramos la caída de voltaje de alimentación sobre la resistencia y el LED en serie. Para este ejemplo, usamos una batería de 9V.

Vs = 9V

3. Aplicamos nuestros números en la ecuación eq. 1 y el resultado es el valor de la resistencia.

(Vs – Vf) / If = (9V – 3.2V) / 0.020 = 290Ω

Fig. 5. Ejemplo de circuito con LED



Usando Multiples LED en Serie

Si nuestro circuito usa varios LEDs en series, simplemente sumamos los voltajes de conducción (Vf) de cada LED y los agregamos a nuestra ecuación para calcular la resistencia R.

Para este ejemplo, usamos 3 de los LEDs de Vishay en serie y usamos los valores Vs=12V, Vf= 3.2V, y If=20mA.

La ecuación para calcular la resistencia sería:

 (Vs – Vf – Vf – Vf) / If = (12 – 3.2 – 3.2 – 3.2) / 0.020 = 120Ω

Fig. 6. Circuito con múltiples LEDs en serie



Thursday, March 19, 2015

LED Circuit Design

Light emitting diodes (LED) are one of the most commonly used electronic components in today’s world. They are cheaper than other light sources, use much less power, dissipate less heat and their small form factors makes them ideal for countless applications.

BASIC CONCEPTS

1. LEDs are semiconductors. While Ohm's Law (V=iR) still applies, we must consider the voltage drop of the LED (Vf) first when doing the calculations.

2. LEDs have two states or regions of operation: Forward-bias and reverse-bias. In simple terms, forward-bias makes the LED a conductor (current flows, lights up), and reverse-bias makes it an insulator (no current, no light). In the forward-bias region, current will only flow from Anode to Cathode. In reverse-bias, no current flows. There's also the breakdown region, where applying enough voltage in the opposite direction will create a reverse current. Doing this will usually damage the LEDs so we want to avoid it.


Fig. 1. Schematic symbol for LED showing anode and cathode


3. The LED is forward-biased (turned on) when the source voltage (e.g. power supply) is higher than the forward voltage (Vf) of the LED. The forward voltage can be found in the LED's datasheet. 

4. For standard LEDs, the cathode will usually have a shorter pin and the package will have a flat notch on its side.

Fig. 2. Package dimensions of LED


5. LEDs are current-controlled devices; brightness is proportional to the current flow. Too much current will burn them; too little will dim them. Since a forward-biased LED is a conductor, we need to use a resistor in series to control the current flow.

Fig. 3. Simple LED series circuit


6. The equation to calculate the value of the resistor in the LED circuit is simple. We take the voltage source (Vs), we subtract the LEDs forward voltage (Vf) and divide the result by the LEDs forward current (If). The LEDs forward voltage and current are usually found in the LEDs datasheet and will vary depending on the color and type of LED. This equation is simply Ohm's Law.

Eq. 1. Ohm's Law applied to LED resistor calculation

7. Ideally, we will use the forward-current recommended by the manufacturer in the datasheet. Increasing the current will increase the brightness, but may also reduce the LEDs life span. If we exceed the maximum current rated in the datasheet, the LED might get damaged.

Designing a LED Circuit

For this design example, I’ll be using a white LED manufactured by Vishay [Datasheet].

1. First, we use the datasheet to find the forward voltage (Vf) and the typical forward current (If) of the LED. We will find Vf and the typical If in the Electrical Characteristics section.


Fig. 4. Fragment of LEDs datasheet

For this LED, Vf ranges from 2.8V to 3.6V. This occurs because LEDs will never be identical due to manufacturing imperfections. The only way of finding the actual Vf value, is measuring it with a volt-meter once the circuit is built and running. For this example, we’ll use the average of those values, 3.2 volts. The typical forward current is the value used by the manufacturer for testing.

Vf = 3.2V
If = 20mA

2. Find the voltage drop across both the LED and the resistor. In this example, we’ll be using a 9V battery.

Vs = 9V

3-Substitute the values in eq.1 to calculate the resistor value.

(Vs – Vf) / If = (9V – 3.2V) / 0.020 = 290Ω

Fig. 5. LED series circuit example



Using Multiple LED in Series

To use multiple LEDs in series, we simply need to add the forward voltage (Vf) of each LED in the series into the equation.

For this example, we are using 3 of the Vishay LEDs in series and our values are Vs=12V, Vf= 3.2V, and If=20mA.

The equation to calculate our resistor would be:

 (Vs – Vf – Vf – Vf) / If = (12 – 3.2 – 3.2 – 3.2) / 0.020 = 120Ω

Fig. 6. Multiple LED series circuit example


Wednesday, December 10, 2014

Estás Tratando de Organizar tu Código? Prueba GitHub

Muchos de nosotros hemos pasado por una situación como ésta. Creas un proyecto de códigopara  microcontrolador en diferentes archivos.  A los pocos días, haces varias modificaciones al código y guardas los archivos. Tras unos días más, agregas más modificaciones a tu código y después de compilar te das cuenta que introdujiste un bug a tu proyecto. Como el proyecto ha sido modificado varias veces, encontrar el error puede tomar bastante tiempo y puede ser muy frustrante porque no recuerdas qué cambios pudieron haberlo generado.

Para resolver ese problema se han creados diferentes Sistemas de Control de Versiones (VCS por sus siglas en inglés), los cuales organizan y administran los archivos con código de forma más eficiente. Los VCS proveen repositorios o archivos centralizados, dan seguimiento a las modificaciones, y te dan información sobre quién los hizo, cuándo, e idealmente, por qué. También guardan copias de cada versión de código que hayan existido. Entre los sistemas más conocidos tenemos Subversion (SVN), Git, Mercurial, CVS, LibreSource y Perforce, entre otros. Algunos son gratuitos, otros de código abierto o propietarios.

El sistema del cual quiero hablar en este artículo es Git. Creado por Linus Torvald (creador de Linux), Git es una VCS distribuida. Para este tipo de VCS, los desarrolladores no tienen que compartir un solo repositorio. En lugar de eso, tienen que hacer una copia del repositorio original a sus propios sistemas y si deciden hacer cambios al código original, pueden mandárselo al autor para que lo fusione al repositorio de su proyecto. 




Entonces, ¿qué cosa es Github? Github es un servicio de alojamiento en línea de repositorios basado en el control de versiones Git con una interfaz amigable y simple. Github ofrece una interfaz gráfica, mientras que en su forma original, Git require el uso de línea de comando. Además, Github te permite mantener tu repositorio en sus servidores de forma gratuita, siempre y cuando tu repositorio sea público. Si deseas tener repositorios privados, puedes pagar una cuota mensual, la cual vale la pena pagar si eres un profesional. La mayoría de VCS requieren que tengas tu propio servidor para guardar toda la información. El sistema Github también te permite compartir código y repositorios con otros desarrolladores en cualquier parte del mundo. Esto permite que la colaboración en proyectos sea más eficiente y segura, pues ningún cambio puede ser echo a tu repositorio sin el consentimiento del dueño del repositorio.


Además de ser un VCS, Github también funciona es una red social, ya que te permite entrar en contacto o seguir las actividades de otros desarrolladores. En Github, puedes ver sus repositorios públicos y también puedes colaborar con sus proyectos. Github también es una herramienta para buscar trabajo como freelancer y se puede utilizar para mostrar tu portafolio de desarrollo.

En conclusión, es recomendable utilizar algún tipo de VCS para organizar tus proyectos con código. De todos los sistemas actualmente en el mercado, Github te da acceso a sus servidores de manera gratuita para guardar tus repositorios y ofrece una interfaz gráfica muy fácil de usar.

Trying to Keep Track of Your Code? Try GitHub

Many of us have probably ran into this situation. You write some microcontroller code and save it in different project files. A week later, you make some changes and overwrite the project files. A few days later, you make even more changes and realize that your code is buggy. Since you kept adding more and more changes to the code, figuring out what change caused the bug can be time consuming and frustrating.

To solve that problem, different developers have created Version Control Systems (VCS) which can manage the code more efficiently. A VCS provides repositories for your code and keeps track of  what changes were made, who made them and when. This  makes collaboration between developers more efficient and reliable. Moreover, each version of the code that you commit is saved in case you want to revert your code to a previous stage.  Some of the most popular VCS are Subversion (SVN), Git, CVS, Mercurial, LibreSource and Perforce, among others. They can be free, open-source or proprietary. 

The system I want to talk about is Git. Designed by Linus Torvalds (creator of Linux), Git is a classified as a distributed VCS. This means that the developers don't have to share a common repository to make code changes. Instead, developers have to make a copy of the repository into their own systems and merge it back in order to make the changes effective. 



So, what is Github? Github is an online repository hosting service based on Git with a much friendlier user interface than using Git through command line. The advantage of Github, is that it you can keep your repositories in their servers for free as long as you make them public. Otherwise, you can pay to have private repositories. Github also allows you to share code and collaborate with other developers. And for your protection, no changes can be made to your repository without your approval.


Besides a repository and code sharing site, Github is also a Social Network. It allows you to connect with other developers, follow their work. Github also helps you offering or looking for freelance work, and the repositories make excellent work portfolios for potential employers.

In conclusion, I really encourage you to use some sort of VCS to keep your code organized. Of all the systems currently available, I recommend Github since it is a free, offers a really simple user interface and allows you to collaborate with other developers as long as they are connected to the internet.

Sunday, August 10, 2014

¿Qué es la Histéresis?

Si tienes experiencia trabajando con diseños digitales, seguramente has escuchado la palabra histéresis. Lo más probable, es que hayas buscado la palabra en la internet y la explicación te haya confundido más. Esto se debe a que el término es usado no sólo en electrónica, sino también en mecánica, física, y economía, entre otros.

Para entender el concepto de histéresis, comencemos hablando sobre la lógica digital. Los circuitos digitales utilizan un sistema binario basado en voltajes altos y bajos para representar 1's y 0's. Normalmente, el valor de estos voltajes es definido por estándares. Por ejemplo, la lógica TTL define altos y bajos como +5V y 0V. Debido a esta definición, muchos asumen que las señales son exclusivamente altos o bajos (como en la figura 1).



Fig 1. Señales cuadradas representando 1's y 0's.


En realidad, las señales toman tiempo para transicionar de un nivel a otro. Dependiendo del diseño del circuito, éstas señales pueden sobrepasarse, demorar en transicionar, oscilar o ser afectadas por ruido eléctrico. La figura 2 muestra una transición de 0 a 1, donde vemos a la señal sobrepasándose por casi 40% y luego oscilando.


Fig 2. Escalón unitario mostrando sobrepaso y oscilación.


Los circuitos digitales normalmente usan una barrera para decidir si la señal es alta o baja. Si el voltaje de la señal de entrada es mayor a esta barrera (llamada threshold en inglés), la señal de salida es 1. Si es menor, la señal de salida es 0. Sin embargo, cuando una señal de entrada es afectada por oscilaciones o ruido eléctrico, esta misma puede cruzar la barrera múltiples veces y la señal de salida termina mostrando varias transiciones entre altos y bajos (figura 3).



Fig 3. Señales digitales mostrando varias transiciones por ruido eléctrico


Entonces, ¿qué es la histeresis? Histéresis es una región creada alrededor de una barrera lógica en la cual cambios de la señal de entrada no tienen ningún efecto en la señal de salida (figura 4). Básicamente, esta propiedad crea 2 barreras separadas para cambiar de alto a bajo, y viceversa.

Vale la pena mencionar que si no prestamos atención, podemos encontrar problemas sincronizando diferentes señales debido a que la señal de entrada puede tardar mucho tiempo en cruzar la histéresis.



Fig 4. Barrera digital rodeada por banda de histéresis


Una aplicación de histerésis puede ser observada en la lógica TTL. La señal de salida sólo cambia a 1 si la señal de entrada tiene voltaje de 2V a 5V. En caso de haber ruido eléctrico u oscilaciones, la señal de salida no cambiaría de alto a bajo a menos que la señal de entrada sea menor a 800mV, o que el ruido sea tan alto que llegue a cruzar estas barreras.



Fig 5. TTL signal levels



Saturday, August 9, 2014

[ES] Interfaz entre Módulo de LCD SainSmart de 20x4 con Arduino Uno

Este es un proyecto simple diseñado para crear interfaz entre el módulo de LCD SainSmart de 20x4 (20 caracteres, 4 líneas). Yo compre mi módulo de LCD en Amazon, ofrecido como SainSmart LCD Module For Arduino 20 X 4, PCB Board, White On Blue.

Basándome en las opiniones de los usuarios, el módulo puede venir en dos versiones dependiendo del vendedor (Amazon distribuye productos para diferentes vendedores). La diferencia de las versiones es que el módulo puede incluir, o no, el adaptador de comunicaciones I2C. Yo compré mi módulo a la tienda BeesClover e incluyó el adaptador de I2C. Algunos usuarios también han recibido el producto sin la hoja de datos (datasheet), la cual incluye la dirección del módulo de I2C. Este módulo tiene un precio módico comparado a otras tiendas. Sobre todo, si tienes una suscripción con Amazon Prime, debido a que el costo de envío es casi la mitad que el precio del producto.



Fig 1. Módulo de LCD SainSmart- Frente


Fig 2. Módulo de LCD SainSmart-Reverso


Fig 3. Adaptador de I2C. El interruptor rotativo controla el contraste.



Estas instrucciones están diseñadas para el módulo de LCD con el adaptador de I2C:

1. Hacer una búsqueda en línea de la librería de Arduino LiquidCrystal_V1.2.1.zip y descargar. El archivo fue creado por F. Malpartida y modifica la librería original de Arduino para LCD, haciéndola compatible con módulos Hitachi HD44780 y de similar arquitectura.

2. Reemplazar la librería de Arduino original LiquidCrystal  con la librería en el archivo descargado. Para abrir el archivo ZIP puedes descargar el programa 7z.

3. Conectar los pines del adaptador de I2C al Arduino Uno, conectando los pines de 5V y GND respectivamente, de SDA (data) al pin A4 y de SCL (reloj) al pin A5.

Nota: Los pines varían para otras placas de Arduíno. Para el Mega2560, usar pines 20, 21; para el Leonardo, pines 2, 3; para el Due, pines 20, 21, SDA1, SCL1.

4. Buscar la dirección del adaptador de I2C en la hoja de data. La dirección en mi módulo es 0x27. Sino, usar la librería  I2cScanner para identificar la dirección en tu adaptador.

5. Compilar y cargar el siguiente código al Arduino. La pantalla debe de mostrar "Hello World" en cada una de las 4 líneas y parpadear cada segundo. Asegurarse que la dirección junto a la línea #define I2C_ADDR es la misma que en la hoja de data.

#include <Wire.h>                // Carga librería de interfaz I2C


#include <LiquidCrystal_I2C.h>   // Carga librería de I2C para LCDs

#define I2C_ADDR 0x27    // Configurar dirección de I2C


//Define pines en controlador de LCD usando I2C. No cambiar.
#define BACKLIGHT_PIN 3 
#define En_pin 2
#define Rw_pin 1
#define Rs_pin 0
#define D4_pin 4
#define D5_pin 5
#define D6_pin 6
#define D7_pin 7

LiquidCrystal_I2C lcd(I2C_ADDR,En_pin,Rw_pin,Rs_pin,D4_pin, D5_pin,D6_pin,D7_pin);

void setup()
{
lcd.begin (20,4,LCD_5x8DOTS);    //Define tipo de pantalla LCD
lcd.setBacklightPin(BACKLIGHT_PIN,POSITIVE);
}


// Start LCD display loop
void loop()                 
{
lcd.setBacklight(HIGH);      // Enciende luz de fondo en LCD
lcd.clear();                 // Borra caracteres en LCD
lcd.print("HELLO WORLD 1       "); // Escribe en líneas 1 a 4
lcd.print("HELLO WORLD 2       ");
lcd.print("HELLO WORLD 3       ");
lcd.print("HELLO WORLD 4       ");
delay(1000);                 // Espera 1000 ms (1 sec)
lcd.clear();                 // Borra caracteres    
lcd.setBacklight(LOW);       // Apaga luz de fondo
delay(1000);                 // Espera 1000 ms (1 sec)
}

Nota: El archivo con este código se puede descargar de mi repositorio https://github.com/sphanlung/Arduino bajo el nombre SainsmartLCD-ES.ino


 Fig 4. Interfaz de Arduino Uno con LCD

Fig 5. LCD mostrando Hello World



Fig 6. Hoja de data - Página 1



Fig 7. Hoja de data - Página 2