2016-03-10 91 views
0

我有這個代碼,我嘗試處理輸入密碼「78486」來關閉傳感器功能!Arduino代碼問題..?

問題是,當我用鍵盤輸入的代碼..它不工作..

所以,請幫我做它的工作。我認爲這個問題是如果條件!

#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"); 
     } 
    }  
} 

回答

0

我個人倒在讀階段結束檢查值:這種方式是很難猜測是錯誤的字符(如果它退出時,每次一個字符是錯誤的,你將不得不做的最多50次嘗試;如果最後退出,則最多需要執行100000次)。

此外,您需要一種重置位置並開始新密碼的方式:因爲您沒有使用#字符我使用它。

最後,我絕對更喜歡在這種情況下開關案例。所以

// 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返回時沒有按鍵。只需驗證它

+0

謝謝你的回答,我會檢查它,並用我的反饋重播=) –

+0

Thanx = D 它w like像魅力<3 –

+0

很高興它的工作:)然後標記此答案爲接受:) – frarugi87