Restricted access to devices via RFID card part 2

After we have defined the hardware in the first part and can use a card firmly to switch the relay, we donate a first operator interface to our ESP in the second part of this series to perform configuration tasks around our card reader. The website is expanded from part to part of this series and equipped with more functions.

The information provided by the Part One.

Ale first we have to adapt our local WLAN to our needs in the following lines in the code:

WiFi.start("Your Wizard","Your Password");

We upload the following code to our NodeMcu:

 

'35; includes <SPI.h>
'35; includes <MFRC522.h>
'35; includes <ESP8266WiFi.h>
/'35; include <WiFiClient.h> 
'35; includes <ESP8266WebServer.h>
'35; includes <ESP8266mDNS.h>
'35; includes <EEPROM.h>

\35; define RST PIN     5     // SPI Reset Pin (D1 output)
\35; define RELAIS PIN  16    // Relais (D0 output) [LOW Active] -Also internal LED near USB port
\35; define SS-U PIN      15    // SPI Slave Select Pin

\35; define RGBLED R    2     // Red (D4 output) 
\35; define RGBLED G    0     // Green (D3 output) Also internal LEDs on the ESP module
\35; define RGBLED B    4     // Blue (D2 output)

\35; define WiFiPwdLen   25   // Maximum WiFi password length
\35; define STATE 20     // Maximum WiFi SSIDlength
\35; define ESPHost 20 // Maximum number of ESPHost characters

\35; define BUILTIN LED 16
\35; define PIN WIRE SDA 4 
\35; define PIN WIRE SCL 5 

MFRC522 mfrc522(SS-U PIN, RST PIN);   // Create MFRC522 instance
MFRC522::MIFARE Key key;
ESP8266WebServer server(80);        // Create Web Server Instance

