Problem reading a char or string

Hello guys,

For my project I am using a keypad to enter a reference.
I would like to save the complete reference as a parameter but I don't know how to do it

Here is what I did for the moment

void refPDU ()
{
  //reference as XXX-XXX-XXX
  delay(1000);
  int i = 0;
  int j = 0;
  int n = 0;
  Serial.println("Serial number of PDU: ");
  while (i != 3 && n < 11)
  {
    while (j != 3)
    {
      char customKey = customKeypad.waitForKey();
      if(customKey)
      {
        Serial.print(customKey);
        referencePDU[n] = Serial.read();   
        n += 1;                                               
      }
      j += 1;  
    }
    Serial.print("-");
    j = 0;
    i += 1;
  }
  Serial.println("");
  Serial.println(referencePDU);
  return;    
}

And here is what I have on my serial console:

Serial number of PDU:
123-456-789-
⸮⸮⸮⸮⸮⸮⸮⸮⸮

Why do I have this for my referencePDU ?

If you have any advice, feel free to tell me ^^

Thanks in advance

Thomas

      char customKey = customKeypad.waitForKey();
      if (customKey)
      {
        Serial.print(customKey);
        referencePDU[n] = Serial.read();
        n += 1;
      }

So, if there is something other than zero read from the keypad, read a character from Serial.

Is that what you mean to do ?

You pass a char array to a function that expects a string. Of course, weird things are going to happen.

You CAN make the char array a string, by adding the NULL terminator.

     char customKey = customKeypad.waitForKey();
      if(customKey)
      {
        Serial.print(customKey);
        referencePDU[n] = Serial.read();   
        n += 1;
        referencePDU[n] = '\0'; // NULL terminate the array

Of course, it makes no sense to print customKey and then assign referencePDU something you read from the serial port, without checking that there is anything to read.

Looks to me like you want:

       referencePDU[n] = customKey;

Ty for your replies

My goal is to enter my reference and when I reach 11 caracters ( xxx-xxx-xxx ), it saves my reference in referencePDU parameters so that I can use this parameter later

Using :

Serial.print(customKey);
referencePDU[n] = customKey;
n += 1;

I have :

Serial number of PDU:
192-538-765-
192538765

Getting closer ^^ But how could I have the - between each group of 3 numbers ?

Thanks

Thomas

But how could I have the - between each group of 3 numbers ?

By printing 3 characters, then a dash, then three more...

If you need the referencePDU array to contain the dashes (I doubt that you do), you could add a dash after adding customKey, when n is 2, 5, and 8.

how could I have the - between each group of 3 numbers ?

You know how many characters have been added to the array so put a '-' in at the appropriate time. Don't forget to make the array large enough.

Is the array going to be used as s string or just an array of chars ?