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, 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

Wednesday, July 23, 2014

What is Hysteresis?

If you have experience with digital designs, you have probably run into the term hysteresis (if not, you will).  Most likely, you looked it up online and most explanations were rather confusing. This occurs because the term hysteresis is used all over the place, such as mechanics, physics, biology and even economics.

Let's begin talking about digital logic. We use high and low voltage signals to represent a 1 and 0 binary system. The voltages are usually defined by some standard. For instance, TTL logic uses 0V and +5V for 0 and 1. Because of that, many people assume that electric signals in digital logic are exclusively high or low, like perfectly squared signals (see in figure 1).



Fig 1. Square wave representing digital 1's and 0's


In reality, signals take time to transition and depending on the circuit design, signals can overshoot, undershoot, oscillate and can also be affected by noise. Figure 2 shows a step response, a simple transition from 0 to 1, where we observe the signal overshooting past its target value by almost 40%, causing some oscillation as it reaches a steady-state.


Fig 2. Step response showing overshooting and oscillation


Digital devices use a threshold to decide if a signal becomes 0 or 1. However, when a rising signal is affected by noise or oscillation, it can end up crossing a thresholds multiple times (fig. 3). In the example, the input signal transitions from low to high. But, because of the noise, the signal ends up crossing the threshold multiple times and the circuit interprets it as a multiple transitions.


Fig 3. Digital signal with multiple transitions due to noise


So, what's hysteresis? It is a region around the threshold designed to ignore any transitions caused by a noisy signal or oscillations. In other words, it is a property that creates two separate thresholds for a digital signal (see fig. 4).

Additionally, if you don't pay attention to it, you could inadvertently create timing delays, and some unstable signals might could up crossing it.



Fig 4. Digital threshold showing hysteresis band


For an example, we can take a look at TTL logic (transistor-transistor logic). The output will usually transition to high, only when the input is between 2V to 5V. The gap between 0.8V and 2V would be our hysteresis and ff the signal oscillates, the output won't transition to low unless the input signal falls below 0.8V. .


Fig 5. TTL signal levels



Tuesday, July 22, 2014

Interfacing SainSmart 20x4 LCD Module with Arduino Uno

This is a simple project to interface the 20x4 LCD Module by SainSmart using the Arduino Uno. I got my LCD module in Amazon, listed as SainSmart LCD Module For Arduino 20 X 4, PCB Board, White On Blue.

Based on customer reviews, the module may or may not come with a I2C module depending on which seller it comes from (mine was BeesClover). Also, the package may not include the datasheet and some components.  This LCD module can be considered cheap if you have Amazon Prime, since shipping would have added 40-50% to the cost.


Fig 1. SainSmart 20x4 LCD 

Fig 2. SainSmart 20x4 LCD 


Fig 3. I2C Adapter. The rotary knob controls the contrast.


Below are the instructions to test the LCD module with an I2C adapter:

1. Do an online search and download the Arduino library file LiquidCrystal_V1.2.1.zip. This file was developed by F. Malpartida and modifies the Arduino default LCD library to be compatible with the Hitachi HD44780 and compatible chipsets.

2. Replace the default LiquidCrystal Arduino library with the folder contained in the new file. You'll need a program like 7zip to decompress the ZIP file.

3. Connect the pins in the I2C adapter to the Arduino Uno, matching the 5V and GND pins on both boards, the SDA pin to A4 and SCL with A5.

Note: Pins vary for other Arduino boards. For Mega2560, use pins 20, 21; for Leonardo, pins 2, 3; for Due, pins 20, 21, SDA1, SCL1.

4. Find the I2C address for the module in the datasheet. Otherwise, use the I2cScanner library to find the address in your device.

5. Load the code sample below into the Arduino. The display should read "Hello World" in each row while turning on and off every second. Make sure that the address in #define I2C_ADDR matches the value in the datasheet.

#include <Wire.h>                // Loads I2C interface library
#include <LiquidCrystal_I2C.h>   // Loads LCD library for I2C

#define I2C_ADDR 0x27    // Set I2C device address


//Define pins in LCD controller for I2C interface. Don't change.
#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 type of LCD display
lcd.setBacklightPin(BACKLIGHT_PIN,POSITIVE);
}


// Start LCD display loop
void loop()                 
{
lcd.setBacklight(HIGH);      // Turn on LCD backlight
lcd.clear();                 // Clear LCD characters
lcd.print("HELLO WORLD 1       "); // Print rows 1 through 4
lcd.print("HELLO WORLD 2       ");
lcd.print("HELLO WORLD 3       ");
lcd.print("HELLO WORLD 4       ");
delay(1000);                 // Wait 1000 ms (1 sec)
lcd.clear();                 // Clear LCD characters    
lcd.setBacklight(LOW);       // Turn off LCD backlight
delay(1000);                 // Wait 1000 ms (1 sec)
}

The file with this code can be downloaded from my repository https://github.com/sphanlung/Arduino under the name SainsmartLCD.ino

 Fig 4. Arduino interfacing with LCD

Fig 5. LCD displaying Hello World


Fig 6. Datasheet - Page 1


Fig 7. Datasheet - Page 2


Wednesday, July 16, 2014

Caracteres Especiales para Ingeniería Usando Tecla ALT

Si alguna vez tuviste que escribir un reporte de ingeniería, sabes lo irritante que es tipear operadores matemáticos y letras griegas usando un teclado estándar.

Afortunadamente, las PCs te permiten insertar algunos de esos caracteres presionando la tecla ALT e insertando una combinación de números. Abajo, puedes encontrar algunos de esos caracteres.



    Alt + 171  = ½                 Alt + 0216 = Ø

    Alt + 172  = ¼                 Alt + 224  = α

    Alt + 0190 = ¾                 Alt + 225  = ß

    Alt + 0178 = ²                 Alt + 227  = π

    Alt + 0179 = ³                 Alt + 228  = Σ

    Alt + 252  = ⁿ                 Alt + 229  = σ

    Alt + 0176 = °                 Alt + 231  = τ

                                   Alt + 232  = Φ

    Alt + 242  = ≥                 Alt + 233  = Θ

    Alt + 243  = ≤                 Alt + 234  = Ω

    Alt + 244  = ⌠                 Alt + 235  = δ

    Alt + 245  = ⌡                 Alt + 236  = ∞

    Alt + 246  = ÷                 Alt + 237  = φ

    Alt + 247  = ≈

    Alt + 251  = √                 Alt + 1    = ☺

    Alt + 240  = ≡

    Alt + 0177 = ±