// Programa: primo4_serial.ino
// Descripción: Lee un valor del puerto serie (0-9999) y muestra
// en el lcd si el valor es PRIMO y/o CAPICUA
// Autor: D.Llorente (junio-2024)
//-------------------------------------------------------
#include <LiquidCrystal_PCF8574.h>
LiquidCrystal_PCF8574 lcd(0x27); // dir. del LCD-I2C

#define POT 34 // POT en gpio 34
#define P1 27 
#define P2 16
#define P3 17

// Variables y funnciones
bool pantalla=0;
bool comenzar = 0;   
bool esCapicua(int valor);
bool esPrimo(int valor);
void pantalla0(void);
void pantalla1(void);

void setup()
{
Serial.begin(9600);
// Config. E/S
pinMode(P1,INPUT_PULLUP);
pinMode(P2,INPUT_PULLUP);
pinMode(P3,INPUT_PULLUP);
//Config. LCD
lcd.begin(16, 2);      // Declaración del tipo de lcd
lcd.setBacklight(255); // Retroiluminación = ON
// Bucle de inicio P1(cambia pantalla) P2(inicia el programa)
pantalla0();
while (comenzar==0){
if(digitalRead(P1)==LOW){
  delay(400);
  pantalla = !pantalla;
  if(pantalla==0) pantalla0();
  else pantalla1();
}
if(digitalRead(P2)==LOW) comenzar=1; 
}
//---------------------------------
lcd.clear();
lcd.print("Valor: 0");  // Enviar msg a línea1 del lcd
lcd.setCursor(0,1);
lcd.print("Cap:NO - Pr:NO");  // Enviar msg a línea1 del lcd
}

void loop() {
if (Serial.available()){
  int valor=Serial.parseInt(); // Leer valor del puerto Serie
  lcd.setCursor(7,0);
  lcd.print(valor);
  lcd.print("   ");
  lcd.setCursor(4,1);
  if (esCapicua(valor)) lcd.print("Si");
  else lcd.print("No");
  lcd.setCursor(12,1);
  if (esPrimo(valor)) lcd.print("Si");
  else lcd.print("No");
 }
}//end looP

// Mis funciones
bool esCapicua(int valor){
 int mil = valor / 1000;
 int resto2 = valor-(mil*1000);

 int cen = resto2/100;           
 int resto = resto2-(cen*100);  // 
 int dec = resto/10;  // Cociente 46/10 = 4
 int uni = resto%10;  // Resto de 46/10 = 6
  
// Si valor es de una cifra = es capicua SIEMPRE
 if(valor<10) return 1;
 else if (valor>=10 && valor<=99) {   // dos cifras
    if(dec==uni) return 1;
    else return 0;
 }
 else if (valor>=100 && valor<=999) {   // trescifras
   if(cen == uni) return 1;
    else return 0;
 }
 else {
   if(cen == dec  && mil == uni) return 1;
    else return 0;
 }
}

bool esPrimo(int valor){
  return 1;
}

void pantalla0(void){
lcd.clear();                   // Borrar pantalla
lcd.print("Prog. Cap/Primo");  // línea1 del lcd
lcd.setCursor(0,1);            // Cambio linea
lcd.print("    v1.0 ");        // línea2 del lcd
}
void pantalla1(void){
lcd.clear();                   // Borrar pantalla
lcd.print("Aut: D.Llorente");  // línea1 del lcd
lcd.setCursor(0,1);            // Cambio linea
lcd.print("  junio-2024   ");  // línea2 del lcd
}