lunes, 7 de julio de 2014

DAC Wing for the Papilio Platform

Hello again! This time I decided I would start to share my designs over here as well. This time I'll be sharing a Papilio Wing.
As you may or may not know, the Papilio platform is an awesome barebones FPGA platform with Arduino-style headers to plug what they call "Wings" (instead of shields). Since an FPGA usually has a ton of I/O, you can plug a huge ammount of wings to it (or one Mega Wing) like this.


Since the papilio platform is relatively new, there are not a lot of wings for it. This is why I decided to make a proper audio DAC Wing (they have one, but it's based on PWM and a low-pass filter). The wing I made is EXTREMELY simplistic. It's based on the MAX5556 DAC which barely requires anything. It has only a couple of passives and a 3.5mm stereo jack. This is the render of the board.

kJt2oOE.png

The link for the design files (it is open source, obviously) are here (GitHub)
And here is the link to order the board from OSHPark (It is the prototype version).

jueves, 20 de febrero de 2014

Hercules Launchpad #8 - Nokia 5110 LCD Display (Part 3 - CCS Setup)

Ok, now that we've configured the files in HALcoGen, we have to import the Nokia Libraries. To make this, follow the steps...

Step 1
Create a new project just like we've done it before.

Step 2
Copy the .h and .c files to their respective folders inside the project (include and source, respectively)
OR 
Right-click on the root folder inside CCS and select "Add files...". Then select the library files you downloaded like this




Step 3
Now right-click again on the root folder inside CCS, but this time go to "Properties". Then go to "Include options" and add the directory where you stored the library files.



That's it! When you make use of the libraries you won't have any compiling errors. On Part 4 I'll explain the functions of the libraries...

miércoles, 19 de febrero de 2014

Hercules Launchpad #7 - Nokia 5110 LCD Display (Part 2 - HALcoGen configuration)

So we continue....


Ok, now I feel confident enough to share my progress on the Nokia Display Library.
First I'm going to show you how to configure HALcoGen so that you can use the library.

Step 1
Create a new project just like before...

Step 2
Enable the RTI, GIO, SPI1 and HET drivers.



Step 3
Configure the RTI compare 0 timer to any small value (RTI -> RTI1 Compare). Also enable the interrupt for the compare 0 (RM42L432PZ -> VIM Channel 0-31). This is to generate delays.



Step 4
Configure the HET Drivers. You have to set pin 0 to be a PWM signal and enable the outputs of HET pins 0, 2, 4 and 6.



Step 5
Generate the code! (F5)

Ok, so this is the configuration you will need to be able to use the library. I will leave you with the links of my GitHub so that you can download the library and a demo.
On the part 3 of this tutorial I will explain all the functions I've created.

GitHub

https://github.com/DiegoRosales/Nokia-5110-for-Hercules-Launchpad

domingo, 26 de enero de 2014

Hercules Launchpad #6 - Nokia 5110 LCD Display (Part 1 - The basics)

Esto va a estar bueno...
Pues después de como un mes de pedirlos por eBay, finalmente me llegó mi paquete con 5 displays LCD



y pues, como cualquier persona con el 100% de sus facultades mentales, me puse inmediatamente a ver qué onda con estos displays. Me costó un poco echarlos a andar con el Hercules Launchpad, pero finalmente lo logré y les enseñaré cómo



Pero antes de empezar...
Este tema es muy popular, sin embargo casi toda la información y los recursos que existen (librerías, tutoriales, etc.) están hechos para el Arduino. Es por esto que para que esta información esté disponible para más gente, la explicación será en inglés.

Let's get started!

Ok, so first things first...
Pinouts!!
It is really important to know the pinout of the LCD, as it may vary. The one I got from eBay goes like this
  1. !Reset (RST)
  2. !Chip Enable (CE)
  3. Data / !Command (DC)
  4. Data In / MOSI (DIN)
  5. Clock signal (CLK)
  6. Main source input (Vcc)
  7. Backlight voltage (LIGHT)
  8. Ground (GND)
Another important thing to know is the function of the pins.

!Reset
This is pretty much self explanatory... sort of. This pin resets the microcontroller inside the display to a default state. It is important to know that it is Active Low, meaning that the reset function is triggered when the pin has 0V. Therefore we must maintain this pin on High (3.3V) pretty much all the time.

!Chip Enable
There is not much science about this pin. Whenever you want to tell something to the display, you must activate this pin. This pin is also Active Low, so whenever you try to send something to the display, you must set 0V to this pin.

Data / !Command
This is interesting. There are two kinds of information you can send to the display. The first one is display data. This is the information about what pixels are on and off. The other type of information are commands. This commands are made to achieve several functions such as setting up the contrast levels, inverting the image, setting the cursors, etc. If we want to send display data, we must set a HIGH (3.3V) on this pin. If we want to send a command, we must set a LOW (0V). Pretty straight forward, right?

Data in / MOSI
Ok, so this is the pin where we send the actual information to the display. This display communicates over an SPI (Serial Peripheral Interface) form factor, that's why  we can say it is a MOSI pin (Master Output Slave Input). The Maximum Bit Rate supported by this display is 4Mbits/sec, just remember that. We will discuss the data format later on...

Clock input
There is not much to this. It is part of the SPI protocol. Keep in mind that the maximum clock frequency is given by the maximum bit rate, which is 4Mbits/sec. Therefore, the maximum clock frequency is 4MHz.

Main source input
You must apply 3.3V to this pin. That's it! It doesn't take up much current...

Backlight voltage
This pin is connected to the four LEDs on the board. If you want to see what you're doing in the dark, apply voltage to this pin at will... just be careful, as this boards do not come with current limiting resistors, so they can be very power hungry.

Ground
It is a good practice to connect this pin to Ground... just saying.

Ok... now that you are an expert on the pins of the display, let's see how does it actually work.
The very first thing to do is to reset the display... at least according to the datasheet, see?



According to the datasheet, the reset pulse can be low even before we power up the display, but the time between the power up and the reset pulse must not exceed 30ms. The pulse width of the reset signal must be at least 100ns, which is low enough for us to not worry.
The second thing to do whith it is to initialize the display. This is achieved by sending a series of commands that set up the contrast and other various things. We will see the details of that in the code.
Finally, the last thing to do is to start sending display data.

Now let's discuss the data format.
As I said before, the display controller operates with an SPI interface. This means that it requires a Chip Enable (CE), a Clock Signal (CLK) and one or two data signals (MISO, MOSI). Since this display does not return any data, we only have to worry about one data signal (MOSI).
Another important thing is that the data is sent to the display in packets of 8 bits, with the most significant bit (MSB) first.
The way it is transmitted is the following:



In this case, SDIN is the equivalent of MOSI, SCLK is the Clock signal and SCE is the Chip Enable signal. D/C is the signal that indicates whether we are sending data or commands.
If we want to send several bytes, we just need to keep the SCE low and the clock signal going.
Also, as you can see, each bit is sent in one clock cycle. Not two, not three but one!

Now... let's talk about how the data is displayed on the screen. The micro controller inside the screen has an internal RAM to which we send the display data. This RAM is divided in blocks of 8 bits forming the rows. Therefore it has only 6 rows. It looks like this



Each bit corresponds to a pixel, but we can only manipulate individual bytes, not bits. If we wanted to manipulate a single bit, we would need to have a buffer inside our controller and modify the individual bit there, and then re-send the byte that holds our bit, or just re-send the entire display.

Ok, so pretty much this is what you need to know before you start making your own code!

But before we get into the code, let me tell you a couple of things about the Hercules Launchpad. 
First... it has 3 dedicated SPI modules and one kind of weird Multi-Buffer SPI (MIBSPI). Unfortunately, the MIBSPI/SPI1 pins are the only SPI pins that are soldered. The other 2 modules are in the unsoldered part, and since I didn't want to mess with the MIBSPI/SPI1 module right now, I decided to make the transmitter by software (which isn't hard at all).


