【问题标题】:Keypad on arduinoarduino上的键盘
【发布时间】:2017-03-15 08:26:35
【问题描述】:

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

这是我的代码:

#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

问题出在哪里?

【问题讨论】:

    标签: arduino keypad


    【解决方案1】:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-17
      相关资源
      最近更新 更多