Prueba todas las maneras de configurar una pantalla LCD alfanumérica

Dependencies:   FRDM_TSI TextLCD mbed

main.cpp

Committer:
Antulius
Date:
2019-05-08
Revision:
8:39219ab1efd9
Parent:
7:af295ac5f904

File content as of revision 8:39219ab1efd9:

/* ###########################################################################
**    Archivo        : main.c
**    Proyecto       : FRDM-KL46Z_LCD_Test
**    Procesador     : MKL46Z256VLL4
**    Herramienta    : Mbed
**    Version        : Driver 01.01
**    Compilador     : GNU C Compiler
**    Fecha/Hora     : 14-07-2015, 11:48, # CodeGen: 0
**    Descripción    :
**         Este proyecto hace...
**         This module contains user's application code.
**   Componentes     : GPIO, Timer, etc .
**   Configuraciones : Includes, Stacks y Drivers externos
**   Autores         :
**         ATEAM Development Group:
**          - Antulio Morgado Valle
**
**   Versión        : Beta
**   Revisión       : A
**   Release        : 0
**   Date           : 20/10/2019
**   Bugs & Fixes   :
**                    Added support for Led_RGB
**                    22/09/2018 
**                    Added LCD Menu, Beta version (with bugs)
**
** ###########################################################################*/
/*
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:  Includes
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
*/
#include "mbed.h"
#include "I2C.h"
#include "SPI.h"
#include "Serial.h" 
#include "TextLCD.h"
#include "stdio.h"
/*
:...............................................................................
:  Definiciones
:...............................................................................
*/
#define Ticker_Rate     1000        // Periodo de interrupción (us)
#define LCD_Filas       4           // Número de Renglones del LCD
#define LCD_Columnas    20          // Número de Caracteres x Renglón del LCD
#define Buzz_On         1           // Estado para Buzzer Encendido
#define Buzz_Off        0           // Estado para Buzzer Apagado
#define on              0           // Estado para botón presionado
#define off             1           // Estado para botón sin presionar
#define hold            2           // Estado para botón mantenido presionado
#define release         3           // Estado para botón al liberarse 
/*
+-------------------------------------------------------------------------------
|  Configuración de Puertos 
+-------------------------------------------------------------------------------
*/
Ticker      TimerInt;              // Inicializa la Interrupción por Timer
DigitalOut  led_monitor(LED2); // Inicializa el LED Monitor
DigitalOut  buzzer (PTE31);         // Inicializa el Buzzer Piezo Eléctrico
//PwmOut      buzzer (PTE31);         // PWM Control del Elemento Calefactor
/*
** -------------------------------------------------------------------
**    Inicialización de los Pines de Funciones Especiales.
** -------------------------------------------------------------------
*/

/*************************************************
* Host PC Communication channels
**************************************************/
Serial      terminal(USBTX, USBRX); // Inicializa la Comunicación Serial a la PC
//Serial      terminal(PTA2,PTA1);          // Terminal Serial
//Serial      terminal(PTE0, PTE1);         // Tx, Rx Using MAX3232 or BlueTooth

/*************************************************
* Bluetooth Communication support
************************************************** 
* Initialize the library with the numbers of the interface pins
* Board Freedom FRDM-KL46Z
* IDE  Mbed On Line Compiler
***************************************************/
Serial   bluetooth(PTE0, PTE1);             // Tx, Rx

/************************************************* 
* I2C Communication
************************************************** 
* Initialize the library with the numbers of the interface pins
* Board Freedom FRDM-KL46Z
* IDE  Mbed On Line Compiler
* LCD  I2C  PCF8574A
* Pin  Board    LCD
*      I2C_SCL  SCL (white) + resistance pull-up 4.7k
*      I2C_SDA  SDA (blue)  + resistance pull-up 4.7k
*      5V       5V  (red)
*      GND      GND (black)
***************************************************/
//I2C         i2c_lcd(PTC2,PTC1);             // SDA, SCL