************ UPDATE!!! 19/02/2014************

So I decided to stop being lazy and getting into the dedicated SPI ports. As I mentioned, the microcontroller has 3 SPI modules, one of them being a MIBSPI/SPI, which means Multi-Buffer SPI combined with a normal SPI for compatibility. At first I could not make the display ports with it, but after a little investigation and experimentation I made it work.


Second... this is the pin layout of the Launchpad



The connection I made with the display was the following

  • !Reset (RST) ---> N2HET[14]
  • !Chip Enable (CE)  ---> N2HET[12]
  • !Chip Enable (CE)  ---> MIBSPI1nCS1 or GIOA[6] for compatibility with standard boosterpack pinout.
  • Data/!Command (DC) ---> N2HET[10]
  • Data IN (DIN) ---> N2HET[6]
  • Data IN (DIN) ---> MIBSPI1SIMO/ADVERT
  • Clock signal ---> N2HET[4]  
  • Clock signal ---> MIBSPI1CLK
  • Vcc (VCC) ---> N2HET[2]
  • LEDs (LIGHT) ---> N2HET[0]
  • Ground (GND) ---> GND

Note that Vcc is not connected to the 3.3V reference voltage of the launchpad, but instead of a HET pin. This is because this way we have more control over the powerup of the display.


To be continued...


