This will read keys until either 6 have been entered each followed by Return, or you enter an F followed by Return
char buffer[7];
char newChar;
int i;
#define NO_KEY '!'
void setup()
{
Serial.begin(9600);
}
void loop()
{
i = 0;
buffer[0] = '\0'; //terminator in first position just in case
while (i < sizeof(buffer) - 1) //leave space for terminator
{
newChar = getChar();
if (newChar == 'F')
{
break;
}
else if (newChar != NO_KEY)
{
buffer[i] = newChar;
i++;
buffer[i] = '\0'; //terminate string in case we finish next time
}
}
Serial.println(buffer);
}
char getChar()
{
if (Serial.available() == 0 )
{
newChar = NO_KEY;
}
else
{
newChar = Serial.read();
}
return newChar;
}
I don't have a keypad so it reads input from the serial port. Set the monitor to no termination if you try it.
NOTE - the routine as written is not bullet proof and is quite happy to accept F as the first character as well as a string longer than 6 characters from the serial input with no Return after each but it illustrates the concept of terminating input on receipt of a particular character.