2016-08-30 256 views
0

我正在嘗試使用Arduino,鍵盤和伺服器來製作組合鎖,但我遇到了障礙。如何使用4x4鍵盤將多位整數輸入到Arduino中?

我找不到在變量中存儲4位數值的方法。因爲keypad.getKey只允許存儲一個數字。

經過在互聯網上瀏覽一段時間後,我在論壇上找到了解決問題的方案,但答案並未包含代碼示例,而且我在互聯網上找不到任何其他內容。

答案表示要麼使用用戶輸入數字的時間限制,要麼輸入一個終止字符(根據他們這將是更好的選擇)。

我想知道更多關於這些終止字符以及如何實現它們,或者如果有人可以提出一個更好的解決方案,也將非常感激。

謝謝你在前進,

+0

這是相同的當AI電話運營商告訴你「_Enter你的電話號碼,然後綁定KEY_」這樣劃分累加器value什麼阻止你這樣做? –

+0

我不知道該怎麼做。你能推薦一個解釋它的網站嗎? –

+0

這很簡單。試想一下:通過繼續調用getkey()來填充你的數字容器。每次你得到一個密鑰,檢查它,它是終止密鑰然後停止,否則再次調用getkey()來獲得一個新的密鑰。 –

回答

1

店4位數的值,這樣做可能是使用尺寸4.數組假設keypad.getKey返回一個int,你可以這樣做的最簡單和原始的方法這個:int input[4] = {0};
您將需要一個遊標變量知道到該陣列的插槽,你需要寫的時候按下一個鍵,所以你可以做一些類型的循環是這樣的:

int input[4] = {0}; 
for (unsigned cursor = 0; cursor < 4; ++cursor) { 
    input[cursor] = keypad.getKey(); 
} 

如果你想使用終止符(可以說你的鍵盤有0-9和AF鍵,我們可以說,F是終止鍵),代碼修改爲類似:

bool checkPassword() { 
    static const int expected[4] = {4,8,6,7}; // our password 
    int input[4] = {0}; 

    // Get the next 4 key presses 
    for (unsigned cursor = 0; cursor < 4; ++cursor) { 
     int key = keypad.getKey(); 

     // if F is pressed too early, then it fails 
     if (key == 15) { 
      return false; 
     } 

     // store the keypress value in our input array 
     input[cursor] = key; 
    } 

    // If the key pressed here isn't F (terminating key), it fails 
    if (keypad.getKey() != 15) 
     return false; 

    // Check if input equals expected 
    for (unsigned i = 0; i < 4; ++i) { 
     // If it doesn't, it fails 
     if (expected[i] != input[i]) { 
      return false; 
     } 
    } 

    // If we manage to get here the password is right :) 
    return true; 
} 

現在你可以使用checkPassword功能,在主功能如下:

int main() { 
    while (true) { 
     if (checkPassword()) 
      //unlock the thing 
    } 
    return 0; 
} 

NB:使用定時器聽起來也是可能的(也可以與終止字符選項組合使用,它們不是唯一的)。這樣做的方法是設置一個計時器到您選擇的時間段,當它結束時,您將光標變量重置爲0.

(我從來沒有在arduino上編程,也不知道它的鍵盤庫,但邏輯在這裏,它取決於你現在)

0

在評論OP說一個單一的號碼是想通過。典型的算法是對於輸入的每個數字,您將累加器乘以10並添加輸入的數字。這假定密鑰條目是ASCII,因此從其中減去'0'得到一個數字0..9而不是'0'..'9'

#define MAXVAL 9999 
int value = 0;         // the number accumulator 
int keyval;          // the key press 
int isnum;          // set if a digit was entered 
do { 
    keyval = getkey();       // input the key 
    isnum = (keyval >= '0' && keyval <= '9'); // is it a digit? 
    if(isnum) {         // if so... 
     value = value * 10 + keyval - '0';  // accumulate the input number 
    } 
} while(isnum && value <= MAXVAL);    // until not a digit 

如果你有一個退格鍵,您只需10

+0

它會工作,如果它不是一個4 * 4鍵盤。順便說一句,它可以被修改爲每個按鍵使用一個字節,而不是訪問所有鍵盤的可能性:) – abidon

+0

@Aureo鍵盤與問題無關。 OP回答了我的評論問題,他的目標是輸入一個範圍爲'0..9999'的單個數字 –