Strict WiFi   {     char ESPHost[ESPHost];      char APSTA[STATE]; // STATION Name TO Connect, if definded     char WiFiPwd[WiFiPwdLen]; // WiFiPAssword, if definded     char Config[3]; //If Config is Vaild, tag "TK" is required"   };

Strict PICCardEEP   {     char CardVaildUID[4];     char Reserved[4];   };

WiFi MyWiFiConfig;
PICCardEEP MyEEPROMValidCardUID;
bool Result  = false;
bool LearnNewCard = false;

void setup()     {    pinMode(RST PIN,OUTPUT);   digitalWrite(RST PIN,HIGH);   pinMode(RELAIS PIN,OUTPUT);   pinMode(RGBLED R,OUTPUT);   pinMode(RGBLED G,OUTPUT);   pinMode(RGBLED B,OUTPUT);   digitalWrite(RELAIS PIN,HIGH);    Relais inactive   digitalWrite(RGBLED R,LOW);       //Member from AUS   digitalWrite(RGBLED G,LOW);   digitalWrite(RGBLED B,LOW);   Serial.start(9600);               // Initialize serial communication with PC   yield();    Serial.Print(ESP.getChipId());   SPI.start();                      // Initialize SPI Communication   digitalWrite(RST PIN,LOW);   Result  = startWiFiClient();     yield();   EEPROM.start(512);   EEPROM.goat(100,MyEEPROMValidCardUID);   // From address 100 the valid card will be deposited   EEPROM.end();   InitializeHTTPSServer();   digitalWrite(RST PIN,HIGH);   mfrc522.PCD Reset();   mfrc522.PCD Init();               // Initialize MFRC522 Reading module   mfrc522.PCD-u AntennaOn();   yield();    digitalWrite(RGBLED R,HIGH);     //Leather colour purple initialization complete   digitalWrite(RGBLED G,LOW);   digitalWrite(RGBLED B,HIGH);     }

Start Functions Webserver
void handleNotFound()    {    }
void handleRoot()   // Main page   {   String temp ="";        if (server.hasArgh("AuthCard") )  // Reboot System      {     temp = "Please present card to readers.";     server.send ( 200, "text/html", temp );     digitalWrite(RGBLED R,HIGH);     //Led Color Yellow Programming Mode     digitalWrite(RGBLED G,HIGH);     digitalWrite(RGBLED B,LOW);     LearnNewCard = true;     server.client().stop();           }   server.sendHeader("Cache-Control", "no-cache, no-store, must-revalidate");   server.sendHeader("Pragma", "no-cache");   server.sendHeader("Expires", "-1");   server.setContentLength(CONTENT_LENGTH_UNKNOWN);   // HTML Content   server.send ( 200, "text/html", temp );   // Speichersparen - Schon mal dem Cleint senden   temp = "";   temp += "<! DOCTYPE HTML><html lang='de'><head><meta charset='UTF-8'><meta name= viewport content='width=device-width, initial-scale=1.0,'>";   server.sendContent(temp);   temp = "";   temp += "<style type='text/css'><!-- DIV.container { min-height: 10em; display: table-cell; vertical-align: middle }.button {height:35px; width:90px; font-size:16px}";   server.sendContent(temp);   temp = "";   temp += "body {background-color: powderblue;} </style>";   temp += "<head><title>Kartenleser RC522</title></head>";   temp += "<h2>Kartenleser RC522 Konfiguration</h2>";   temp += "<body>";   server.sendContent(temp);   temp = "";   temp += "<form action='/' method='post'>";   temp += "<button type='submit' name='AuthCard' value='1' style='height: 50px; width: 200px' >Authorisiere nächste Karte an Leser</button>";   temp += "</form>";   server.sendContent(temp);   temp = "";    server.client().stop();    }

void InitalizeHTTPServer()    {   bool initok = false;   server.on("/", handleRoot);   server.onNotFound ( handleNotFound );   server.begin(); // Web server start   }     // ******************* End Functions Webserver *********************************************

// ******************* Start Functions WiFi Management *************************************

bool startWiFiClient() {   bool WiFiClientStarted = false;   size_t A0_ADCValue = 0;   byte i = 0;   byte connRes = 0;   //Serial.setDebugOutput(true);  // Zu Debugzwecken aktivieren.    WiFi.hostname("CrdRdr41667");   WiFi.softAPdisconnect(true);   WiFi.disconnect();   WiFi.mode(WIFI_STA);   if(loadCredentials())      {      WiFi.begin(MyWiFiConfig.APSTAName, MyWiFiConfig.WiFiPwd);      while (( connRes != 3 ) and( connRes != 4 ) and (i != 30))  //if connRes == 0  "IDLE_STATUS - change Statius"       {        i++;       // Serial.print("."); // Connect vorgang auf der seriellen Schnittstelle beobachten       delay(500);       yield();       connRes  = WiFi.waitForConnectResult();       }      if (connRes == 4 ) { // if password is incorrect       Serial.println("ATWIFI:PWDERR");             WiFi.disconnect();       }      if (connRes == 6 ) { //  module is not configured in station mode       Serial.println("ATWIFI:STAERR");       WiFi.disconnect();       }      }   if(WiFi.status() == WL_CONNECTED)      {     Serial.print("ATIP:");     Serial.println(WiFi.localIP());     WiFi.setAutoReconnect(true); // Set whether module will attempt to reconnect to an access point in case it is disconnected.     // Setup MDNS responder     if (!MDNS.begin("CrdRdr41667"))        {       Serial.println("ATMDNS:NOK");       } else { MDNS.addService("http", "tcp", 80); }        WiFiClientStarted = true;     } else      {     WiFi.disconnect();     WiFi.mode(WIFI_STA);     WiFi.begin("Deine_WLANSSID","Dein_Passwort"); // Ändern bzw. anpassen!     saveCredentials();      while (( connRes != 3 ) and( connRes != 4 ) and (i != 30))  //if connRes == 0  "IDLE_STATUS - change Statius"       {        i++;       // Serial.print("."); // Connect vorgang auf der seriellen Schnittstelle beobachten       delay(500);       yield();       connRes  = WiFi.waitForConnectResult();       }      }    //WiFi.printDiag(Serial);       // Zu Debugzwecken aktivieren.   return WiFiClientStarted; 
}
// ******************* END Functions WiFi Management *************************************

// ******************* Start Functions Store WiFi Credentials to EEPROM ******************
bool loadCredentials() 
{
 bool RetValue;
 EEPROM.begin(512);
 EEPROM.get(0,MyWiFiConfig);
 EEPROM.end();
 if (String(MyWiFiConfig.ConfigValid) == "TK")    {     RetValue = true;   } else   {     RetValue = false; // WLAN Settings nicht gefunden.   }   return RetValue; 
}

void saveCredentials() Speicehre Wlan credentials on EEPROM 
{   String A;   Size_t ;   for ( = 0 ;  < Sizeof(MyWiFiConfig) ; ++) Loeschen of the old configuration      {       Eeprom.Write(, 0);       }   for ( = 0 ;  < STANameLen  ; ++) Loeschen of the old configuration      {       MyWiFiConfig.WiFiPwd[] = 0;       }   for ( = 0 ;  < WiFiPwdLen ; ++) Loeschen of the old configuration      {       MyWiFiConfig.APSTAName[] = 0;       }      A = Wifi.Ssid().c_str();    = A.length();   A.Tochararray(MyWiFiConfig.APSTAName,+1);    A = Wifi.Psk().c_str();    = A.length();   A.Tochararray(MyWiFiConfig.WiFiPwd,+1);       Strncpy(MyWiFiConfig.ConfigValid , "TK", Sizeof(MyWiFiConfig.ConfigValid) );    Eeprom.Begin(512);   Eeprom.Put(0, MyWiFiConfig);   Eeprom.Commit();   Eeprom.End();
}
END Functions StoreCredentialsto EEPROM *****************************************************************************************************
 
Void Loop()  Main loop
{   Only when a card is found and could be read does if execute the contents   If (mfrc522.PICC_IsNewCardPresent() && mfrc522.PICC_ReadCardSerial() )   PICC = proximity integrated circuit card = contactless chip card   {     Serial.Print("PICC UID:");     for (Byte  = 0;  < mfrc522.Uid.Size; ++)      {       Distance between HEX numbers and leading zero at byte < 16       Serial.Print(mfrc522.Uid.uidByte[] < 0x10 ? " 0" : " ");       Serial.Print(mfrc522.Uid.uidByte[], Hex);     }    Bool Isvalid = True;   If (LearnNewCard)   {    for (Byte  = 0;  < Sizeof(MyEEPROMValidCardUID.CardVaildUID); ++)      {      MyEEPROMValidCardUID.CardVaildUID[] = mfrc522.Uid.uidByte[];      Eeprom.Begin(512);      Eeprom.Put(100,MyEEPROMValidCardUID);      Eeprom.Commit();      Eeprom.End();      LearnNewCard = False;     }     Isvalid = True;       } else   {     for (Byte  = 0;  < Sizeof(MyEEPROMValidCardUID.CardVaildUID); ++)      {     If (mfrc522.Uid.uidByte[] != MyEEPROMValidCardUID.CardVaildUID[]) { Isvalid = False; }         }   }     If (Isvalid)    {       Bool PinState= digitalRead(RELAIS_PIN);       PinState = !PinState;       digitalWrite(RELAIS_PIN, PinState);            digitalWrite(RGBLED_R,Low);     Led Green       digitalWrite(RGBLED_G,High);       digitalWrite(RGBLED_B,Low);       Serial.Print("Valid.");       Delay(2000);       digitalWrite(RGBLED_R,Low);     Led color blue reader is in basic condition       digitalWrite(RGBLED_G,Low);       digitalWrite(RGBLED_B,High);     } else    {        digitalWrite(RGBLED_R,High);     Led Red - Last card was invalid       digitalWrite(RGBLED_G,Low);       digitalWrite(RGBLED_B,Low);       Serial.Print("Invalid.");       Delay(2000);       }      Serial.println();      Puts the read card into a sleep mode to search for other cards.     mfrc522.PICC_HaltA();     Delay(1000);   }   Server.handleClient(); Edit Web server requests   Yield();               Call internal ESP8266 functions   Delay(20);
}

 

We compile the code and upload it to our NodeMcu. While uploading the sketch, our RGB Led lights up "red". After successful upload, the color of the LED changes to "purple" after some time. Changing the color indicates that the upload operation was successful.

To allow a upload to the NodeMcu Reliable "Flash" button on the NodeMcu must be pressed and held while compiling!

When the upload process completes successfully, we start our serial terminal in the IDE and set the transfer speed to 9600 baud. We get an output that outputs our IP address on the local network:

 

We ping the displayed address to test if everything worked out. When we get a response to our pings, we go to the ESP's website by typing the IP address shown above into the browser:

 

Since our ESP has not yet saved an authorized card in the internal EEPROM, we now click on the button. We receive the following notice:

The LED lights up yellow to indicate that a card can be held in front of the reader. The next card held in front of the reader in this mode is accepted and saved as authorized. The previous authorized card will be deleted. Only one card can be authorized at a time.

In the next part we will connect a button to our NodeMcu with which we can automatically exchange WPS keys with our router and write the WLAN access data permanently into our EEPROM. Thus, the last part of the fixed configuration is dynamized from our code. Once compiled, the code can be used with any router and card. We will continue to use the internal file system of the ESP to be able to manage several cards via the web interface.

 

Until the next part

Esp-8266Projects for advanced

1 comment

Martin

Martin

Im Terminal kommt immer nur das. Keine IP
rl

$⸮⸮|

⸮$⸮|⸮$⸮c|⸮⸮⸮2⸮r⸮b⸮#⸮⸮on⸮lNo⸮⸮⸮Bp⸮⸮${l{lp⸮N⸮⸮l⸮⸮bo⸮|l⸮⸮b⸮⸮no⸮$⸮⸮

$`⸮ood`n{⸮ےo#⸮d{⸮⸮n
18:34:54.645 → ATSN:7427403D⸮⸮

Leave a comment

All comments are moderated before being published

Recommended blog posts

  1. Install ESP32 now from the board manager
  2. Lüftersteuerung Raspberry Pi
  3. Arduino IDE - Programmieren für Einsteiger - Teil 1
  4. ESP32 - das Multitalent
  5. OTA - Over the Air - ESP programming via WLAN