0

I have written a code that remaps the 16-Key touch keypad. When 2 key is pressed, it writes weird characters in the serial monitor even on my 16x2 LCD

Weird Char

But the other keys work fine.
Here's the code:

#define SCL_PIN 11
#define SDO_PIN 12
struct keymap {
 int kCode;
 String kValue;
 };
keymap keys[] = {
 {1, "1"},
 {2, "2"},
 {3, "3"},
 {5, "4"},
 {6, "5"},
 {7, "6"},
 {9, "7"},
 {10,"8"},
 {11,"9"},
 {14,"0"},
 {13,"CLEAR"},
 {15,"ENTER"}
 };
void setup()
{
 Serial.begin(9600);
 pinMode(SCL_PIN, OUTPUT);
 pinMode(SDO_PIN, INPUT);
}
void loop() {
 int Key = Read_Keypad();
 if (Key != 0) {
 for (int x = 0; x < 16; x++) {
 if (Key == keys[x].kCode) {
 Serial.println(keys[x].kValue);
 }
 }
 delay(300);
 }
}
byte Read_Keypad(void)
{
 byte Count;
 byte Key_State = 0;
 for (Count = 1; Count <= 16; Count++)
 {
 digitalWrite(SCL_PIN, LOW);
 if (!digitalRead(SDO_PIN))
 Key_State = Count;
 digitalWrite(SCL_PIN, HIGH);
 }
 return Key_State;
}
asked Jan 12, 2017 at 12:41

1 Answer 1

1

It seems by changing 16 to 12 on

for (int x = 0; x < 12; x++) {
 if (Key == keys[x].kCode) {
 lcd.print(keys[x].kValue);
 }
}

fixed it.

answered Jan 12, 2017 at 13:09
1
  • 2
    You might want to explicitly explain why this fix worked, in case it might help others. Your keymap array had only 12 elements, and your loop was examining undefined memory beyond the bounds of the keymap array when it was accessing elements 12-15. I think that the trigger on kepress of "2" was coincidence due to the undefined nature of the memory values you were checking every time through the loop. Commented Jan 12, 2017 at 16:11

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.