PicManía by RedRaven
 

Búsqueda personalizada

 

LA LIBRERÍA GRÁFICA DE MICROCHIP

 
 


Ideas, Rutinas y Técnicas

 
 

   La EXPLORER-16 tiene un bus de expansión. En este bus se puede conectar, entre otras tarjetas, la Graphics PICTail Plus Board con una pantalla TFT Samsung S6D0129 con pantalla táctil resistiva.

   Todos ejemplos que se muestran en esta sección se han realizado usando el C30 (v3.0.2) de Microchip para PIC24H y dsPIC.

 

Introducción:
 

   Microchip nos proporciona gratuitamente una magnifica librería gráfica, realizada en C30, para la serie PIC24 de este fabricante. Incluye drivers para una media docena de TFT gráficas de distintos fabricantes y una gran colección de funciones de bajo y alto nivel.
 

   Incluye también una buena serie de ejemplos en la que se explotan la mayoría de las posibilidades de esta librería. Basándome en estos ejemplos me propongo desarrollar una serie de ejemplos mas sencillos para ir construyendo, paso a paso, ejemplos de más enjundia.
 

 
Índice General:
 
  Bailando con Gráficos:
 
  • Test1 Un botón que incrementa una variable.
  • Test2 KEYPAD que genera mensajes en las pantalla.
 
 


 

Nota1: El Micro usado es el PIC34FJ128GA010 sobre la tarjeta de desarrollo Explorer-16
 

 


Test1 Un botón que incrementa una variable.
 

Empezando a comprender la Librería Gráfica de la gente de Microchip. Y me gusta. Se parece mucho a las LeadTools que utilizaba en Delphi, la filosofía es muy parecida. Y además el Copy/Paste con los ejemplos que trae hacen maravillas para poder montar un proyecto nuevo.

El caso es que he abierto un proyecto desde cero y he intentado montar un ejemplito fácil pero que me hiciese ver qué es lo que me hacía falta, para ir añadiéndolo al proyecto, y en qué orden. Digamos que el cuerpo base es el del ejemplo "Graphics AN1136" de donde he sacado la configuración general y el tratamiento de un simple Buttom. Del ejemplo "Graphics Primitive Layer Demo" he sacado el tratamiento de Fonts del texto y por último del "Graphics Object Layer Demo" el tema del Beep cuando pulso sobre el botón.

Así he montado un programa que: Coloca un texto de cabecera al inicio a modo de presentación, crea un Botón en la posición, con el tamaño y el texto que yo deseo. Al pulsar sobre el Botón emite un Beep, incrementa una variable y muestra su valor en el centro de la pantalla con otro tipo y color distintos de la letra.

Además me he saltado a la torera una de las prescripciones que venían en la Ayuda de la Librería Gráfica, y que decía dónde tenía que poner el proyecto para que funcionasen los includes, las librerías y todo eso ... Y lo he colocado en MI directorio de proyectos, a un kilómetro de donde me decían que tenia que poner todo. Me ha costado un poco de trabajo configurar todo el tema de los directorios de includes y eso pero al final ha funcionado correctamente.

El resultado: Un pequeño paso para la Humanidad pero un salto gigantesco para mí.

 
     
  /*****************************************************************************
* © 2008 PicManía By RedRaven
* http://picmania.garcia-cuervo.net
*
* FileName: test1.c
* Dependencies: Test1.h
* Processor: PIC24FJ128GA010
* Compiler: MPLAB C30 V3.00
* Linker: MPLAB LINK30
*
* Coloca un texto de cabecera. Crea un Botón.
* Al pulsar sobre el Botón emite un Beep,
* incrementa una variable y muestra su valor
* en el centro de la pantalla
*****************************************************************************/

#include "Test1.h"
#include <stdio.h>

// Configuration bits
_CONFIG2(FNOSC_PRIPLL & POSCMOD_XT) // Primary XT OSC with PLL
_CONFIG1(JTAGEN_OFF & FWDTEN_OFF) // JTAG off, watchdog timer off

///////////////////////////////// FONTS ///////////////////////////////////////
extern FONT_FLASH Font35;

/////////////////////////////////////////////////////////////////////////////
// OBJECT'S IDs
/////////////////////////////////////////////////////////////////////////////

#define ID_BTN1 10

/////////////////////////////////////////////////////////////////////////////
// LOCAL PROTOTYPES
/////////////////////////////////////////////////////////////////////////////
void Present_Me(void);
void Monitor_Value(void);
void CheckCalibration(void); // check if calibration is needed

