Checking acces users

Hi every one.
I have a problem with my code. When checking the PIN code entered by a user the program don´t recognized it even the PIN is ok. The sketch have no compilation problems so i don´t understand where the issue is. My code is this. (Please excuse the gramatical mistakes, my English is no perfect)
Thanks!

void checkPIN()
{
  int correct=0;
  for (int q=0; q<=3; q++)
  {   
    if (attempt[q]==usuario1[q]||attempt[q]==usuario2[q]||attempt[q]==usuario3[q]||attempt[q]==usuario4[q]||attempt[q]==usuario5[q])
   {
     attempt2[q]=attempt[q];
     correct++;   
   }
  }
  if ((correct==3) && ((attempt2[4]==usuario1[4]) || (attempt2[4]==usuario2[4]) || (attempt2[4]==usuario3[4]) || (attempt2[4]==usuario4[4]) || (attempt2[4]==usuario5[4])))
   {   
    Serial.println("PIN correcto");
    digitalWrite(11, HIGH); // activa un contacto
    for (int zz=0; zz<=4; zz++) // borrar el último código introducido
    {
    attempt[zz]=0;
    }
    switchModule();
    setup2();
    loop2();    
   }   
    else
      {
        Serial.println("PIN erroneo");
        digitalWrite(12, HIGH); // activa un contacto
        delay(1000);   
        digitalWrite(12, LOW);
        for (int zz=0; zz<=4; zz++) // borrar el último código introducido
         {
         attempt[zz]=0;
         }
        setup();
       }
 }

Without knowing how attempt, usuario1, usuario2, usuario3, usuario4, or usuario5 are defined, or what values they contain, there is no way we can help you.

There are almost certainly better ways of doing what you are trying to do. We’d need to know more about the context though.

    switchModule();
    setup2();
    loop2();

Where are these functions? setup2 and loop2 imply absolutely nothing about what the functions do. Better names are in order before you post more code.

Ok excuse me, i dont have too much experience in this. Here is my code:

#include <Keypad.h>

//VARIABLES ENVIO DATOS
int led = 13;
int onModulePin = 2;        // Definimos el Pin 2 para activar o desactivar el modulo 3G (sin pulsar el botón)
int timesToSend = 1;        // Numero de sms a enviar
int count = 0;
char phone_number[]="*********";     // ********* numero que recibirá el sms


//VARIABLES TECLADO
const byte ROWS = 4; //4 filas
const byte COLS = 3; //3 columnas
char keys[ROWS][COLS] = {
  {'1','2','3'},
  {'4','5','6'},
  {'7','8','9'},
  {'*','0','#'}};
byte rowPins[ROWS] = {7, 6, 5, 4}; // reserva de memoria en bytes, conectar a los pines de filas del teclado
byte colPins[COLS] = {10, 9, 8}; // reserva de memoria en bytes, conectar a los pines de columnas del teclado
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
char serialnumber[10]= {'6','1','0','3','7','2','2'};
char marcamaquina[10]= {'B','T'};
char modelomaquina[10]= {'L','W','E','2','0','0'};
char usuario1[4]={'1','2','3','#'};
char usuario2[4]={'4','5','6','#'};
char usuario3[4]={'7','8','9','#'};
char usuario4[4]={'0','9','8','#'};
char usuario5[4]={'7','6','5','#'};
char attempt[4]={0,0,0,0};; // usado para comparar
int z=0;
int sal1 = 11; // salida led verde pin 11
int sal2 = 12; // salida led rojo pin 12
char attempt2[4]={0,0,0,0};



