sexta-feira, 29 de abril de 2011

Criando um Workspace e debugando seu programa

No ultimo post ensinamos como criar uma biblioteca para executar código morse através do led, nesse mostraremos como utilizar o workbench para criar uma área de trabalho e dubugar o programa.
As bibliotecas “CodigoMorse.c” e ”CodigoMorse.h” já se encontram para download.
Crie uma pasta para colocar os arquivos em qualquer local de “Usuários”, pois se for criado em (C:\ArquivosdeProgramas) o Workbech terá que ser sempre executado como administrador, para Windows Vista e 7.
Inclua nesta a pasta das bibliotecas “inc” encontrada em (C:\Program Files (x86)\IAR Systems\Embedded Workbench 6.0 Kickstart\430), e crie outra pasta com o nome “projetos”.
Ponha as duas bibliotecas já prontas na pasta “inc”.
Agora abra o Workbench e vá em (File → New → File).
Escreva o seu codigo "main", que também pode ser encontrado para download:

#include "msp430.h"
#include "CodigoMorse.h"

int main(void)
{
      unsigned char i;
      WDTCTL = WDTPW + WDTHOLD;    // Interrompe o watchdog
      P1DIR |= 0x01;                            // Seta P1 como saida
      for (;;)                                         // Inicia loop infinito
      {
           CodigoMorse('S');
           CodigoMorse('O');
           CodigoMorse('S');
           P1OUT = 0x00;     //Termina a mensagem e aguarda antes de reiniciar
          for(i=0;i<10;i++)
         {
              TempoEntreLetras();
         }
      }
}

Salve esse arquivo na pasta “inc” com o nome “MainMorce.c”.
Após todos os processos concluídos, a árvore de includes fica assim:
As bibliotecas principais do MSP430 são básicas para o programa principal e para as todas nossas bibliotecas que iremos criar, portanto não podemos esquecer de incluí-las.
Agora você tem tudo que precisa para criar um worspace e fazer o download do programa para o microcontrolador.

Vamos começar criando e configurando a área de trabalho:
Vá em (File → New → workspace), e depois em (Project → Create New Project).
Na janela que abrir selecione “Empty Project” e pressione “Ok”.
Uma nova janela irá se abrir, salve com o nome “CodigoMorse.ewp” na pasta “projetos”.
Vá em (Project → Options → General Options → Device), selecione (MSP430x2xx Family → MSP430F2013)
Por ultimo em (Project → Options → Debugger → Driver), certifique-se de que esteja selecionado “FET Debugger” e não “Simulator”

Agora o workspace esta pronto para receber os arquivos:
Clique com o botão direito do mouse na janela da esquerda com o nome “Workspace” e depois em (Add → Add Files).
Adicione os 2 “.c” previamente criados (CodigoMorse.c e MainMorse.c).
Vá em (File → Save Workspace), e salve sua área de trabalho com o nome “CodigoMorse.eww”, não esquecendo que deve ser salvo na pasta “projetos”.

Antes de executar o download você devera ter certeza de que os arquivos não apresentam erros:
Vá em (Project → Rebuild All). Deverá aparecer a seguinte janela :


Como o Workspace não possui erros, o projeto poderá ser copilado no microprocessador.
Note também que toda a árvore de includes foi incluída automaticamente.


Vá em (Project → Download and Debug).
Caso o computador não consiga se comunicar com o microprocessador, provavelmente é erro de reconhecimento da placa, veja o post sobre instalação.
Caso a comunicação não apresente falhas o projeto será baixado e o Workspace irá mudar.
Agora você ira aprender a utilizar os botões que controlam o microprocessador, e que podem ajudá-lo a inclusive “debugar” o programa.
Da esquerda para a direita:

  1. Reset: reinicia o projeto que esta sendo executado.
  2. Break: para a execução do projeto, estará incessível a menos que o projeto esteja sendo executado.
  3. Step Over: executa a atual linha do código, e vai para a próxima.
  4. Step Into: executa o próximo passo do código. Por exemplo, em um for(i=0;i<5;i++): caso i=3 o próximo passo é incrementar i, mas sem sair do for.
  5. Step Out: termina os passos da atual linha. No caso anterior o for iria ser concluído diretamente.
  6. Next Statement: vai para a próxima linha de comando do programa principal.
  7. Run to Cursor: executa o programa até a linha indicada pelo cursor. A linha indicada não será executada.
  8. Go: começa a executar o projeto.
  9. Stop Debugging: interrompe o debugging e volta pra a área de trabalho anterior.
Mas, os botões só funcionaram assim caso existam funções, se o código não apresentar funções, então o botão 6 funcionará igual ao 4.
Também é de grande utilidade utilizar a janela “watch”, vá em (View → Watch).
Agora você pode selecionar qualquer variável do código e arrastá-la para essa janela para que possa acompanhar seus valores mudando e assim compreender melhor o que esta acontecendo.
Agora que você já sabe como utilizar os botões poderá ver o SOS passo a passo, ou de uma vez, divirta-se!
Finalmente, após 2 semanas você finalmente viu o tão esperado SOS, mas agora com todas informações que já tem e com a biblioteca completa, você pode escrever o que quiser, pode modificar as rotinas de tempo, criar funções para executar frases, etc.

Bom acho que por enquanto é isso, mande suas duvidas para agente através dos comentários, tentaremos ao máximo solucioná-las, caso precisem de ajuda para o workbench, procurem em seu datasheet.

Valeu, e até semana que vem quando começaremos a falar sobre o hardware!


sexta-feira, 22 de abril de 2011

Creating a program and library to the MSP