/////////////////////////////////////////////////////////////////////////////
// MAIN
/////////////////////////////////////////////////////////////////////////////
GOL_SCHEME *altScheme; // alternative style scheme
WORD update = 0; // variable to update customized graphics
unsigned int Value = 0;
unsigned int antValue = 0;

int main(void){

  GOL_MSG msg; // GOL message structure to interact with GOL

  EEPROMInit(); // initialize EEPROM
  TouchInit(); // initialize touch screen
  BeepInit(); // Initialize beeper
  GOLInit(); // initialize graphics library &
  // create default style scheme for GOL
  SetColor(BLACK);
  ClearDevice();

  Present_Me();

  altScheme = GOLCreateScheme(); // create alternative style scheme
  altScheme->TextColor0 = BLACK;
  altScheme->TextColor1 = WHITE;

  BtnCreate( ID_BTN1, // object’s ID
    10, 50, // object’s Top Left Corner
    110,100, // object’s Bottom Right Corner
    0, // radius of the rounded edge
    BTN_DRAW, // draw the object after creation
    NULL, // no bitmap used
    "One ++", // use this text
    altScheme); // use alternative style scheme

  update = 1; // to initialize the user graphics

  while(1){
    if(GOLDraw()) { // Draw GOL object
      TouchGetMsg(&msg); // Get message from touch screen
      GOLMsg(&msg); // Process message
    }
  }
}

void Present_Me(void){

  static const char text[] = "'One Beep Button' by PicMania";

  SetFont(&FONTDEFAULT);
  SetColor(BRIGHTRED);
  MoveTo(0,0);
  while(!OutText((char*) text));
}

void Monitor_Value(void){

  static char text[6];

  // Delete ant Text
  sprintf(text,"%4d",antValue);
  MoveTo(150,110);
  SetFont(&Font35);
  SetColor(altScheme->TextColor0);
  while(!OutText((char*) text));
  // Print act Text
  sprintf(text,"%4d",Value);
  MoveTo(150,110);
  SetColor(altScheme->TextColor1);
  while(!OutText((char*) text));
}


/////////////////////////////////////////////////////////////////////////////
// Function: WORD GOLMsgCallback(WORD objMsg, OBJ_HEADER* pObj, GOL_MSG* pMsg)
// Input: objMsg - translated message for the object,
// pObj - pointer to the object,
// pMsg - pointer to the non-translated, raw GOL message
// Output: if the function returns non-zero the message will be processed by default
// Overview: it's a user defined function. GOLMsg() function calls it each
// time the valid message for the object received
/////////////////////////////////////////////////////////////////////////////
WORD GOLMsgCallback(WORD objMsg, OBJ_HEADER* pObj, GOL_MSG* pMsg){

  WORD objectID;

  objectID = GetObjID(pObj);

  if (objectID == ID_BTN1) {
    if (objMsg == BTN_MSG_PRESSED) { // check if button is pressed
      antValue=Value;
      ++Value;
      Beep();
    }
    update = 1;
  }

  return 1;
}

/////////////////////////////////////////////////////////////////////////////
// Function: WORD GOLDrawCallback()
// Output: if the function returns non-zero the draw control will be passed to GOL
// Overview: it's a user defined function. GOLDraw() function calls it each
// time when GOL objects drawing is completed. User drawing should be done here.
// GOL will not change color, line type and clipping region settings while
// this function returns zero.
/////////////////////////////////////////////////////////////////////////////
WORD GOLDrawCallback(){

  if(update){
    Monitor_Value();
    update = 0;
  }

  return 1;
}
 
 
     
 
Esta es la configuración de los includes del programa principal:
 
     
  /*********************************************************************
* FileName: Test1.h
********************************************************************/
#ifndef _TEST1_H
#define _TEST1_H

// Oscillator frequency
#define SYSCLK 32000000 // 8MHz x 4PLL

////////////////////////////// INCLUDES //////////////////////////////
#include <p24Fxxxx.h>
#include "GenericTypeDefs.h"
#include "Graphics.h"
#include "EEPROM.h"
#include "TouchScreen.h"
#include "Beep.h"

#endif
 
 
     

Y los includes y demás son estos (copio la pantalla del Proyecto en MPLAB):
 

 
 

 
 

 


Test2 KEYPAD que genera mensajes en las pantalla.
 

Quien pone un botón pone ciento. así que aquí el test2.c que pone en pantalla un KEYPAD con los 10 números, del "0" al "9", y otros dos mas con "Si" y "No". Las dos líneas superiores están destinadas a Texto, la primera de ellas a un texto fijo y la segunda para presentar mensajes. Al pulsar cada uno de los botones se van acumulando sobre un string que se presenta en la segunda línea de texto, la de los mensajes.