/*************************************************
* SPI Communication
************************************************** 
* Initialize the library with the numbers of the interface pins
* Board Freedom FRDM-KL46Z
* IDE  Mbed On Line Compiler
* LCD  SPI  SN74HC595
* Pin  Board     LCD
*      SPI_MOSI  SER   (white) 
*      SPI_MISO  none  (blue)  
*      SPI_CLK   SRCLK
*      SPI_PCS   RCLK
*      5V        5V  (red)
*      GND       GND (black)
***************************************************/
SPI         spi_lcd(PTD6,PTD7,PTD5,PTD4);   // MOSI, MISO, SCLK, SSEL

/*************************************************
* LCD instantiation 
**************************************************/ 
//TextLCD LCD(PTC5, PTC6, PTC8, PTC9, PTC10, PCT11, TextLCD::LCD20x2); // 4bit bus: rs, e, d4-d7
//TextLCD_I2C lcd(&i2c_lcd, 0x7E, TextLCD::LCD20x4);                   // I2C bus, PCF8574A Arduino Shield, LCD Type
TextLCD_SPI lcd(&spi_lcd, PTD4, TextLCD::LCD16x4, TextLCD::HD44780);   // SPI bus, SN74595 expander, CS pin, LCD Type 

/*
** ===================================================================
**     Variables Globales del Programa
** ===================================================================
*/
uint16_t Rate=Ticker_Rate/2;        // Velocidad de barrido (500us = 0.5ms)
uint16_t counter=250;               // Cuenta inicial de 250us
int16_t  N_Interrupciones;          // Contador de Overrunig
/*
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
|  Definición de Funciones Prototipo y Rutinas de los Vectores de Interrupción
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*/
void setup(void);                   // Rutina de Inicialización para el Hardware
void Ticker_OnInterrupt(void);   // Rutina de Atención para el Ticker
void buzzer_beep(void);             // Pitidos del Buzzer
//void I2C_scanner(void);             // Busca dispositivos conectados al bus I2C
void test_LCD(void);                // Prueba la operación del LCD
void blinking_led(void);            // Rutina de Parpadeo del Led monitor
/*
#===============================================================================
|
|               P R O G R A M A     P R I N C I P A L
|
#=============================================================================== 
*/
int main()
{
                // Inicialización de variables, puertos e interrupciones
terminal.baud(115200);          // Se configura la velocidad de transmisión e inicia la comunicación serial.    
terminal.printf(" System is Wake Up!.\n\r"); 
setup();                        //Inicializa el Hardware Principal

    while (true)                // El Lazo del Programa principal está aquí !!!
    {
        lcd.cls();
        lcd.locate(0,0);                  
        lcd.printf("Bienvenidos Sean");       // El LCD saluda al Mundo
        lcd.printf("    a la \n");              // y a la          
//        lcd.setInvert(on);      
        lcd.printf("Gloriosa ESIME !\n");       // Gloriosa ESIME ! 
//        lcd.setInvert(off);
        lcd.locate(0,4);                  
        lcd.printf("Flashings: %d",N_Interrupciones); // Led Flasings Transcurridos
        wait(0.5); 

//        Blinking_Led();                 // Parapadeo del LED por Software                         
    }
}
/* END main */

/*
................................................................................
:  Rutinas de los Vectores de Interrupción
................................................................................
*/
void Ticker_OnInterrupt()        // Rutina de Atención al Ticker
{
    counter--;                      // Aquí va la Rutina de Servicio !
    if (!counter)
    {
        terminal.printf("Counter Finish! \r\n");
        led_monitor = !led_monitor; // Parapadeo del LED por Interrupción (Toggle the LED)
        N_Interrupciones++;
        counter = Rate;             // Restablece el contador
    }
}
/* END Events */   
/*
________________________________________________________________________________
|
|  Funciones Prototipo
|_______________________________________________________________________________
*/
                // Las Funciones Prototipo van aquí !