My Github
https://github.com/DiegoRosales

Datasheet

https://www.sparkfun.com/datasheets/LCD/Monochrome/Nokia5110.pdf

Useful videos

http://www.youtube.com/watch?v=M9XBFomX7JI
http://www.youtube.com/watch?v=RAlZ1DHw03g

My Github
https://github.com/DiegoRosales

lunes, 6 de enero de 2014

Hercules Launchpad #5 - Comunicación Serial (SCI / Serial Communications Interface)

Ahora les voy a enseñar cómo hacer que la tarjeta se comunique de manera serial a través del puerto USB para transmitir mensajes.
Como ustedes podrán ver, la tarjeta posee un chip de la marca FTDI. Esta empresa es ampliamente conocida por fabricar circuitos integrados capaces de encargarse de la comunicación serial a través del puerto USB. Este chip en particular es el modelo FT2232HL, que convierte el protocolo USB a UART (Universal Asynchronous Receiver/Transmitter). El protocolo UART es muy sencillo y flexible. Consiste en un bit de inicio, varios bits de datos (este número de bits es predefinido) y uno o dos bits de paro. También puede tener bits de paridad y demás monerías. Como podrán ver en la hoja de datos, este chip tiene muchísimas aplicaciones


En esta tarjeta el chip se usa para dos cosas: 
  • Programación y depuración del procesador a través de la emulación JTAG
  • Comunicación serial usando los protocolos UART