Los detalles interesantes de este ejemplo son:

La función Create_Objects() crea on-the-fly los botones, en función de los parámetros definidos con KEYPAD_BTN, NUMVERSPC, NUMHORBTN y NUMVERBTN. Lo único importante a tener en cuenta es que los Textos que aparecen en cada botón tienen que ser contantes ó variables estáticas diferenciadas, yo he utilizado la matriz de constantes BtnTexts, cuando lo intenté creando un string que iba cambiando según creaba cada uno de los botones me aparecían todos los botones con el texto del ultimo contenido del string.

La función GOLMsgCallback() es llamada cada vez que se produce un "evento". Ahí es donde preguntamos por el objeto que produce el evento, a través de su objectID y el tipo de evento producido, en nuestro caso "interceptamos" el tipo BTN_MSG_PRESSED y con él vamos cargando el string de salida MyText[]. Cada vez que tenemos un evento válido nuevo ponemos en alto un flag llamado update.

La función GOLDrawCallback() es llamada por la librería cada vez que tiene que actualizar la pantalla. En ella detectamos si tenemos el flag update en alto y en caso de ser así ponemos el string MyText[] en la pantalla.
 

 
     
  /*****************************************************************************
* © 2008 PicManía By RedRaven
* http://picmania.garcia-cuervo.net
*
* FileName: test2.c
* Dependencies: Test2.h
* Processor: PIC24FJ128GA010
* Compiler: MPLAB C30 V3.00
* Linker: MPLAB LINK30
*
* Matriz de botones numericos + función.
* Area de Textos fijos
* Area de Mensajes con lo pulsado en el KEYPAD
*****************************************************************************/

#include "Test2.h"
#include <stdio.h>

// Configuration bits
_CONFIG2(FNOSC_PRIPLL & POSCMOD_XT) // Primary XT OSC with PLL
_CONFIG1(JTAGEN_OFF & FWDTEN_OFF) // JTAG off, watchdog timer off

///////////////////////////////// FONTS ///////////////////////////////////////
extern FONT_FLASH Font25;
extern FONT_FLASH Font35;

/////////////////////////////////////////////////////////////////////////////
// OBJECT'S IDs & DIMENSIONS
/////////////////////////////////////////////////////////////////////////////

#define KEYPAD_BTN 10
#define NUMVERSPC 1
#define NUMHORBTN 4
#define NUMVERBTN 3

/////////////////////////////////////////////////////////////////////////////
// LOCAL PROTOTYPES
/////////////////////////////////////////////////////////////////////////////
void Create_Objects(void);
void CheckCalibration(void); // check if calibration is needed

/////////////////////////////////////////////////////////////////////////////
// MAIN
/////////////////////////////////////////////////////////////////////////////
GOL_SCHEME *altScheme; // alternative style scheme
WORD update = 0; // variable to update customized graphics
static char MyText[32] = "\0";
WORD nextChar = 0;
static const char BtnTexts[12][3] = {"1","2","3","Si","4","5","6","0","7","8","9","No"};
WORD updateSi = 0;
WORD updateNo = 0;

int main(void){

  GOL_MSG msg; // GOL message structure to interact with GOL

  EEPROMInit(); // initialize EEPROM
  TouchInit(); // initialize touch screen
  BeepInit(); // Initialize beeper
  GOLInit(); // initialize graphics library &
  // create default style scheme for GOL
  SetColor(BLACK);
  ClearDevice();
  CheckCalibration();
  Create_Objects();

  while(1){
    if(GOLDraw()) { // Draw GOL object
      TouchGetMsg(&msg); // Get message from touch screen
      GOLMsg(&msg); // Process message
    }
  }
}

void Create_Objects(void){

  static const char text[] = "Indalo Touch KEYPAD by dmarquez";
  unsigned int nbuttons,VerDiv,HorDiv;
  unsigned int i,PosX,PosY,nHor;

  SetFont(&Font25);
  SetColor(WHITE);
  MoveTo(0,0);
  while(!OutText((char*) text));

  altScheme = GOLCreateScheme(); // create alternative style scheme
  altScheme->TextColor0 = BLACK;
  altScheme->TextColor1 = WHITE;

  VerDiv = (unsigned int) GetMaxY() / (NUMVERBTN + NUMVERSPC);
  HorDiv = (unsigned int) GetMaxX() / NUMHORBTN;
  nbuttons = NUMHORBTN * NUMVERBTN;
  PosX = 0; PosY = VerDiv;
  nHor = 0;

  SetFont(&Font35);

  for(i=0;i<nbuttons;i++){

    BtnCreate( KEYPAD_BTN+i, // object’s ID
      PosX, PosY, // object’s Top Left Corner
      PosX+HorDiv,PosY+VerDiv,// object’s Bottom Right Corner
      0, // radius of the rounded edge
      BTN_DRAW, // draw the object after creation
      NULL, // no bitmap used
      (char*) BtnTexts[i], // use this text
      altScheme); // use alternative style scheme
    PosX += HorDiv;
    if(++nHor==NUMHORBTN){
       nHor = 0;
       PosX = 0;
       PosY += VerDiv;
    }
  }
  update = 1; // to initialize the user graphics
}