void setup()                    // Inicialización del Hardware del Sistema
{
    /* Inicia la comunicación la Terminal */ /* 115200 Bauds, 8 bits, 1 stop, N parity */
  terminal.baud(115200);                 // Se inicia la comunicación serial.    
  terminal.printf(" System is Wake Up!.\n\r"); 

/* Inicialización del Bluetooth */      
  bluetooth.baud(115200);                // Se inicia la comunicación Bluetooth.  
//  bluetooth.scanf("%s", buf);          //Lee un carácter desde el Bluetooth
//  bluetooth.printf("recv: %s", buf);   //Hace eco al Bluetooth
//  terminal.printf("recv: %s\r\n", buf);  //Imprime en la Terminal el caracter recibido
  bluetooth.printf("Bluetooth Starting OK! ... \n\r"); 
  terminal.printf("Bluetooth Starting OK! ... \n\r");       
/* Prueba del Buzzer */    
  terminal.printf("Testing Buzzer... \n\r");   
  buzzer_beep();
  
/* Configufración del Display LCD */    /* Mucho OjO !!! */
  
/* LCD Utilizando el SPI */ 
  spi_lcd.frequency(1000000);           // Frecuencia de operación para el SPI
  spi_lcd.format(8,0);                  // Modo de Operación para el SPI
 
/* LCD Utilizando el I2C */ 
//  I2C_scanner();                // Busca Dispositivos I2C conectados al Bus 
/*  i2c_lcd.frequency(100000);    // Frecuencia de operación para el I2C (100KHz)
  i2c_lcd.start();              // Inicio de operación para el I2C
//  lcd.setBacklight(LightOn );   // Enciende la luz de fondo del LCD
  terminal.printf("I2C Initialized...\n\r");
*/ 
/* Prueba de operación del LCD */
  terminal.printf("LCD Test, please wait...\n\r");  
  test_LCD();                   // Rutina de pueba del LCD
  terminal.printf("LCD Initialized Succesfuly...\n\r");   
/* Arranque de la interrupción por el Ticker */    
  terminal.printf("Ticker Starting Now...\n\r"); 
  TimerInt.attach_us(&Ticker_OnInterrupt, Ticker_Rate);   // Le asigna el periodo de barrido de 1ms (Ticker_Rate=1000)
}  

void test_LCD()
{
  lcd.cls();
  lcd.printf("Hello World!\n");     // El LCD saluda al Mundo!
  lcd.setInvert(on);
  lcd.printf("Hola Mundo!\n");      // El LCD saluda al Mundo!
  lcd.setInvert(off);
  lcd.printf("Ciao Mondo!\n");      // El LCD saluda al Mundo!
  lcd.setInvert(on);
  lcd.printf("Bonjour le Monde");   // El LCD saluda al Mundo!
  wait(10); 
  lcd.cls();                            // Limpia el Display LCD
  lcd.setBacklight(TextLCD::LightOff);  // Apaga la Iluminación de Fondo
  Timer Elpased_Time;                   //Inicializa el Tiempo a Transcurrir
  Elpased_Time.start();
  for (int row=0; row<lcd.rows(); row++)// Prueba toda la Pantalla
  {
   uint16_t col=0; 
    lcd.putc('0' + row);                
    for (col=1; col<lcd.columns()-1; col++) 
    {    
      lcd.putc('*');                    // Llena lalinea con el carácter "*"
    }
    lcd.putc('+');                      // Al final pone el carácter "+"
  }  
  Elpased_Time.start();                 // Calcula el tiempo transcurrido
  terminal.printf("All my hard work took %f sec\r\n", Elpased_Time.read());  
  wait(1);  
  terminal.printf("LCD Display and TextLCD Enhanced Test Completed.\n\r"); 
  lcd.cls();  
  lcd.setCursor(TextLCD::CurOff_BlkOn); //
// Set and show user defined characters. A maximum of 8 UDCs are supported by the HD44780.
// They are defined by a 5x7 bitpattern. 
  lcd.setUDC(0, (char *) udc_0);        // Muestra el cursor |>
  lcd.putc(0);   
  terminal.printf("LCD Starting OK! ... \n\r");       
}