//PROGRAMA
void setup()
{
  pinMode(sal1, OUTPUT);
  pinMode(sal2, OUTPUT);
  Serial.begin(115200); //Configura la velocidad del puerto serie
  keypad.setHoldTime(150); // Tiempo de pulsado de boton. Default is 1000mS
  keypad.setDebounceTime(30); // Tiempo de rebote de bootn. Default is 50mS
  Serial.println(" Introduzca PIN: ");
}
void leds()
{ 
  if (sal1 == LOW) 
    sal2 = HIGH;
  else 
  { 
    sal2 = LOW;
  }
}
void checkPIN()
{
  int correct=0;
  for (int q=0; q<=3; q++)
  {   
    if (attempt[q]==usuario1[q]||attempt[q]==usuario2[q]||attempt[q]==usuario3[q]||attempt[q]==usuario4[q]||attempt[q]==usuario5[q])
   {
     attempt2[q]=attempt[q];
     correct++;   
   }
  }
  if ((correct==3) && ((attempt2[4]==usuario1[4]) || (attempt2[4]==usuario2[4]) || (attempt2[4]==usuario3[4]) || (attempt2[4]==usuario4[4]) || (attempt2[4]==usuario5[4])))
   {   
    Serial.println("PIN correcto");
    digitalWrite(11, HIGH); // activa un contacto
    for (int zz=0; zz<=4; zz++) // borrar el último código introducido
    {
    attempt[zz]=0;
    }
    switchModule();
    setup2();
    loop2();    
   }   
    else
      {
        Serial.println("PIN erroneo");
        digitalWrite(12, HIGH); // activa un contacto
        delay(1000);   
        digitalWrite(12, LOW);
        for (int zz=0; zz<=4; zz++) // borrar el último código introducido
         {
         attempt[zz]=0;
         }
        setup();
       }
 }
void readKeypad()
{
  char key = keypad.getKey();
  if (key != NO_KEY)
  {
   switch(key)
  {
 case '*':
  z=0; 
  digitalWrite(12, LOW);
  digitalWrite(11, LOW);
  setup();
  break;
 case '#':
  delay(50);
  Serial.println(" ");
  checkPIN();
  break;
  default:
  attempt[z]=key;
  z++;
  }
   Serial.print("*");
   leds();
  }
}
void loop()
{
  readKeypad();
}
void switchModule(){
    digitalWrite(onModulePin,HIGH);     //Para activar el módulo 3G, debemos enviarle un pulso de 2sg por el pin número 2 (lo mismo para apagar)
    Serial.println("Activando modulo 3G...");
    delay(2000);
    digitalWrite(onModulePin,LOW);
    Serial.println("Modulo 3G activado...");
}
void setup2(){
    Serial.begin(115200);               //Configuramos puerto UART
    delay(2000);
    pinMode(led, OUTPUT);
    pinMode(onModulePin, OUTPUT);
    for (int i=0;i< 5;i++){
        delay(5000);
    } 
    Serial.println("AT+CMGF=1");        //Seleccionamos el formato del sms (0=PDU 1=texto)
    delay(100);
}

void loop2(){
  
    while (count < timesToSend){
        delay(1500);                
        Serial.print("AT+CMGS=\"");   // send the SMS number
        Serial.print(phone_number);
        
        Serial.println("\"");       
        delay(1500); 
             
        Serial.print("Maquina conectada: ");
        Serial.println (marcamaquina);        
        delay(1500); 
                 
        Serial.print("Modelo: ");
        Serial.println (modelomaquina);        
        delay(1500); 
                   
        Serial.print("Numero de serie: ");
        Serial.println (serialnumber);
        delay(1500); 
           
        Serial.print("Usuario: ");
        Serial.println (attempt2);
        
        delay(500);
        Serial.write(0x1A);       //sends ++
        Serial.write(0x0D);
        Serial.write(0x0A);
        delay(5000);
        count++;
    }

}
char usuario1[4]={'1','2','3','#'};

would involve a lot less typing as:

char usuario1[]="123#";

AND would be properly sized then, and NULL terminated, to be used in strcmp().

All of your arrays for holding keypad input should be one element larger, to hold a trailing NULL.

  default:
  attempt[z]=key;
  z++;
  attempt[z] = '\0'; // Add this to keep attempt NULL terminated (after making attempt larger)
  for (int q=0; q<=3; q++)
  {   
    if (attempt[q]==usuario1[q]||attempt[q]==usuario2[q]||attempt[q]==usuario3[q]||attempt[q]==usuario4[q]||attempt[q]==usuario5[q])
   {
     attempt2[q]=attempt[q];
     correct++;   
   }
  }

Can then become:

if(strcmp(attempt, usuario1) == 0)
  correct = 1;
else if(strcmp(attempt, usuario2) == 0)
  correct = 2;
else if(strcmp(attempt, usuario3) == 0)
  correct = 3;
else if(strcmp(attempt, usuario4) == 0)
  correct = 4;
else if(strcmp(attempt, usuario5) == 0)
  correct = 5;

which, I think, you’ll have to admit is a lot easier to understand. And, you can know which value attempt matched, if that makes any difference.

I don’t understand what this is doing:

  if ((correct==3) && ((attempt2[4]==usuario1[4]) || (attempt2[4]==usuario2[4]) || (attempt2[4]==usuario3[4]) || (attempt2[4]==usuario4[4]) || (attempt2[4]==usuario5[4])))

