arduino上的键盘

时间:2017-03-15 08:26:36

标签: arduino keypad

我正在开发一个项目,我正在使用键盘输入密码,我所做的是我正在读取用户键入的键并将其收集到一个数组中以与其进行比较密码。我面临的问题是,当我比较输入的单词和正确的密码时,我总是得到“错误的密码”。

这是我的代码:

#include "Keypad.h"
const byte ROWS = 4; //four rows
const byte COLS = 3; //three columns
char keys[ROWS][COLS] = {
{'1','2','3'},
{'4','5','6'},
{'7','8','9'},
{'*','0','#'}
};
char passwrd[7];
char cst[7]="*1998#";
 byte rowPins[ROWS] = {28, 27, 26, 25}; //connect to the row pinouts of the   keypad
 byte colPins[COLS] = {24, 23, 22}; //connect to the column pinouts of the keypad

 Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);

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

void loop()
{

   int i=0;
 do
 {
     char key = keypad.getKey();
     if (key != NO_KEY)
     {
        passwrd[i]=key;
        i++;
        Serial.println(key);
     }
 }while (i!=6);
 Serial.println(passwrd);
 Serial.println(cst);
 if (passwrd==cst)
 {
     Serial.println("correct passwrd");
 }
 else 
 {
     Serial.println("wrong passwrd");
 }
}

以下是我从串口com获得的内容:

*
1
9
9
8
#
*1998#
*1998#
wrong passwrd

问题出在哪里?

1 个答案:

答案 0 :(得分:0)

==上使用char*将比较指针指向内存的地址,因为c型字符串是指针。您需要使用strcmp()函数。

如果c字符串相同,

strcmp()会返回0

这应该有效:

if (strcmp(passwrd, cst) == 0)
{
    Serial.println("correct passwrd");
}
else 
{
    Serial.println("wrong passwrd");
}

示范

把它放在你的Arduino上以证明这一点:

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
}

char* are_the_same(int val) {
  if(val == 0)
    return "No";
  return "Yes";
}

void loop() {
  // put your main code here, to run repeatedly:
  char* one = "test";
  char two[5];

  // We are copying 'test' into string two. If we don't do this the compiler will optimise and make them point to the same piece of memory and ruin the demonstration.
  int i;
  for (i = 0; i < 5; i++)
    two[i] = one[i];

  Serial.print("one == two, are they the same? ");
  Serial.println(are_the_same(one == two));

  Serial.print("strcmp(one, two) == 0, are they the same? ");
  Serial.println(are_the_same(strcmp(one, two) == 0));
  Serial.println();
  delay(1000);
}

这会给你:

one == two, are they the same? No
strcmp(one, two) == 0, are they the same? Yes