void buzzer_beep()
{
    buzzer = Buzz_On;
    wait_ms(750);
    buzzer = Buzz_Off;
    wait_ms(125);
    buzzer = Buzz_On;
    wait_ms(250);
    buzzer = Buzz_Off;   
    wait_ms(125);
    buzzer = Buzz_On;
    wait_ms(500);
    buzzer = Buzz_Off;
}  

void blinking_led()             // Software Blinking routine for LED 
{
        // The on-board LED is connected, via a resistor, to +3.3V (not to GND). 
        // So to turn the LED on or off we have to set it to 0 or 1 respectively
        led_monitor = 0;        // turn the LED on
        wait_ms(200);           // 200 millisecond
        led_monitor = 1;        // turn the LED off
        wait_ms(1000);          // 1000 millisecond
}
/*
void I2C_scanner()
{     
  terminal.printf ("I2C scanner. Scanning ...");
  uint8_t count = 0;
  char     test[] = { 0b00000000, 0b00000000, // RS=0, EN=1,0, LED+=1, NC, DB4=DB5=DB6=DB7=0 en datos
                      0b01101100, 0b00101100, // RS=0, EN=1,0, LED+=1, NC, DB4=DB5=1 en datos,
                      0b01101100, 0b00101100, // RS=0, EN=1,0, LED+=1, NC, DB4=DB5=1 en datos,
                      0b01101100, 0b00101100, // RS=0, EN=1,0, LED+=1, NC, DB4=DB5=1 en datos, 
                      0b01100100, 0b00100100, // RS=0, EN=1,0, LED+=1, NC, DB5=1 en datos,
                      0b01100100, 0b00100100, // RS=0, EN=1,0, LED+=1, NC, DB5=1 en datos, 
                      0b01100110, 0b00100001, // RS=0, EN=1,0, LED+=1, NC, DB7=N=1 2 líneas, DB6=F=0 5x7puntos,
                      0b01100000, 0b00100000, // => Display ON/OFF Control.
                      0b01100001, 0b00100001, // RS=0, EN=1,0, LED+=1, NC, DB7=1 (Display off, cursor off, blink off)
                      0b01100000, 0b00100000, // => Display Clear.
                      0b01101000, 0b00101000};// RS=0, EN=1,0, LED+=1, NC, DB4=1 en datos, (Cursor Home};  // Patrón de Prueba

//  char     test[2] = {0x55,0xAA};// Patrón de Prueba    
  i2c_lcd.frequency(100000);   // Frecuencia de operación para el I2C (100KHz)
  i2c_lcd.start();              // Inicio de operación para el I2C
  for (int i = 8; i < 128; i++)
  {
    uint8_t acknoledge = i2c_lcd.write (i,test,22,1);    //(dirección, ap_datos, N°_datos, repetición) 
    if (acknoledge == 0)
      {
      terminal.printf ("\n\rFound address: ");
      terminal.printf ("%u DEC",i);         // Valor de la dirección en Decimal
      terminal.printf (" (0x%x HEX)\n\r",i);   // Valor de la dirección en Hexadecimal   
//      terminal.printf (" (0x%hd HEX)\n\r",i);  // Valor de la dirección en Hexadecimal
      count++;

      wait (1);  // maybe unneeded?
      } // end of good response
      led_monitor = !led_monitor;   // Parapadeo del LED       
  } // end of for loop
  led_monitor = 1;                  // Apaga el LED
  i2c_lcd.stop();                  // Fin de operación para el I2C    
  terminal.printf ("\n\rDone.\n\r");
  terminal.printf ("Found %d Device(s)\n\r",count);
}  // end of setup                 
*/

/* END Program */

/* END Mbed */