The arrays are all 4 elements long, so the indices are 0 to 3. These references are all beyond the bounds of the arrays.

    for (int zz=0; zz<=4; zz++) // borrar el último código introducido
    {
    attempt[zz]=0;
    }

Here, again, you are writing beyond the ends of the arrays. Since we are now using NULL terminated array, putting a single NULL in the array is sufficient.

attempt[0] = '\0';

Of course, resetting z to 0 at some point would be a good idea, too.

As would using Tools + Auto Format.

The value that matches makes a lot of sense cause i want to send via sms the user that turn on the machine. So i have my check pin function like this now:

void checkPIN()
{
  int correct;
  if(strcmp(attempt, usuario1) == 0)
    correct = 1;
  else if(strcmp(attempt, usuario2) == 0)
    correct = 2;
  else if(strcmp(attempt, usuario3) == 0)
    correct = 3;
  else if(strcmp(attempt, usuario4) == 0)
    correct = 4;
  else if(strcmp(attempt, usuario5) == 0)
    correct = 5;

  if ( correct==1 || correct==2 || correct==3 || correct==4 || correct==5 )
  {   
    Serial.println("PIN OK");

I change also the PIN codes:

char usuario1[5]="111#";
char usuario2[5]="222#";
char usuario3[5]="333#";
char usuario4[5]="444#";
char usuario5[5]="555#";
char attempt[5]="0000";
char attempt2[5]="0000";

Is this ok?? again there is no compile error. But if I enter the code for user 1 (123) it says that the PIN is wrong... A where shall I put this?

attempt[0] = '\0';

Thanks a lot for your time PaulS

The code for user 1 I entered is 111 (the 123 is the old one but it doesnt work any way)

char usuario1[5]="111#";
char usuario2[5]="222#";
char usuario3[5]="333#";
char usuario4[5]="444#";
char usuario5[5]="555#";
char attempt[5]="0000";
char attempt2[5]="0000";

The compiler can count. There is no need to tell it how big the array needs to be.

  int correct;

should be:

  int correct = 0;
  if ( correct==1 || correct==2 || correct==3 || correct==4 || correct==5 )

can be a lot shorter:

  if(correct != 0)

You know how to use Serial.print(), obviously. So, where is the debug output? What IS in attempt[] when the function is called?

Add:

Serial.print("attempt: [");
Serial.print(attempt);
Serial.print("]");

at the top of the function.

You need to post your code, again, so that we can see that you made all the required changes.

Here is the code with you corrections:

#include <Keypad.h>

//VARIABLES ENVIO DATOS
int led = 13;
int onModulePin = 2;        // Definimos el Pin 2 para activar o desactivar el modulo 3G (sin pulsar el botón)
int timesToSend = 1;        // Numero de sms a enviar
int count = 0;
char phone_number[]="*********";     // ********* numero que recibirá el sms


//VARIABLES TECLADO
const byte ROWS = 4; //4 filas
const byte COLS = 3; //3 columnas
char keys[ROWS][COLS] = {
  {
    '1','2','3'  }
  ,
  {
    '4','5','6'  }
  ,
  {
    '7','8','9'  }
  ,
  {
    '*','0','#'  }
};
byte rowPins[ROWS] = {
  7, 6, 5, 4}; // reserva de memoria en bytes, conectar a los pines de filas del teclado
byte colPins[COLS] = {
  10, 9, 8}; // reserva de memoria en bytes, conectar a los pines de columnas del teclado
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
char serialnumber[10]="6103722";
char usuario1[]="111#";
char usuario2[]="222#";
char usuario3[]="333#";
char usuario4[]="444#";
char usuario5[]="555#";
char attempt[]="0000";   // usado para comparar
int z=0;
int sal1 = 11; // salida led verde pin 11
int sal2 = 12; // salida led rojo pin 12
char attempt2[5]="0000";



//PROGRAMA
void setup()
{
  pinMode(sal1, OUTPUT);
  pinMode(sal2, OUTPUT);
  Serial.begin(115200); //Configura la velocidad del puerto serie
  keypad.setHoldTime(150); // Tiempo de pulsado de boton. Default is 1000mS
  keypad.setDebounceTime(30); // Tiempo de rebote de bootn. Default is 50mS
  Serial.println(" Introduzca PIN: ");
}
void leds()
{ 
  if (sal1 == LOW) 
    sal2 = HIGH;
  else 
  { 
    sal2 = LOW;
  }
}
void checkPIN()
{
  Serial.print("attempt: [");
  Serial.print(attempt);
  Serial.print("]");
  int correct = 0;
  if(strcmp(attempt, usuario1) == 0)
    correct = 1;
  else if(strcmp(attempt, usuario2) == 0)
    correct = 2;
  else if(strcmp(attempt, usuario3) == 0)
    correct = 3;
  else if(strcmp(attempt, usuario4) == 0)
    correct = 4;
  else if(strcmp(attempt, usuario5) == 0)
    correct = 5;

  if ( correct=!0)
  {   
    Serial.println("PIN OK");
    digitalWrite(11, HIGH); // activa un contacto
    for (int zz=0; zz<=4; zz++) // borrar el último código introducido
    {
      attempt[zz]=0;
    }
    switchModule();
    setup2();
    loop2();    
  }   
  else
  {
    Serial.println("PIN erroneo");
    digitalWrite(12, HIGH); // activa un contacto
    delay(1000);   
    digitalWrite(12, LOW);
    for (int zz=0; zz<=4; zz++) // borrar el último código introducido
    {
      attempt[zz]=0;
    }
    setup();
  }
}
void readKeypad()
{
  char key = keypad.getKey();
  if (key != NO_KEY)
  {
    switch(key)
    {
    case '*':
      z=0; 
      digitalWrite(12, LOW);
      digitalWrite(11, LOW);
      setup();
      break;
    case '#':
      delay(50);
      Serial.println(" ");
      checkPIN();
      break;
    default:
      attempt[z]=key;
      z++;
      attempt[z] = '\0'; // Add this to keep attempt NULL terminated (after making attempt larger)

    }
    Serial.print("*");
    leds();
  }
}
void loop()
{
  readKeypad();
}
void switchModule(){
  digitalWrite(onModulePin,HIGH);     //Para activar el módulo 3G, debemos enviarle un pulso de 2sg por el pin número 2 (lo mismo para apagar)
  Serial.println("Activando modulo 3G...");
  delay(2000);
  digitalWrite(onModulePin,LOW);
  Serial.println("Modulo 3G activado...");
}
void setup2(){
  Serial.begin(115200);               //Configuramos puerto UART
  delay(2000);
  pinMode(led, OUTPUT);
  pinMode(onModulePin, OUTPUT);
  for (int i=0;i< 5;i++){
    delay(5000);
  } 
  Serial.println("AT+CMGF=1");        //Seleccionamos el formato del sms (0=PDU 1=texto)
  delay(100);
}
void loop2(){

  while (count < timesToSend){
    delay(1500);                
    Serial.print("AT+CMGS=\"");   // send the SMS number
    Serial.print(phone_number);

    Serial.println("\"");       
    delay(1500); 

    Serial.print("Numero de serie: ");
    Serial.println (serialnumber);
    delay(1500); 

    Serial.print("Usuario: ");
    Serial.println (attempt);

    delay(500);
    Serial.write(0x1A);       //sends ++
    Serial.write(0x0D);
    Serial.write(0x0A);
    delay(5000);
    count++;
  }

}
    for (int zz=0; zz<=4; zz++) // borrar el último código introducido
    {
      attempt[zz]=0;
    }

should be:

    attempt[0] = '\0';
    z = 0;

No serial output? It is hard to see the problem without it.

Now the program see every PIN code I enter as correct. I try with "999#" and this is the serial output:

Introduzca PIN:


attempt: [999]PIN correct Activando modulo 3G... Modulo 3G activado...

  Serial.print("attempt: [");
  Serial.print(attempt);
  Serial.print("]");

The last print() should be println().

Add 5 blocks like:

  Serial.print("usuario1: [");
  Serial.print(usuario1);
  Serial.println("]");

for each of the 5 valid values.

Also, add a similar block to print out correct, after the series of if statements.

Ok, the problem is that if I add these blocks like this:

  if (strcmp(attempt, usuario1) == 0)
      Serial.print("usuario1: [");
      Serial.print(usuario1);
      Serial.println("]");
    correct = 1;

I get an error: "else without a previous if" Where I need to ubicate these blocks?? With these blocks the problem of see every PIN as a correct one will be over?

Ok, the problem is that if I add these blocks like this:

They should be after the print of attempt, before the if/else if stuff.

With these blocks the problem of see every PIN as a correct one will be over?

No. They will provide clues needed to figure out the problem.