Arduino代码问题..?

时间:2016-03-10 12:15:55

标签: arduino

我有这个代码,我尝试处理的是输入密码" 78486"关闭传感器功能!

问题是,当我使用键盘输入代码时......它不起作用..

所以请帮助我让它工作..我认为问题出在if条件下!

#include <Keypad.h>

char* secretCode = "78486";
int position = 0;

int minSecsBetweenEmails = 60; // 1 min
int val = 0;
long lastSend = -minSecsBetweenEmails * 1000l;

const byte rows = 4;
const byte cols = 3;
char keys[rows][cols] = {
{'1','2','3'},
{'4','5','6'},
{'7','8','9'},
{'*','0','#'}
};


byte rowPins[rows] = {8, 7, 6, 5};
byte colPins[cols] = {4, 3, 2};


Keypad keypad = Keypad(makeKeymap(keys),
                   rowPins, colPins,
                   rows, cols);

void setup()
{
  pinMode (9, OUTPUT);
 Serial.begin(9600);
}

void loop() 
{
  long now = millis();
  char key = keypad.getKey();

  if  (key == '*')  {
     pinMode (9, INPUT); }

  if(key == '2')      {

    pinMode (9, OUTPUT);
//      if(key == secretCode[position])
//  {
//    position++;
//  }
//    if (position == 5){
//     pinMode (9, OUTPUT);
//    }
 }

  if(digitalRead(9) == HIGH)
  {
   if (now > (lastSend + minSecsBetweenEmails * 1000l))
   {
     Serial.println("MOVEMENT");
     lastSend = now;
    }
    else
      {
     Serial.println("Too soon");
      }
   }      
}

1 个答案:

答案 0 :(得分:0)

就个人而言,我会在阅读阶段结束时检查一下这个值:这样就更难猜出错误的字符是什么(如果每次出现错误时它都退出,你将不得不最多50次尝试;如果它最后退出,你最多需要做100000次。

此外,您需要一种方法来重置位置并启动一个新密码:因为您没有使用我使用的#char。

最后我绝对更喜欢这种情况下的开关盒。所以

// In the main definition part:
uint8_t position = 0;
char readingCode[5];
char secretCode[] = "78486";

// In the loop:
char key = keypad.getKey();

switch (key)
{
    case '*': // shut down sensor
        pinMode (9, INPUT);
        break;
    case '#':
        position = 0;
        break;
    case '0':
    case '1':
    case '2':
    case '3':
    case '4':
    case '5':
    case '6':
    case '7':
    case '8':
    case '9':
        if (position < 5)
        {
            readingCode[position] = key;
            position++;
        }
        if (position >= 5)
        { // check the code
            bool correct = true;
            uint8_t i;
            for (i = 0; i < 5; i++)
                if (readingCode[i] != secretCode[i])
                    correct = false;
            if (correct)
                pinMode (9, OUTPUT);
            position = 0;
        }
        break;
}

还有一件事:我不知道没有按下按键时getKey会返回什么。只需验证它