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;
}
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.

  • 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. – jose can u c Jan 12 '17 at 16:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.