/////////////////////////////////////////////////////////////////////////////
// Function: WORD GOLMsgCallback(WORD objMsg, OBJ_HEADER* pObj, GOL_MSG* pMsg)
// Input: objMsg - translated message for the object,
// pObj - pointer to the object,
// pMsg - pointer to the non-translated, raw GOL message
// Output: if the function returns non-zero the message will be processed by default
// Overview: it's a user defined function. GOLMsg() function calls it each
// time the valid message for the object received
/////////////////////////////////////////////////////////////////////////////
WORD GOLMsgCallback(WORD objMsg, OBJ_HEADER* pObj, GOL_MSG* pMsg){

  WORD objectID;
  unsigned int nbuttons;
  char c;

  objectID = GetObjID(pObj);
  nbuttons = NUMHORBTN * NUMVERBTN;

  if((objectID > (KEYPAD_BTN - 1)) && (objectID < (KEYPAD_BTN + nbuttons))){
    if(objMsg == BTN_MSG_PRESSED) { // check if button is pressed
      c = BtnTexts[objectID-KEYPAD_BTN][0];
      // Botón Especial "Si"
      if(c=='S'){
        updateSi = 1;
      }
      else{
        // Botón Especial "No"
        if(c=='N'){
          updateNo = 1;
        }
        else{
          MyText[nextChar++]=c;
          MyText[nextChar] ='\0';
        }
      }
      Beep();
    }
    update = 1;
  }
  return 1;
}

/////////////////////////////////////////////////////////////////////////////
// Function: WORD GOLDrawCallback()
// Output: if the function returns non-zero the draw control will be passed to GOL
// Overview: it's a user defined function. GOLDraw() function calls it each
// time when GOL objects drawing is completed. User drawing should be done here.
// GOL will not change color, line type and clipping region settings while
// this function returns zero.
/////////////////////////////////////////////////////////////////////////////
WORD GOLDrawCallback(){

  unsigned int i;

  if(update){
    SetFont(&Font35);
    // Función Especial "Si" Flash Texto.
    if(updateSi){
      updateSi=0;
      for(i=0;i<10;i++){
          SetColor(BRIGHTGREEN);
          MoveTo(0,GetTextHeight(&Font25));
          OutText(MyText);
          DelayMs(250);
          SetColor(BRIGHTRED);
          MoveTo(0,GetTextHeight(&Font25));
          OutText(MyText);
          DelayMs(250);
          SetColor(WHITE);
          MoveTo(0,GetTextHeight(&Font25));
          OutText(MyText);
          DelayMs(250);
        }
      }
      else{
        // Función Especial "No" Borra Todo.
        if(updateNo){
        updateNo=0;
        SetColor(BLACK);
        MoveTo(0,GetTextHeight(&Font25));
        OutText(MyText);
        nextChar = 0;
        MyText[0]='\0';
      }
      else{
        SetColor(YELLOW);
        MoveTo(0,GetTextHeight(&Font25));
        OutText(MyText);
      }
    }
    update = 0;
  }
  return 1;
}

// End //////////////////////////////////////////////////////////////////////
 
 
     
 

 
 

 

Esta página se modificó el 27/12/2008


Esta página usa la letra Ñ

Nota pública importante sobre las consultas al Webmaster de PicManía.


Sugerencias a Picmanía... (que serán leídas pero seguramente no podrán ser contestadas)

Esta página pertenece al grupo de páginas de Diego RedRaven

 

 



Nota: Esta página Web esta repleta de imágenes, textos, logotipos y demás material extraídos de los mas variados medios de los que no soy ni autor ni depositario de los correspondientes derechos de autor, uso y/o reproducción. Si Ud. es depositario de dichos derechos y desea que el material correspondiente sea eliminado de esta Web no dude en ponerse en contacto conmigo mediante e-mail y será inmediatamente retirado. Gracias.
 
Visitas
Totales : 74921 Hoy: 1 Activas: 1 Vistas: 74921

Esta página fue modificada el 07-08-2010 22:42:34

           
 DmSoft WAMP Escribir Unreal