I've written a function that takes in values from a 4X3 numeric keypad and compares them with numbers to decide which compartment to use in a candy vending machine project my son is working on.) It's supposed to return "invalid choice" for anything other than the numbers 1 and 2 from the keypad. It works fine for 1 and 2 and returns invalid for all other numbers except 8,9 or *. If I input any of these numbers, they're interpreted as valid under the strcmp '2' condition. I'm stumped as to why these characters are being equated with '2'. Can anyone enlighten me?
int Candy_choice;
boolean Candy_chosen = false;
int Which_candy;
char Key_pressed;
//define the symbols on the buttons of the keypads
char hexaKeys[ROWS][COLS] = {
{'1','2','3'},
{'4','5','6'},
{'7','8','9'},
{'*','0','#'}
};
byte rowPins[ROWS] = {9, 8, 7, 6}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {5, 4, 3}; //connect to the column pinouts of the keypad
//initialize an instance of class NewKeypad
Keypad My_Keypad = Keypad( makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);
void Get_choice()
{
Serial.print("Enter choice: ");
while(! Candy_chosen) //if the user hasn't chosen which candy they want
{
Key_pressed = My_Keypad.getKey(); //wait for a key to be input
if (Key_pressed) //a key has been pressed
{
Serial.println(Key_pressed);
if(!strcmp('1', Key_pressed)) //if the key is "1"
{
Which_candy = 1; //set the candy choice to 1
Candy_chosen = true; //set the candy chosen flag to true
Serial.print("Enter password: "); prompts user for password
return; //return to main loop
}
else
if(!strcmp('2', Key_pressed))
{
Which_candy = 2;
Candy_chosen = true;
Serial.print("Enter password: ");
return;
}
else
{
Serial.println("invalid choice");
delay(500);
Serial.print("Enter choice: ");
}
}
}
}
I'm most grateful for the responses and will do my best to mend the errors of my ways. I've gotta say though that as a non-programmer dad trying to learn how to write arduino code on the QT to help out his kid, the condescending remarks come off as unfairly harsh.
The above being said, Im anxious to learn to do things the right way... Can I get a quick summary of at least some of the "many,many errors" in my code? (have already changed the name of my keypad instance!)
Points well-taken... it was the "Really, now, is it that difficult..." that I guess I over-reacted to.
BTW, substituting the "if (Key_pressed == n)" got rid of the strange behavior I was experiencing... And I've just discovered switch, which has eliminated all those ugly nested if-then-else statements!
Thanks to everyone for the help... I'm sure I'll be back!