arduino 上的键盘

Keypad on arduino

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

这是我的代码:

#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

问题出在哪里?

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

strcmp() returns 0 如果 c 字符串相同。

这应该有效:

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

示范[​​=28=]

把这个放在你的 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