Do loop not working

In the following code, a number should always be printed out as long as "4" is not selected.

This is not the case. All that ever happens is that only one number is ever displayed i.e the do loop never appears to repeatitself :frowning:

#include <Keypad.h>

void setup(){
Serial.begin(9600);
Serial.println(readKey());
}

void loop(){
 
}

char readKey() {
  const byte ROWS = 4; //four rows
  const byte COLS = 3; //four columns
  //define the cymbols on the buttons of the keypads
  char hexaKeys[ROWS][COLS] = {
  {'1','2','3'},
  {'4','5','6'},
  {'7','8','9'},
  {'*','0','#'}
  };
  byte rowPins[ROWS] = {7,6, 8, 5}; //connect to the row pinouts of the keypad
  byte colPins[COLS] = {4, 3, 2}; //connect to the column pinouts of the keypad
  //initialize an instance of class NewKeypad
  Keypad customKeypad = Keypad( makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);

  char customKey;
 
  do {
    customKey = customKeypad.getKey();
    if (customKey){
      return customKey;
      Serial.println(customKey);
    }
  } while (customKey!="4");
}
 if (customKey){
      return customKey;
      Serial.println(customKey);
    }

tell us what you understand about "return"

while (customKey!="4");and what you understand about the differences between chars and strings

... and what is the MINIMUM number of times that the code in a do ... while will be executed?

HINT: The correct answer is not zero.

NOTE: In programming, zero is often desirable. That is why do ... while is used so infrequently and why while (...) ... is used more often.

vaj4088:
NOTE: In programming, zero is often desirable. That is why do ... while is used so infrequently and why while (...) ... is used more often.

But in this case, do...while is the correct form.

Hi,

  do {
    customKey = customKeypad.getKey();
    if (customKey){
      return customKey;                 <<<Remove this line.
      Serial.println(customKey);
    }
  } while (customKey!="4");
}

Jacques

  } while (customKey!="4"); .. and change this one

Thanks all, can't believe I put the return there; it should have been outside of the loop. I was just wanting to test something and so the purpose of the code will make no sense :slight_smile:

abasel, thank you for explaining that but the return was just one of multiple issues.