Ahora vamos a hacer un ejemplo donde desde la computadora le mandemos instrucciones al procesador para que cambie el ciclo de trabajo de el LED conectado al puerto HET. Para este ejemplo vamos a utilizar un programa de comunicación serial llamado RealTerm (les dejo el link http://realterm.sourceforge.net/) Comencemos!

Paso 1: Configuración en HALcoGen
Lo primero que hay que hacer es configurar la tarjeta en HALcoGen.

Paso 1.1: Driver Enable
En la pestaña que dice "Driver Enable", habilitamos las casillas que dicen "Enable SCI Driver" y "Enable HET Drivers".

Paso 1.2: HET
Ahora vamos a configurar el HET para que se inicialice con un ciclo de trabajo del 50% a una frecuencia de 1Hz.
Para esto, en la subpestaña que dice "PWM 0-7" nos vamos al primer PWM y lo configuramos para que posea un periodo de 1000000us y un ciclo de trabajo del 50% y lo habilitamos para que salga al pin 8.


Luego, en la subpestaña que dice "Pin 8-15", habilitamos el pin 8 para que sea salida.


Paso 1.3: SCI
Ahora vamos a configurar el SCI. Para esto nos vamos a la pestaña que dice "SCI" y en la subpestaña que dice "SCI/LIN Data Format" hacemos que esté a una frecuencia (baudrate) de 9600 con 2 bits de paro, 8 bits de datos y sin bits de paridad.


Ya tenemos todo listo. Ahora hay que generar el código (F5).

Paso 2: Escribir el Programa
Como se podrán imaginar, el módulo SCI posee varias funciones para poder ser utilizado con facilidad. A continuación veremos cuáles vamos a usar.

Paso 2.1: Configurar el proyecto en Code Composer Studio
Ahora abrimos Code Composer Studio y lo configuramos como lo hemos hecho siempre

Paso 2.2: Escribir el programa principal
Abrimos el archivo que dice "sys_main.c" y escribimos lo siguiente.
Primero hay que incluir todo lo que necesitamos. Esto es, los headers de el SCI y del HET







Luego, para facilitar el programa, hay que definir un tipo usando #define. El tipo que hay que definir es "unsigned char", que es una variable de 8 bits ("char") sin signo ni nada ("unsigned"). A este tipo le vamos a llamar "byte". Esto se hace así.







Pueden ver que también definí una variable llamada "PWM" tipo "byte". Esta va a ser la variable que va a almacenar el ciclo de trabajo que le vamos a mandar desde la computadora.
Ahora hay que inicializar los módulos








Ahora viene lo bueno. En el manual de HALcoGen, en la sección del SCI, pueden ver que hay una función llamada "sciReceive" y nos da la siguiente explicación.


Lo que esta función hace es esperar a que le mandemos un dato de 8 bits con 2 bits de paro y ningún bit de paridad (como lo definimos en HALcoGen). Esta función detiene el flujo del programa hasta que no reciba el dato. Sin embargo, el LED no va a dejar de parpadear por eso, ya que el HET funciona de manera independiente al flujo del programa.
Lo que hay que introducir a esta función para que haga su trabajo es la dirección del módulo, la cantidad de "bytes" que va a recibir (en este caso sólo es 1) y un apuntador diciendo dónde vamos a guardar el dato recibido.

Nota 1: la cantidad de los bytes que vamos a recibir debe ser igual al tamaño de la variable en la que los vamos a guardar. En este caso el tamaño es 1, pero puede ser un arreglo indefinido de bytes (por ejemplo "byte variable[] = "Hola Mundo!""), por lo que hay que usar funciones como "sizeof()" para determinar el número de bytes que vamos a recibir. De otro modo, vamos a tener errores que el compilador no va a detectar.

Continuemos...

El código resultante de esto queda de la siguiente manera.
















Pueden ver que agregue una sección donde checa si el PWM ingresado es válido o no.

Paso 3: Probar la comunicación
Existen varias maneras de establecer una comunicación serial en la computadora. Una es utilizando la terminal serial que trae Code Composer Studio. Sin embargo, yo les voy a mostrar un programa llamado RealTerm que está muy completo y tiene un chorro de monerías.

Paso 3.1: abrir RealTerm
Abrimos RealTerm y nos aparece la siguiente pantalla.


En esta pestaña (Display) nos aseguramos que esté seleccionado Ascii (aunque la verdad no me he puesto a ver si funciona igual con los demás).

Paso 3.2: Configurar el puerto
Ahora nos vamos a la pestaña que dice "Port" y hacemos los siguientes ajustes: Parity None, Data Bits 8, Stop Bits 2, Baud 9600, Port 4 (o donde esté conectado la tarjeta. Esto se puede ver en el administrador de dispositivos en la categoría de puertos COM y LPT). Ya que tenemos todo como se muestra, le damos clic en "Change" y luego en "Open".


Paso 3.3 Mandar datos
Ahora nos vamos a la pestaña que dice "Send" y ya podemos comenzar a mandarle datos. En la casilla de texto escribimos un número y luego le damos clic en "Send Numbers".


Así de sencillo fue!

Nota 2: La funcion "sciSend" es igual de fácil de utilizar que el "sciReceive" y funciona perfectamente con RealTerm.

Luego les enseñaré cómo hacer un programa en Visual Studio que se comunique a través del puerto serial.

Les dejo el link del código


My Github
https://github.com/DiegoRosales

domingo, 22 de diciembre de 2013

Hercules Launchpad #4 - Interrupciones (Interrupts) Parte 2

En la parte 1 de esta entrada vimos cómo el procesador puede reaccionar a las interrupciones generadas por cambios en el estado de un bit (el bit del push button). Ahora veremos cómo el procesador puede reaccionar a las interrupciones generadas por el HET (High End Timer) y por el módulo RTI (Real Time Interrupt). Este último módulo está especialmente diseñado para medir cuentas de tiempo.
En este ejemplo vamos a hacer que se prendan los dos LEDs que tiene la tarjeta, pero con diferente frecuencia. Uno de los LEDs va a ser el resultado de las interrupciones del HET y el otro del RTI.

Paso 1:
Abrimos y configuramos HALcoGen de la siguiente manera. Primero en la pestaña de Driver Enable habilitamos los drivers RTI, GIO y HET.

Luego nos vamos a la pestaña de RTI y en la subpestaña que dice "RTI1 Compare" configuramos el comparador 0 para que mande una interrupción cada 200ms, por ejemplo.


Nota 1: El RTI puede interrumpir por desbordamiento o por comparación. Es decir, puede interrumpir cuando el contador llega a su límite y debe comenzar desde cero o cuando la cuenta es igual a la constante que definimos para comparar.

Ya que tenemos eso, nos vamos a configurar el HET. Configuramos el PWM0 para que tenga un período de 1 segundo con un ancho de pulso del 80% para que se vean bien los cambios.


Luego en la subpestaña que dice "Pwm Interrupts" habilitamos las interrupciones que dicen "End of duty" y "End of period" en High Level. Habilitamos las dos para que el LED se encienda cuando termina el ciclo de trabajo (la parte alta) y se apague el resto del periodo.


Nota 2: El HET tiene 3 modos de interrupción: cuando acaba el ciclo de trabajo, cuando acaba el periodo o cuando detecta un flanco (de subida o bajada) en alguno de los pines si es que estos están configurados como entradas.

Ahora habilitamos el LED (Bit 8) en la subpestaña que dice "Pins 8-15" para que sea una salida.


Luego en la pestaña que dice "GIO" configuramos el bit 2 (el que está conectado al otro LED) como salida.


Por último en la subpestaña que dice "VIM Channel 0-31" dentro de la pestaña principal (RM42L432PZ) habilitamos el canal 2 (RTI Compare 0) y el canal 10 (HET Level 0).


Estas han sido todas las configuraciones necesarias de HALcoGen. Ya podemos generar los archivos (F5).

Paso 2:
Ahora comencemos con el código. Dentro de Code Composer Studio creamos nuestro nuevo proyecto igual como le hemos estado haciendo (Paso 5 Paso 6 del primer tutorial). Luego, en el archivo "sys_main.c" escribimos lo siguiente.
Paso 2.1 (includes):
Los archivos que hay que incluir son los siguientes






Paso 2.2 (main()):
En el main hay que inicializar los módulos y las interrupciones (ya que no parece haber manera de que se inicializen desde el principio usando HALcoGen). También hay que hacer que el contador 0 del módulo RTI comience a contar.















Paso 2.3 (control de interrupciones):
Luego hay que irnos al archivo "notifications.c" para ver qué hacemos con las interrupciones. Dentro del control de interrupciones del RTI escribimos lo siguiente












Nota 3: En este pedazo de código pueden ver cómo las funciones del GIO pueden controlar los pines del módulo HET.

Dado que no tenemos ninguna otra fuente de interrupciones del RTI, no hay que ponerle ningún if para ver de dónde vienen las interrupciones. Lo mismo sucede con el control de interrupciones del HET (pwmNotification).










Y pues ya con esto tenemos todo el código que necesitamos. Si lo corremos en la tarjeta, podemos ver que los dos LED prenden y apagan a velocidades distintas, pero sincronizadas. Llega un punto donde los dos LEDs encienden y apagan al mismo tiempo, ya que 200ms es múltiplo de 1 seg y el 80% de 1 segundo son 200ms!!!

Les dejo los archivos.
https://www.mediafire.com/?4i1y1jdm4clt88h

My Github
https://github.com/DiegoRosales

Nota 4: El manual de ayuda de HALcoGen es de gran ayuda. Viene extremadamente bien documentado y trae algunos ejemplos.

lunes, 16 de diciembre de 2013

Hercules Launchpad #3 - Interrupciones (Interrupts) Parte 1

Ahora vamos a rediseñar el programa anterior para que funcione con interrupciones y sea más eficiente. 
El microcontrolador que trae la tarjeta tiene dos prioridades para las interrupciones: prioridad alta (High) y prioridad baja (Low). Como ustedes sabrán (o no), las interrupciones son causadas por eventos fuera del flujo normal del programa (pulsar un botón, por ejemplo). Cuando se genera la interrupción, el programa salta inmediatamente a algo llamado "Interrupt Service Rutine" (rutina de servicio a las interrupciones) o SCR, que es un espacio en la memoria con instrucciones que responden a la interrupción según lo que queramos.
Este microcontrolador posee algo llamado "Vectored Interrupt Manager" y es el módulo que nos ayuda a configurar y reaccionar a las interrupciones. Si nos vamos al manual, podemos ver lo siguiente

Los 96 canales son las fuentes de interrupción y todas se pueden configurar a través de HALcoGen, así que comencemos.

Paso 1:
Abrimos HALcoGen, creamos nuestro proyecto y habilitamos únicamente el GIO Driver. Luego nos vamos a la pestaña de GIO y habilitamos la salida del bit 2 (LED) y en el bit 7 habilitamos la interrupción con flanco de subida (Rising Edge) y baja prioridad (Low Priority)


Paso 2:
Ahora hay que configurar el VIM. Para esto nos vamos a la pestaña del microcontrolador (RM42L432PZ) y nos vamos a la subpestaña que dice "VIM Channel 0 - 31". Ahí mismo nos vamos al número 23 que dice "GIO Int B".

Nota: "GIO Int B" se usa para las interrupciones de baja prioridad (Low Priority), mientras que "GIO Int A" se usa para las interrupciones de alta prioridad (High Priority).

Ya que tenemos configurado todo, generamos el código (F5).

Paso 3:
Ya que generamos los archivos, abrimos Code Composer Studio y creamos un nuevo CCS Project con nuestras especificaciones y lo configuramos para que acepte los archivos de HALcoGen.
Luego abrimos el archivo "notification.c" para configurar lo que queremos que el micro haga cuando genere nuestra interrupción. Como podrán ver, el archivo está casi vacío, por lo que es evidente que está diseñado para que nosotros escribamos nuestro código. Si nos vamos a donde está el comentario 19, podemos observar que éste se encuentra dentro de la función "gioNotification". Si vemos el manual de ayuda de HALcoGen, podemos ver que la función acepta 2 parámetros: el puerto y el número de bit. Por lo tanto, para saber si la interrupción fue generada por el botón, hay que escribir el código siguiente

void gioNotification(gioPORT_t *port, sint32 bit)
{
/*  enter user code between the USER CODE BEGIN and USER CODE END. */
/* USER CODE BEGIN (19) */
// Checa si el botón generó a interrupción
if((port==gioPORTA) && (bit==7))
{
// Enciende y apaga el LED
gioToggleBit(gioPORTA, 2);
}
/* USER CODE END */
}
Paso 4:
Ahora nos vamos al archivo "sys_main.c" e incluimos la librería del GIO.

/* USER CODE BEGIN (0) */
#include "gio.h"

/* USER CODE END */

Y más abajo escribimos

void main(void)
{
/* USER CODE BEGIN (3) */
// Inicializa los módulos
gioInit();
_enable_IRQ();

// Ciclo infinito
while(1);
/* USER CODE END */
}

Noten que en el programa principal sólo hay que inicializar los drivers y crear un ciclo infinito, ya que el VIM se encarga de controlar las interrupciones. Esto hace que el microcontrolador no esté checando constantemente si el botón fue presionado mientras está en el programa principal, sino que lo hace como que en paralelo.

Les dejo el código que hice

http://www.mediafire.com/download/i32fbdbub7vsvv4/Tutorial%203.zip

My Github
https://github.com/DiegoRosales