In this post we will talk about the libraries already used in the previous example and create new libraries from the analysis of the example.
Let's start with the libraries already used, they are: msp430.h , msp430f2013.h, in430.h e intrinsics.h.
These are basic libraries that determine since which MSP microcontroller family is being used, even set some functions used to control the board:
• "msp430.h": this library has only the function to call the “.h” responsible for each version of msp.
• "msp430f2013.h": this is the file that is called to the MSP we are using
is responsible for basic configurations and settings to control the board, such as doors, inputs and outputs, watchdog, registers, timers, bit settings, memory, interrupt.
• "in430.h": Sets the intrinsic functions and mapping compiler for the MSP430 IAR Systems C / C + +.
• "intrinsics.h": registration code intrinsic of functions of IAR Embedded Workbench for MSP430.

To show how to create libraries we decided to start the analysis from the example of the LED, and modify it to a Morse code.
But before that, a quick and (perhaps) is instructive summary of what the morse code:
Morse code is a system of representing letters, numbers and punctuation marks through a
coded signal sent intermittently.


It was developed by Samuel Morse in 1835, creator of the electric telegraph, a device that uses electrical currents to control electromagnets that work for emission or reception of signals.
A coded message in Morse can be transmitted in various ways in pulses (or tones) short and long:
electrical pulses transmitted through a cable;
mechanical waves (noise disturbance);
visual signals (lights turning on and off, as our LED);
electromagnetic waves (radio signals);

This system represents letters, numbers and punctuation marks with just a sequence of dots, dashes, and spaces.
Probably the most famous Morse code in the word is the SOS, one of the most used and signals sent in emergency situations.
In popular usage, SOS was associated with phrases such as "Save Our Seamen”, "Save Our Ship”, "Survivors On Shore" or "Save Our souls ". These phrases, however, appeared later, as a way to help remember the letters correctly (a retro-acronym). As a code, the letters SOS do not have a meaning for themselves.
Now back to embedded programming, let's consider a program that can transmit the message with just the led.
Analyzing the code of the flashing LED realize that the command responsible for turning on and off the LED is "P1OUT ^ = 0x01;", and that it must be declared as output "P1DIR | = 0x01;."
From these two commands, and a Morse code table decided to create a library that allows easily for the programmer to send a coded message in Morse code through the LED.
Use a program of your choice to build and save the following code as libraries. The following code corresponding to the library foundation for the program:
#include "CodigoMorse.h"
#include "msp430.h"

#define T_LONGO 30000   //the longer time will be used for the representation of character traits ans between characters
#define T_CURTO 10000   //the shortest time will be used for the representation of points and beyween signals
unsigned int i;

//definitions of times and outputs
void TempoCurto(void)  //TempoCurto means short time
{
      for (i=0;i<T_CURTO;i++);
}

void TempoLongo(void)   //TempoLongo means long time
{
      for (i=0;i<T_LONGO;i++);
}

void TempoEntreSinais (void)  //TempoEntreSinais means time between signals
{
      for (i=0;i<T_CURTO;i++);
}

void TempoEntreLetras (void)  //TempoEntreLetras means time between letters
{
      for (i=0;i<T_LONGO;i++);
}

void CodigoMorseTraco (void)   //TempoEntreLetras morse code traice
{
      P1OUT |= 0x01 //turn on led
      TempoLongo();
      P1OUT &= ~0x01;  //turn off led
      TempoEntreSinais();
}

void CodigoMorsePonto (void)  //TempoEntreLetras morse code dot
{
      P1OUT |= 0x01;      // turn on led
      TempoCurto();
      P1OUT &= ~0x01;   // turn off led
      TempoEntreSinais();
}

//character sets
void CodigoMorseO (void)
{
      CodigoMorseTraco();
      CodigoMorseTraco();
      CodigoMorseTraco();
      TempoEntreLetras();
}

void CodigoMorseS (void)
{
      CodigoMorsePonto();
      CodigoMorsePonto();
      CodigoMorsePonto();
      TempoEntreLetras();
}

//character selection
void CodigoMorse (char caracter)
{
//teste to see if the character that is coming I possible to represent in Morse Code
      if  
  (
     (caracter == 33) ||
     (caracter == 44) ||
     (caracter == 46) ||
     (caracter >= 48 && caracter <= 58) ||
     (caracter == 63) ||
     (caracter >= 65 && caracter <= 90) ||
     (caracter >= 97 && caracter <= 122)
      )
  {
           case 'O':
           case 'o':
           CodigoMorseO();
           break;

           case 'S':
           case 's':
           CodigoMorseS();
           break;
  }
}

Save with the name "CodigoMorse.c." The code only shows how to represent the letters O and S in Morse.
Create another document with the code of library functions:

#ifndef CodigoMorse_H
   #define CODIGOMORSE_H    //This function taks a character encoded in ASCII in the interval of 33 to 122
   void TempoCurto (void);
   void TempoLongo (void);
   void TempoEntreSinais (void);
   void TempoEntreLetras (void);
   void CodigoMorse (char caracter);
#endif

Save this file named "CodigoMorse.h." Notice that the header file only shows the functions of time (in case anyone wanted to do something beyond the standard strings) and a function that takes a character and automatically encodes it in Morse and presents it in the led.
This library will be used as follows:

for (;;) // Start infinite loop
{
      CodigoMorse('S');
      CodigoMorse('O');
      CodigoMorse('S');
      P1OUT = 0x00;      //Ends the message and waits before restarting
      for(i=0;i<10;i++)
      {
            TempoEntreLetras();   //spending time between messages
      }
}

With this, we have everything we need for next week send an SOS through the LED, we know that no one would see our SOS, but it is the basis for those who want to implement the idea to a larger scale.

In the next post we'll show you how to use libraries and how to build and debug the program in the Workbench.

See ya!