Es geht mit Tastenfeldern weiter und der Programmcode wird etwas angepasst…
Programmierung 2 mit angepasstem Code:
#include "Keypad.h"
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] = {5,6,7,8};
byte colPins[COLS] = {2,3,4};
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
char PIN[6]={'1','2','3','4','5','6'}; // Die Geheimzahl
char attempt[6]={0,0,0,0,0,0};
int z=0;
void setup()
{
Serial.begin(9600);
}
void correctPIN() // wird bei korrekter PIN ausgeführt
{
Serial.println("richtige PIN eingegeben");
}
void incorrectPIN()
{
Serial.println("falsche PIN eingegeben");
}
void checkPIN()
{
int correct=0;
int i;
for(i=0; i<6; i++)
{
if(attempt[i]==PIN[i])
{
correct++;
}
}
if (correct==6)
{correctPIN();
}
else
{
incorrectPIN();
}
for (int zz=0; zz<6; zz++) // entfernt den vorherigen Eingabeversuch
{
attempt[zz]=0;
}
}
void readKeypad()
{
char key = keypad.getKey();
if (key != NO_KEY)
{
switch(key)
{
case '*':
z=0;
break;
case '#':
delay(100); // zum Entprellen
checkPIN();
break;
default:
attempt[z]=key;
z++;
}
}
}
void loop()
{
readKeypad();
}
Wie geht es weiter?
Im nächsten Artikel wird das Tastenfeld mit einer LED-Schaltung verbunden. Statt Infomeldungen im seriellen Monitor auszugeben, soll bei richtiger PIN eine grüne LED leuchten und bei falscher PIN eine rote LED.