эти наклейки из-за малой антенны через пластик уже могут не срабатывать, им нужен прямой контакт. Лучше большую (увеличит дальность) наклейку на обратную сторону крышки аккумулятора. А если телефон в чехле, то сойдет и метрошный одноразовый билетик.
Если в телефоне есть NFC, то никакх брелков и наклеек уже не надо. Я так на работе и в автобусах прохожу %)
допустим такая история, дали ключ от подъезда. этот ключ можно вписать в билет метро? если нет то в какую наклейку можно? nfc в телефоне нет. и ещё есть код чтобы писать в наклейки. всё что я видел это для чтения данных с карты
ну ключ с брелка, которым двери открываю, я вижу. этот ключ можно клонировать. какая разница что использует домофон, если он видит ключ из базы он должен открыть, я в ларке могу ключ склонировать и там не спрашивают про секторы. просто берут один брелок отдают два
они используют брелки с перезаписываемыми секторами. Ради эксперимента дайти им метрошный билетик, пусть попробуют на него склонировать - вдруг получится? За это денег не берут :)
мы отвлеклись. при чём тут ларёк. есть ардуино, есть брелок с ключем, есть ещё карточка, абсалютно не обязательно метро, чтото подходящее. как один ключ перенести на на другой?
В итоге выяснилось, что всё даже хуже: на команде (из наиболее распространенной библиотеки Мигеля Бальбо) mfrc522.PICC_IsNewCardPresent() ардуино
1. без резета - зависает раз в полчаса.
2. с хардварным и софтварным резетом раз в 2 секунды - зависает раз в 7 часов
3. с вот таким полным отключаением питания раз в 4 секунды - не зависает сутки (а мне больше и не надо)
digitalWrite( rfid_VCC ,LOW);
digitalWrite( rfid_RST,LOW); // not connected
digitalWrite( rfid_MISO,LOW);
digitalWrite( rfid_MOSI,LOW);
digitalWrite( rfid_SCK,LOW);
digitalWrite( rfid_SS,LOW);
Забавные факты:
Произвольные зависания связаны с наличием на той-же ISP шине LPD433 радиомодуля, если к нему не обращаться, то и не зависает.
Библиотека Мигеля Бальбо вообще не делает хардварный резет, она только проверяет состояние вывода RST и поднимает его если он в нуле, но никогда не опускает.
Выключать питание rc522 приходится устанавливая низкий уровень на всех ногах, иначе модуль питается "паразитно" :-)
Подскажите в чем проблема - с библиотекой Мигеля Бальбо все работает, с этой https://github.com/miguelbalboa/rfid не компилируется ни один пример. Ошибка : Arduino: 1.6.4 (Windows 8.1), Плата"Arduino Uno"
C:\Users\Oleg\Documents\Arduino\libraries\rfid-master\src\MFRC522.cpp: In constructor 'MFRC522::MFRC522()':
C:\Users\Oleg\Documents\Arduino\libraries\rfid-master\src\MFRC522.cpp:16:33: error: 'UINT8_MAX' was not declared in this scope
MFRC522::MFRC522(): MFRC522(SS, UINT8_MAX) { // SS is defined in pins_arduino.h, UINT8_MAX means there is no connection from Arduino to MFRC522's reset and power down input
^
C:\Users\Oleg\Documents\Arduino\libraries\rfid-master\src\MFRC522.cpp: In member function 'void MFRC522::PCD_Init()':
C:\Users\Oleg\Documents\Arduino\libraries\rfid-master\src\MFRC522.cpp:201:28: error: 'UINT8_MAX' was not declared in this scope
странно что эта ошибка вообще вылезла, поиск по UINT8_MAX в папке c:\Program Files\Arduino выдает что оно определяется в stdint.h вот так что, можно не заморачиваясь просто подключить его
странно что эта ошибка вообще вылезла, поиск по UINT8_MAX в папке c:\Program Files\Arduino выдает что оно определяется в stdint.h вот так что, можно не заморачиваясь просто подключить его
Я понимаю что должно в EEPROM записывать но почему-то при выключении Дуня забывает все ключи, в написании кода не силен но в коде, который я заливаю функцию записи в память я вижу . Подскажите пож. в чем тогда может быть проблема. Может в коде ошибка? Спасибо
#include <EEPROM.h> // We are going to read and write PICC's UIDs from/to EEPROM
#include <SPI.h> // RC522 Module uses SPI protocol
#include <MFRC522.h> // Library for Mifare RC522 Devices
#define COMMON_ANODE
#ifdef COMMON_ANODE
#define LED_ON LOW
#define LED_OFF HIGH
#else
#define LED_ON HIGH
#define LED_OFF LOW
#endif
#define redLed 7 // Set Led Pins
#define greenLed 6
#define blueLed 5
#define relay 4 // Set Relay Pin
#define wipeB 3 // Button pin for WipeMode, HOLD it then reset arduino for wipe mode.
boolean match = false; // initialize card match to false
boolean programMode = false; // initialize programming mode to false
int successRead; // Variable integer to keep if we have Successful Read from Reader
byte storedCard[4]; // Stores an ID read from EEPROM
byte readCard[4]; // Stores scanned ID read from RFID Module
byte masterCard[4]; // Stores master card's ID read from EEPROM
/*
We need to define MFRC522's pins and create instance
Pin layout should be as follows (on Arduino Uno):
MOSI: Pin 11 / ICSP-4
MISO: Pin 12 / ICSP-1
SCK : Pin 13 / ICSP-3
SS : Pin 10 (Configurable)
RST : Pin 9 (Configurable)
look MFRC522 Library for
other Arduinos' pin configuration
*/
#define SS_PIN 10
#define RST_PIN 9
MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance.
///////////////////////////////////////// Setup ///////////////////////////////////
void setup() {
//Arduino Pin Configuration
pinMode(redLed, OUTPUT);
pinMode(greenLed, OUTPUT);
pinMode(blueLed, OUTPUT);
pinMode(wipeB, INPUT_PULLUP); // Enable pin's pull up resistor
pinMode(relay, OUTPUT);
//Be careful how relay circuit behave on while resetting or power-cycling your Arduino
digitalWrite(relay, HIGH); // Make sure door is locked
digitalWrite(redLed, LED_OFF); // Make sure led is off
digitalWrite(greenLed, LED_OFF); // Make sure led is off
digitalWrite(blueLed, LED_OFF); // Make sure led is off
//Protocol Configuration
Serial.begin(9600); // Initialize serial communications with PC
SPI.begin(); // MFRC522 Hardware uses SPI protocol
mfrc522.PCD_Init(); // Initialize MFRC522 Hardware
//If you set Antenna Gain to Max it will increase reading distance
//mfrc522.PCD_SetAntennaGain(mfrc522.RxGain_max);
Serial.println(F("BlueCore Tech Acces Control")); // For debugging purposes
ShowReaderDetails(); // Show details of PCD - MFRC522 Card Reader details
//Wipe Code if Button Pressed while setup run (powered on) it wipes EEPROM
if (digitalRead(wipeB) == LOW) { // when button pressed pin should get low, button connected to ground
digitalWrite(redLed, LED_ON); // Red Led stays on to inform user we are going to wipe
Serial.println(F("Wipe Button Pressed"));
Serial.println(F("You have 5 seconds to Cancel"));
Serial.println(F("All records will be removed. This cannot be undone!"));
delay(5000); // Give user enough time to cancel operation
if (digitalRead(wipeB) == LOW) { // If button still be pressed, wipe EEPROM
Serial.println(F("CLEARING DATABASE"));
for (int x = 0; x < EEPROM.length(); x = x + 1) { //Loop end of EEPROM address
if (EEPROM.read(x) == 0) { //If EEPROM address 0
// do nothing, already clear, go to the next address in order to save time and reduce writes to EEPROM
}
else {
EEPROM.write(x, 0); // if not write 0 to clear, it takes 3.3mS
}
}
Serial.println(F("DATABASE Successfully Wiped"));
digitalWrite(redLed, LED_OFF); // visualize successful wipe
delay(200);
digitalWrite(redLed, LED_ON);
delay(200);
digitalWrite(redLed, LED_OFF);
delay(200);
digitalWrite(redLed, LED_ON);
delay(200);
digitalWrite(redLed, LED_OFF);
}
else {
Serial.println(F("Wiping Cancelled"));
digitalWrite(redLed, LED_OFF);
}
}
// Check if master card defined, if not let user choose a master card
// This also useful to just redefine Master Card
// You can keep other EEPROM records just write other than 143 to EEPROM address 1
// EEPROM address 1 should hold magical number which is '143'
if (EEPROM.read(1) != 143) {
Serial.println(F("No Master Card Set"));
Serial.println(F("Scan A RFID Card to Set as Master Card"));
do {
successRead = getID(); // sets successRead to 1 when we get read from reader otherwise 0
digitalWrite(blueLed, LED_ON); // Visualize Master Card need to be defined
delay(200);
digitalWrite(blueLed, LED_OFF);
delay(200);
}
while (!successRead); // Program will not go further while you not get a successful read
for ( int j = 0; j < 4; j++ ) { // Loop 4 times
EEPROM.write( 2 + j, readCard[j] ); // Write scanned PICC's UID to EEPROM, start from address 3
}
EEPROM.write(1, 143); // Write to EEPROM we defined Master Card.
Serial.println(F("Master Card Set"));
}
Serial.println(F("-------------------"));
Serial.println(F("Master Card's UID = "));
for ( int i = 0; i < 4; i++ ) { // Read Master Card's UID from EEPROM
masterCard[i] = EEPROM.read(2 + i); // Write it to masterCard
Serial.print(masterCard[i], HEX);
}
Serial.println("");
Serial.println(F("-------------------"));
Serial.println(F("Everything Ready"));
Serial.println(F("Waiting for Keys or cards to be scanned"));
cycleLeds(); // Everything ready lets give user some feedback by cycling leds
}
///////////////////////////////////////// Main Loop ///////////////////////////////////
void loop () {
do {
successRead = getID(); // sets successRead to 1 when we get read from reader otherwise 0
if (programMode) {
cycleLeds(); // Program Mode cycles through RGB waiting to read a new card
}
else {
normalModeOn(); // Normal mode, blue Power LED is on, all others are off
}
}
while (!successRead); //the program will not go further while you not get a successful read
if (programMode) {
if ( isMaster(readCard) ) { //If master card scanned again exit program mode
Serial.println(F("Master Card Scanned"));
Serial.println(F("Exiting Programming Mode"));
Serial.println(F("-----------------------------"));
programMode = false;
return;
}
else {
if ( findID(readCard) ) { // If scanned card is known delete it
Serial.println(F("I know this key, removing..."));
deleteID(readCard);
Serial.println("-----------------------------");
}
else { // If scanned card is not known add it
Serial.println(F("I do not know this key, adding..."));
writeID(readCard);
Serial.println(F("-----------------------------"));
}
}
}
else {
if ( isMaster(readCard) ) { // If scanned card's ID matches Master Card's ID enter program mode
programMode = true;
Serial.println(F("Hello Master - Entered Programming Mode"));
int count = EEPROM.read(0); // Read the first Byte of EEPROM that
Serial.print(F("I have ")); // stores the number of ID's in EEPROM
Serial.print(count);
Serial.print(F(" record(s) in DATABASE"));
Serial.println("");
Serial.println(F("Scan a Card or key to ADD or REMOVE"));
Serial.println(F("-----------------------------"));
}
else {
if ( findID(readCard) ) { // If not, see if the card is in the EEPROM
Serial.println(F("Welcome, Acces Granted"));
granted(300); // Open the door lock for 300 ms
}
else { // If not, show that the ID was not valid
Serial.println(F("Acces Denied!"));
denied();
}
}
}
}
///////////////////////////////////////// Access Granted ///////////////////////////////////
void granted (int setDelay) {
digitalWrite(blueLed, LED_OFF); // Turn off blue LED
digitalWrite(redLed, LED_OFF); // Turn off red LED
digitalWrite(greenLed, LED_ON); // Turn on green LED
digitalWrite(relay, LOW); // Unlock door!
delay(4000); // Hold door lock open for given seconds
digitalWrite(relay, HIGH); // Relock door
delay(1000); // Hold green LED on for a second
}
///////////////////////////////////////// Access Denied ///////////////////////////////////
void denied() {
digitalWrite(greenLed, LED_OFF); // Make sure green LED is off
digitalWrite(blueLed, LED_OFF); // Make sure blue LED is off
digitalWrite(redLed, LED_ON); // Turn on red LED
delay(1000);
}
///////////////////////////////////////// Get PICC's UID ///////////////////////////////////
int getID() {
// Getting ready for Reading PICCs
if ( ! mfrc522.PICC_IsNewCardPresent()) { //If a new PICC placed to RFID reader continue
return 0;
}
if ( ! mfrc522.PICC_ReadCardSerial()) { //Since a PICC placed get Serial and continue
return 0;
}
// There are Mifare PICCs which have 4 byte or 7 byte UID care if you use 7 byte PICC
// I think we should assume every PICC as they have 4 byte UID
// Until we support 7 byte PICCs
Serial.println(F("Scanned KEY's UID:"));
for (int i = 0; i < 4; i++) { //
readCard[i] = mfrc522.uid.uidByte[i];
Serial.print(readCard[i], HEX);
}
Serial.println("");
mfrc522.PICC_HaltA(); // Stop reading
return 1;
}
void ShowReaderDetails() {
// Get the MFRC522 software version
byte v = mfrc522.PCD_ReadRegister(mfrc522.VersionReg);
Serial.print(F("MFRC522 Version: 0x"));
Serial.print(v, HEX);
if (v == 0x91)
Serial.print(F(" = v1.0"));
else if (v == 0x11)
Serial.print(F(" = BlueCore Tech. RFID Acces v2.0"));
else
Serial.print(F(" (unknown)"));
Serial.println("");
// When 0x00 or 0xFF is returned, communication probably failed
if ((v == 0x00) || (v == 0xFF)) {
Serial.println(F("WARNING: Communication failure, is the RFID-MFRC522 properly connected?"));
while(true); // do not go further
}
}
///////////////////////////////////////// Cycle Leds (Program Mode) ///////////////////////////////////
void cycleLeds() {
digitalWrite(redLed, LED_OFF); // Make sure red LED is off
digitalWrite(greenLed, LED_ON); // Make sure green LED is on
digitalWrite(blueLed, LED_OFF); // Make sure blue LED is off
delay(200);
digitalWrite(redLed, LED_OFF); // Make sure red LED is off
digitalWrite(greenLed, LED_OFF); // Make sure green LED is off
digitalWrite(blueLed, LED_ON); // Make sure blue LED is on
delay(200);
digitalWrite(redLed, LED_ON); // Make sure red LED is on
digitalWrite(greenLed, LED_OFF); // Make sure green LED is off
digitalWrite(blueLed, LED_OFF); // Make sure blue LED is off
delay(200);
}
//////////////////////////////////////// Normal Mode Led ///////////////////////////////////
void normalModeOn () {
digitalWrite(blueLed, LED_ON); // Blue LED ON and ready to read card
digitalWrite(redLed, LED_OFF); // Make sure Red LED is off
digitalWrite(greenLed, LED_OFF); // Make sure Green LED is off
digitalWrite(relay, HIGH); // Make sure Door is Locked
}
//////////////////////////////////////// Read an ID from EEPROM //////////////////////////////
void readID( int number ) {
int start = (number * 4 ) + 2; // Figure out starting position
for ( int i = 0; i < 4; i++ ) { // Loop 4 times to get the 4 Bytes
storedCard[i] = EEPROM.read(start + i); // Assign values read from EEPROM to array
}
}
///////////////////////////////////////// Add ID to EEPROM ///////////////////////////////////
void writeID( byte a[] ) {
if ( !findID( a ) ) { // Before we write to the EEPROM, check to see if we have seen this card before!
int num = EEPROM.read(0); // Get the numer of used spaces, position 0 stores the number of ID cards
int start = ( num * 4 ) + 6; // Figure out where the next slot starts
num++; // Increment the counter by one
EEPROM.write( 0, num ); // Write the new count to the counter
for ( int j = 0; j < 4; j++ ) { // Loop 4 times
EEPROM.write( start + j, a[j] ); // Write the array values to EEPROM in the right position
}
successWrite();
Serial.println(F("Succesfully added ID record to DATABASE"));
}
else {
failedWrite();
Serial.println(F("Failed! There is something wrong with ID or bad DATABASE"));
}
}
///////////////////////////////////////// Remove ID from EEPROM ///////////////////////////////////
void deleteID( byte a[] ) {
if ( !findID( a ) ) { // Before we delete from the EEPROM, check to see if we have this card!
failedWrite(); // If not
Serial.println(F("Failed! There is something wrong with ID or bad DATABASE"));
}
else {
int num = EEPROM.read(0); // Get the numer of used spaces, position 0 stores the number of ID cards
int slot; // Figure out the slot number of the card
int start; // = ( num * 4 ) + 6; // Figure out where the next slot starts
int looping; // The number of times the loop repeats
int j;
int count = EEPROM.read(0); // Read the first Byte of EEPROM that stores number of cards
slot = findIDSLOT( a ); // Figure out the slot number of the card to delete
start = (slot * 4) + 2;
looping = ((num - slot) * 4);
num--; // Decrement the counter by one
EEPROM.write( 0, num ); // Write the new count to the counter
for ( j = 0; j < looping; j++ ) { // Loop the card shift times
EEPROM.write( start + j, EEPROM.read(start + 4 + j)); // Shift the array values to 4 places earlier in the EEPROM
}
for ( int k = 0; k < 4; k++ ) { // Shifting loop
EEPROM.write( start + j + k, 0);
}
successDelete();
Serial.println(F("Succesfully removed ID record from DATABASE"));
}
}
///////////////////////////////////////// Check Bytes ///////////////////////////////////
boolean checkTwo ( byte a[], byte b[] ) {
if ( a[0] != NULL ) // Make sure there is something in the array first
match = true; // Assume they match at first
for ( int k = 0; k < 4; k++ ) { // Loop 4 times
if ( a[k] != b[k] ) // IF a != b then set match = false, one fails, all fail
match = false;
}
if ( match ) { // Check to see if if match is still true
return true; // Return true
}
else {
return false; // Return false
}
}
///////////////////////////////////////// Find Slot ///////////////////////////////////
int findIDSLOT( byte find[] ) {
int count = EEPROM.read(0); // Read the first Byte of EEPROM that
for ( int i = 1; i <= count; i++ ) { // Loop once for each EEPROM entry
readID(i); // Read an ID from EEPROM, it is stored in storedCard[4]
if ( checkTwo( find, storedCard ) ) { // Check to see if the storedCard read from EEPROM
// is the same as the find[] ID card passed
return i; // The slot number of the card
break; // Stop looking we found it
}
}
}
///////////////////////////////////////// Find ID From EEPROM ///////////////////////////////////
boolean findID( byte find[] ) {
int count = EEPROM.read(0); // Read the first Byte of EEPROM that
for ( int i = 1; i <= count; i++ ) { // Loop once for each EEPROM entry
readID(i); // Read an ID from EEPROM, it is stored in storedCard[4]
if ( checkTwo( find, storedCard ) ) { // Check to see if the storedCard read from EEPROM
return true;
break; // Stop looking we found it
}
else { // If not, return false
}
}
return false;
}
///////////////////////////////////////// Write Success to EEPROM ///////////////////////////////////
// Flashes the green LED 3 times to indicate a successful write to EEPROM
void successWrite() {
digitalWrite(blueLed, LED_OFF); // Make sure blue LED is off
digitalWrite(redLed, LED_OFF); // Make sure red LED is off
digitalWrite(greenLed, LED_OFF); // Make sure green LED is on
delay(200);
digitalWrite(greenLed, LED_ON); // Make sure green LED is on
delay(200);
digitalWrite(greenLed, LED_OFF); // Make sure green LED is off
delay(200);
digitalWrite(greenLed, LED_ON); // Make sure green LED is on
delay(200);
digitalWrite(greenLed, LED_OFF); // Make sure green LED is off
delay(200);
digitalWrite(greenLed, LED_ON); // Make sure green LED is on
delay(200);
}
///////////////////////////////////////// Write Failed to EEPROM ///////////////////////////////////
// Flashes the red LED 3 times to indicate a failed write to EEPROM
void failedWrite() {
digitalWrite(blueLed, LED_OFF); // Make sure blue LED is off
digitalWrite(redLed, LED_OFF); // Make sure red LED is off
digitalWrite(greenLed, LED_OFF); // Make sure green LED is off
delay(200);
digitalWrite(redLed, LED_ON); // Make sure red LED is on
delay(200);
digitalWrite(redLed, LED_OFF); // Make sure red LED is off
delay(200);
digitalWrite(redLed, LED_ON); // Make sure red LED is on
delay(200);
digitalWrite(redLed, LED_OFF); // Make sure red LED is off
delay(200);
digitalWrite(redLed, LED_ON); // Make sure red LED is on
delay(200);
}
///////////////////////////////////////// Success Remove UID From EEPROM ///////////////////////////////////
// Flashes the blue LED 3 times to indicate a success delete to EEPROM
void successDelete() {
digitalWrite(blueLed, LED_OFF); // Make sure blue LED is off
digitalWrite(redLed, LED_OFF); // Make sure red LED is off
digitalWrite(greenLed, LED_OFF); // Make sure green LED is off
delay(200);
digitalWrite(blueLed, LED_ON); // Make sure blue LED is on
delay(200);
digitalWrite(blueLed, LED_OFF); // Make sure blue LED is off
delay(200);
digitalWrite(blueLed, LED_ON); // Make sure blue LED is on
delay(200);
digitalWrite(blueLed, LED_OFF); // Make sure blue LED is off
delay(200);
digitalWrite(blueLed, LED_ON); // Make sure blue LED is on
delay(200);
}
////////////////////// Check readCard IF is masterCard ///////////////////////////////////
// Check to see if the ID passed is the master programing card
boolean isMaster( byte test[] ) {
if ( checkTwo( test, masterCard ) )
return true;
else
return false;
}
Пробую подключить RFID RC522 совместно с NANO V3.0. Подключаю библиотеку, соединяю все как в скетче. Пробовал RFID-модуль запитывать от NANO и от отдельного источника. Ни в какую не считывается. В чем проблема?
/*
* ----------------------------------------------------------------------------
* This is a MFRC522 library example; see https://github.com/miguelbalboa/rfid
* for further details and other examples.
*
* NOTE: The library file MFRC522.h has a lot of useful info. Please read it.
*
* Released into the public domain.
* ----------------------------------------------------------------------------
* Example sketch/program showing how to read data from a PICC (that is: a RFID
* Tag or Card) using a MFRC522 based RFID Reader on the Arduino SPI interface.
*
* When the Arduino and the MFRC522 module are connected (see the pin layout
* below), load this sketch into Arduino IDE then verify/compile and upload it.
* To see the output: use Tools, Serial Monitor of the IDE (hit Ctrl+Shft+M).
* When you present a PICC (that is: a RFID Tag or Card) at reading distance
* of the MFRC522 Reader/PCD, the serial output will show the ID/UID, type and
* any data blocks it can read. Note: you may see "Timeout in communication"
* messages when removing the PICC from reading distance too early.
*
* If your reader supports it, this sketch/program will read all the PICCs
* presented (that is: multiple tag reading). So if you stack two or more
* PICCs on top of each other and present them to the reader, it will first
* output all details of the first and then the next PICC. Note that this
* may take some time as all data blocks are dumped, so keep the PICCs at
* reading distance until complete.
*
* Typical pin layout used:
* -----------------------------------------------------------------------------------------
* MFRC522 Arduino Arduino Arduino Arduino Arduino
* Reader/PCD Uno Mega Nano v3 Leonardo/Micro Pro Micro
* Signal Pin Pin Pin Pin Pin Pin
* -----------------------------------------------------------------------------------------
* RST/Reset RST 9 5 D9 RESET/ICSP-5 RST
* SPI SS SDA(SS) 10 53 D10 10 10
* SPI MOSI MOSI 11 / ICSP-4 51 D11 ICSP-4 16
* SPI MISO MISO 12 / ICSP-1 50 D12 ICSP-1 14
* SPI SCK SCK 13 / ICSP-3 52 D13 ICSP-3 15
*/
#include <SPI.h>
#include <MFRC522.h>
#define RST_PIN 9 //
#define SS_PIN 10 //
MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance
void setup() {
Serial.begin(9600); // Initialize serial communications with the PC
while (!Serial); // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
SPI.begin(); // Init SPI bus
mfrc522.PCD_Init(); // Init MFRC522
ShowReaderDetails(); // Show details of PCD - MFRC522 Card Reader details
Serial.println(F("Scan PICC to see UID, type, and data blocks..."));
}
void loop() {
// Look for new cards
if ( ! mfrc522.PICC_IsNewCardPresent()) {
return;
}
// Select one of the cards
if ( ! mfrc522.PICC_ReadCardSerial()) {
return;
}
// Dump debug info about the card; PICC_HaltA() is automatically called
mfrc522.PICC_DumpToSerial(&(mfrc522.uid));
}
void ShowReaderDetails() {
// Get the MFRC522 software version
byte v = mfrc522.PCD_ReadRegister(mfrc522.VersionReg);
Serial.print(F("MFRC522 Software Version: 0x"));
Serial.print(v, HEX);
if (v == 0x91)
Serial.print(F(" = v1.0"));
else if (v == 0x92)
Serial.print(F(" = v2.0"));
else
Serial.print(F(" (unknown)"));
Serial.println("");
// When 0x00 or 0xFF is returned, communication probably failed
if ((v == 0x00) || (v == 0xFF)) {
Serial.println(F("WARNING: Communication failure, is the MFRC522 properly connected?"));
}
}
а распаяли как? схему откуда брали? Штуки четыре к мне приходила RFIDfа, вместе на Nano прекрасно все работают. Пробовали стандартные примеры из библиотеки?
нужно локализовать проблему: в стандартном примере функция ShowReaderDetails() - выводит номер версии ридера. если он выдает некорректную информацию, значит ридер подключен к ардуине неправильно и нужно решать проблему с подключением, а потом уже за ключи браться.
/*
* Copy the RFID card data into variables and then
* scan the second empty card to copy all the date
* ----------------------------------------------------------------------------
* Example sketch/program which will try the most used default keys listed in
* https://code.google.com/p/mfcuk/wiki/MifareClassicDefaultKeys to dump the
* block 0 of a MIFARE RFID card using a RFID-RC522 reader.
*
* Typical pin layout used:
* -----------------------------------------------------------------------------------------
* MFRC522 Arduino Arduino Arduino Arduino Arduino
* Reader/PCD Uno/101 Mega Nano v3 Leonardo/Micro Pro Micro
* Signal Pin Pin Pin Pin Pin Pin
* -----------------------------------------------------------------------------------------
* RST/Reset RST 9 5 D9 RESET/ICSP-5 RST
* SPI SS SDA(SS) 10 53 D10 10 10
* SPI MOSI MOSI 11 / ICSP-4 51 D11 ICSP-4 16
* SPI MISO MISO 12 / ICSP-1 50 D12 ICSP-1 14
* SPI SCK SCK 13 / ICSP-3 52 D13 ICSP-3 15
*
*/
#include <SPI.h>
#include <MFRC522.h>
constexpr uint8_t RST_PIN = 9; // Configurable, see typical pin layout above
constexpr uint8_t SS_PIN = 10; // Configurable, see typical pin layout above
MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance.
byte buffer[18];
byte block;
byte waarde[64][16];
MFRC522::StatusCode status;
MFRC522::MIFARE_Key key;
// Number of known default keys (hard-coded)
// NOTE: Synchronize the NR_KNOWN_KEYS define with the defaultKeys[] array
constexpr uint8_t NR_KNOWN_KEYS = 8;
// Known keys, see: https://code.google.com/p/mfcuk/wiki/MifareClassicDefaultKeys
byte knownKeys[NR_KNOWN_KEYS][MFRC522::MF_KEY_SIZE] = {
{0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, // FF FF FF FF FF FF = factory default
{0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5}, // A0 A1 A2 A3 A4 A5
{0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5}, // B0 B1 B2 B3 B4 B5
{0x4d, 0x3a, 0x99, 0xc3, 0x51, 0xdd}, // 4D 3A 99 C3 51 DD
{0x1a, 0x98, 0x2c, 0x7e, 0x45, 0x9a}, // 1A 98 2C 7E 45 9A
{0xd3, 0xf7, 0xd3, 0xf7, 0xd3, 0xf7}, // D3 F7 D3 F7 D3 F7
{0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff}, // AA BB CC DD EE FF
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00} // 00 00 00 00 00 00
};
char choice;
/*
* Initialize.
*/
void setup() {
Serial.begin(9600); // Initialize serial communications with the PC
while (!Serial); // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
SPI.begin(); // Init SPI bus
mfrc522.PCD_Init(); // Init MFRC522 card
Serial.println(F("Try the most used default keys to print block 0 to 63 of a MIFARE PICC."));
Serial.println("1.Read card \n2.Write to card \n3.Copy the data.");
for (byte i = 0; i < 6; i++) {
key.keyByte[i] = 0xFF;
}
}
//Via seriele monitor de bytes uitlezen in hexadecimaal
void dump_byte_array(byte *buffer, byte bufferSize) {
for (byte i = 0; i < bufferSize; i++) {
Serial.print(buffer[i] < 0x10 ? " 0" : " ");
Serial.print(buffer[i], HEX);
}
}
//Via seriele monitor de bytes uitlezen in ASCI
void dump_byte_array1(byte *buffer, byte bufferSize) {
for (byte i = 0; i < bufferSize; i++) {
Serial.print(buffer[i] < 0x10 ? " 0" : " ");
Serial.write(buffer[i]);
}
}
/*
* Try using the PICC (the tag/card) with the given key to access block 0 to 63.
* On success, it will show the key details, and dump the block data on Serial.
*
* @return true when the given key worked, false otherwise.
*/
bool try_key(MFRC522::MIFARE_Key *key)
{
bool result = false;
for(byte block = 0; block < 64; block++){
// Serial.println(F("Authenticating using key A..."));
status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, key, &(mfrc522.uid));
if (status != MFRC522::STATUS_OK) {
Serial.print(F("PCD_Authenticate() failed: "));
Serial.println(mfrc522.GetStatusCodeName(status));
return false;
}
// Read block
byte byteCount = sizeof(buffer);
status = mfrc522.MIFARE_Read(block, buffer, &byteCount);
if (status != MFRC522::STATUS_OK) {
Serial.print(F("MIFARE_Read() failed: "));
Serial.println(mfrc522.GetStatusCodeName(status));
}
else {
// Successful read
result = true;
Serial.print(F("Success with key:"));
dump_byte_array((*key).keyByte, MFRC522::MF_KEY_SIZE);
Serial.println();
// Dump block data
Serial.print(F("Block ")); Serial.print(block); Serial.print(F(":"));
dump_byte_array1(buffer, 16); //omzetten van hex naar ASCI
Serial.println();
for (int p = 0; p < 16; p++) //De 16 bits uit de block uitlezen
{
waarde [block][p] = buffer[p];
Serial.print(waarde[block][p]);
Serial.print(" ");
}
}
}
Serial.println();
Serial.println("1.Read card \n2.Write to card \n3.Copy the data.");
mfrc522.PICC_HaltA(); // Halt PICC
mfrc522.PCD_StopCrypto1(); // Stop encryption on PCD
return result;
start();
}
/*
* Main loop.
*/
void loop() {
start();
}
void start(){
choice = Serial.read();
if(choice == '1')
{
Serial.println("Read the card");
keuze1();
}
else if(choice == '2')
{
Serial.println("See what is in the variables");
keuze2();
}
else if(choice == '3')
{
Serial.println("Copying the data on to the new card");
keuze3();
}
}
void keuze2(){ //Test waardes in blokken
for(block = 4; block <= 62; block++){
if(block == 7 || block == 11 || block == 15 || block == 19 || block == 23 || block == 27 || block == 31 || block == 35 || block == 39 || block == 43 || block == 47 || block == 51 || block == 55 || block == 59){
block ++;
}
Serial.print(F("Writing data into block "));
Serial.print(block);
Serial.println("\n");
for(int j = 0; j < 16; j++){
Serial.print(waarde[block][j]);
Serial.print(" ");
}
Serial.println("\n");
}
Serial.println("1.Read card \n2.Write to card \n3.Copy the data.");
start();
}
void keuze3(){ //Copy the data in the new card
Serial.println("Insert new card...");
// Look for new cards
if ( ! mfrc522.PICC_IsNewCardPresent())
return;
// Select one of the cards
if ( ! mfrc522.PICC_ReadCardSerial())
return;
// Show some details of the PICC (that is: the tag/card)
Serial.print(F("Card UID:"));
dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
Serial.println();
Serial.print(F("PICC type: "));
MFRC522::PICC_Type piccType = mfrc522.PICC_GetType(mfrc522.uid.sak);
Serial.println(mfrc522.PICC_GetTypeName(piccType));
// Try the known default keys
/*MFRC522::MIFARE_Key key;
for (byte k = 0; k < NR_KNOWN_KEYS; k++) {
// Copy the known key into the MIFARE_Key structure
for (byte i = 0; i < MFRC522::MF_KEY_SIZE; i++) {
key.keyByte[i] = knownKeys[k][i];
}
}*/
for (byte i = 0; i < 6; i++) {
key.keyByte[i] = 0xFF;
}
for(int i = 4; i <= 62; i++){ //De blocken 4 tot 62 kopieren, behalve al deze onderstaande blocken (omdat deze de authenticatie blokken zijn)
if(i == 7 || i == 11 || i == 15 || i == 19 || i == 23 || i == 27 || i == 31 || i == 35 || i == 39 || i == 43 || i == 47 || i == 51 || i == 55 || i == 59){
i++;
}
block = i;
// Authenticate using key A
Serial.println(F("Authenticating using key A..."));
status = (MFRC522::StatusCode) mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, &key, &(mfrc522.uid));
if (status != MFRC522::STATUS_OK) {
Serial.print(F("PCD_Authenticate() failed: "));
Serial.println(mfrc522.GetStatusCodeName(status));
return;
}
// Authenticate using key B
Serial.println(F("Authenticating again using key B..."));
status = (MFRC522::StatusCode) mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_B, block, &key, &(mfrc522.uid));
if (status != MFRC522::STATUS_OK) {
Serial.print(F("PCD_Authenticate() failed: "));
Serial.println(mfrc522.GetStatusCodeName(status));
return;
}
// Write data to the block
Serial.print(F("Writing data into block "));
Serial.print(block);
Serial.println("\n");
dump_byte_array(waarde[block], 16);
status = (MFRC522::StatusCode) mfrc522.MIFARE_Write(block, waarde[block], 16);
if (status != MFRC522::STATUS_OK) {
Serial.print(F("MIFARE_Write() failed: "));
Serial.println(mfrc522.GetStatusCodeName(status));
}
Serial.println("\n");
}
mfrc522.PICC_HaltA(); // Halt PICC
mfrc522.PCD_StopCrypto1(); // Stop encryption on PCD
Serial.println("1.Read card \n2.Write to card \n3.Copy the data.");
start();
}
void keuze1(){ //Read card
Serial.println("Insert card...");
// Look for new cards
if ( ! mfrc522.PICC_IsNewCardPresent())
return;
// Select one of the cards
if ( ! mfrc522.PICC_ReadCardSerial())
return;
// Show some details of the PICC (that is: the tag/card)
Serial.print(F("Card UID:"));
dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
Serial.println();
Serial.print(F("PICC type: "));
MFRC522::PICC_Type piccType = mfrc522.PICC_GetType(mfrc522.uid.sak);
Serial.println(mfrc522.PICC_GetTypeName(piccType));
// Try the known default keys
MFRC522::MIFARE_Key key;
for (byte k = 0; k < NR_KNOWN_KEYS; k++) {
// Copy the known key into the MIFARE_Key structure
for (byte i = 0; i < MFRC522::MF_KEY_SIZE; i++) {
key.keyByte[i] = knownKeys[k][i];
}
// Try the key
if (try_key(&key)) {
// Found and reported on the key and block,
// no need to try other keys for this PICC
break;
}
}
}
Есть проблема: сделал замок на rc522, раздал домашним наклейки ntag213, на которых одинаковый номер uid (шел с завода), по которому, собственно, и велась идентификация. Дочь потеряла (сперли?) брелок с наклейкой пару дней назад, а сегодня буквально за руку поймал малолетнего "медвежатника" с этим брелоком, который решил, что дома никого и открыл дверь на моих глазах.
Посему вопрос: можно ли и каким образом сменить uid на других наклейках на различные, которые потом пропишу в код замка? Наклейки вроде перезаписываемые. Курил гугл, но четкой инфы именно про смену uid в 10-значном формате не нашел...
Гопнег - вообще в любом пособии по РФИД обычно крупными буквами написано, что категорически нельзя строить систему безопасности на значениях UID, так как метки можно копировать и подменять. Так что делать замок на UID - это почти тоже самое что просто не запирать двери или, к примеру. запирать их на сортирный шпингалет. В этот раз дочь потеряла метку, а в следующий более продвинутый медвежатник просто скопирует ее метку потихоньку, пока она отвернулась - вы даже и не узнаете.
Для использования РФИД в качестве электронного замка необходимо привязываться к защищенным полям метки, которые читаются только по паролю. Тогда вашу метку нельзя будет так легко скопировать.
Ну и возвращаясь к первому вопросу - в случае использования защищенных полей РФИД вы сможете записать на каждую метку свой код и в случае утери метки просто заблокировать этот код в программе замка.
Хотела считать информацию со своего пропуска, не читается.
Другие частоты...?
народ пишет, что некоторые карты этим ридером плохо читаются - слегка расстроена антенна. Видел в сети рецепт - необходимо заменить один из конденсаторов на лицевой стороне модуля. Поищите.
ЗЫ а пропуск то какой знакомый, у меня тоже такой когда-то был :) Это не РАН случайно?
В итоге выяснилось, что всё даже хуже: на команде (из наиболее распространенной библиотеки Мигеля Бальбо) mfrc522.PICC_IsNewCardPresent() ардуино
1. без резета - зависает раз в полчаса.
2. с хардварным и софтварным резетом раз в 2 секунды - зависает раз в 7 часов
3. с вот таким полным отключаением питания раз в 4 секунды - не зависает сутки (а мне больше и не надо)
digitalWrite( rfid_VCC ,LOW);
digitalWrite( rfid_RST,LOW); // not connected
digitalWrite( rfid_MISO,LOW);
digitalWrite( rfid_MOSI,LOW);
digitalWrite( rfid_SCK,LOW);
digitalWrite( rfid_SS,LOW);
Добрый день. Подскажите как это сделать -3й вариант - как это прописать в коде. Похоже это мой случай. Подключил RFID RC522 к Arduino UNO - всё работает, но сам модуть RC522 постоянно виснет и помогает только отключение питания всей схемы либо RESET кнопкой на UNO. Сама Arduina при этом продолжает работать - все подвязанные кнопки и выводы работают.
А точно у вас RFID виснет - может просто слишком много задержек в коде? Код-то у вас написан отвратительно, такой код должен непрерывно виснуть - он же считайте 99% времени сидит в задержках.
И еще одно замечание - если вам надо сделать 10 раз одно и то же действие - не надо копировать соответвующий кусок кода десять раз, так программы не пишут. В вашей программе строчки с 237 по 400 - это 15 повторов, которые можно записать строчек в 20 максимум
Я знаю) Код слеплен из разных источников и еще не оптимизирован. Но виснет точно не код, так как ардуина продолжает откликатся на нажатия кнопок и выполнять куски кода связанные с их обработкой. А вот RFID модуль глохнет намертво..=\
У некоторых продавцов на Aliexpresse есть в продаже с перезаписываемым 0 блок и 0 сектором. Ищите там.
брелки или rс522? почему то в интернете есть огромное количество как считать данные, но ни одного(я искал) где идёт запись на "болванку" вот это кстати можно считать болванкой? https://ru.aliexpress.com/item/5PCS-Yellow-RFID-Sensor-Proximity-Card-IC-Key-Tags-Keyfobs-Keychain-13-56MHz/32745066583.html?spm=2114.13010608.0.0.Ha8FpB
Я заказывал у этого продавца на пробу, все работает 0 блок и 0 сектор скопировал с нужной карты и зашил в эти. Теперь у меня есть клон, вдруг дома забыл на работе запасная лежит. https://ru.aliexpress.com/item/Free-Shipping-1pc-13-56MHz-Rfid-PVC-Thin-Uid-Changeable-block-0-writable-Card-1K/1711603036.html?detailNewVersion=&categoryId=303006 Сейас стоит 270 руб 3 штучки по 90 руб за штучку.
С помощью Arduino и модуля RC522 изменил 0 блок 0 сектор.
а есть такие круглые брелки? и какой код должен быть чтобы rc522 генерировала сигнал записи а не только читала инфу с карты.
что то типа этого подойдёт чтобы ключи не вытаскивать из кармана а открыть дверь поднесённым телефоном? https://ru.aliexpress.com/item/10pcs-Lot-NFC-TAG-Sticker-13-56MHz-ISO14443A-NTAG-213-NFC-tag-Universal-Lable-for/32637183249.html?spm=2114.30010608.3.1.aovXwD&ws_ab_test=searchweb0_0,searchweb201602_6_10065_10068_10084_10083_10080_10082_10081_10060_10061_10062_10056_10055_10037_10054_10059_10032_10099_10078_10079_10077_10093_426_10103_10073_10102_10096_10052_10050_10051,searchweb201603_2&btsid=7d239803-3835-4416-8766-d60bdba3955d
эти наклейки из-за малой антенны через пластик уже могут не срабатывать, им нужен прямой контакт. Лучше большую (увеличит дальность) наклейку на обратную сторону крышки аккумулятора. А если телефон в чехле, то сойдет и метрошный одноразовый билетик.
Если в телефоне есть NFC, то никакх брелков и наклеек уже не надо. Я так на работе и в автобусах прохожу %)
ладно есть наклейки наверно побольше
метрошный билетик можно переписать под свой ключ?
допустим такая история, дали ключ от подъезда. этот ключ можно вписать в билет метро? если нет то в какую наклейку можно? nfc в телефоне нет. и ещё есть код чтобы писать в наклейки. всё что я видел это для чтения данных с карты
Некоторые сектора можно, некоторые вшиты намертво.
Какие сектора использует домофон - ведомо только его разработчикам.
ну ключ с брелка, которым двери открываю, я вижу. этот ключ можно клонировать. какая разница что использует домофон, если он видит ключ из базы он должен открыть, я в ларке могу ключ склонировать и там не спрашивают про секторы. просто берут один брелок отдают два
они используют брелки с перезаписываемыми секторами. Ради эксперимента дайти им метрошный билетик, пусть попробуют на него склонировать - вдруг получится? За это денег не берут :)
мы отвлеклись. при чём тут ларёк. есть ардуино, есть брелок с ключем, есть ещё карточка, абсалютно не обязательно метро, чтото подходящее. как один ключ перенести на на другой?
у гугля спросить :)
супер то что искал. спасибо
Киньте пожалуйста библиотеку которая подойдёт к скетчу
#include <RFID.h>
#define RST_PIN 9
#define BLUE_LED 6
#define YELLOW_LED 7
unsigned char master[5] = {164,18,146,184,156}; // allowed card
unsigned char i;
void allow();
void denied();
{
Serial.begin(9600);
SPI.begin();
rfid.init();
pinMode(BLUE_LED, OUTPUT);
pinMode(YELLOW_LED, OUTPUT);
digitalWrite(BLUE_LED, HIGH);
digitalWrite(YELLOW_LED, HIGH);
}
{
if (rfid.isCard())
{
if (rfid.readCardSerial())
{
/* Reading card */
Serial.println(" ");
Serial.println("Card found");
Serial.println("Cardnumber:");
for (i = 0; i < 5; i++)
{
Serial.print(rfid.serNum[i]);
Serial.print(" ");
reading_card[i] = rfid.serNum[i];
}
Serial.println();
//verification
for (i = 0; i < 5; i++)
{
if (reading_card[i]!=master[i])
{
break;
}
}
if (i == 5)
{
allow();
}
else
{
denied();
}
}
}
else{
digitalWrite(YELLOW_LED, HIGH);
// rfid.halt();
}
}
{
Serial.println("Access accept!"); //доступ получен
digitalWrite(YELLOW_LED, LOW);
delay(1000);
}
void denied()
{
Serial.println("Access denied!"); //доступ закрыт
digitalWrite(YELLOW_LED, HIGH);
delay(1000);
}
Всем привет, подскажите, кому-нибудь в проектах пригождалась нога Reset ? хочу ее к VCC подтянуть из соображений экономии ног.
а скетч заливать как будешь?
Какую экономию даст подтяжка Reset к Vcc?
а скетч заливать как будешь?
куда, в RC522?
ыыы, точно! Не туда мысля пошла...
Reset нужен, ибо иногда ридер залипает, а команда halt() дергает именно Reset.
В итоге выяснилось, что всё даже хуже: на команде (из наиболее распространенной библиотеки Мигеля Бальбо) mfrc522.PICC_IsNewCardPresent() ардуино
1. без резета - зависает раз в полчаса.
2. с хардварным и софтварным резетом раз в 2 секунды - зависает раз в 7 часов
3. с вот таким полным отключаением питания раз в 4 секунды - не зависает сутки (а мне больше и не надо)
Подскажите в чем проблема - с библиотекой Мигеля Бальбо все работает, с этой https://github.com/miguelbalboa/rfid не компилируется ни один пример. Ошибка : Arduino: 1.6.4 (Windows 8.1), Плата"Arduino Uno"
странно что эта ошибка вообще вылезла, поиск по UINT8_MAX в папке c:\Program Files\Arduino выдает что оно определяется в stdint.h вот так что, можно не заморачиваясь просто подключить его
странно что эта ошибка вообще вылезла, поиск по UINT8_MAX в папке c:\Program Files\Arduino выдает что оно определяется в stdint.h вот так что, можно не заморачиваясь просто подключить его
Подключал stdint.h - то же самое :(
Доброго времени суток, прошу подсказать кто знает как хранить в памяти номера меток т.к. хочу сделать замок.
Собрал схемку, можно записать все метки но после того как отключить питание и снова подать стираються все из памяти
Может есть готовые решения как прикрутить запись на флешку или хранение в eeprom RFID ключей?
Заранее благодарен за помощь
Думаю, вам пригодится http://arduino.ru/Reference/Library/EEPROM
Думаю, вам пригодится http://arduino.ru/Reference/Library/EEPROM
Спасибо за наводку
Я понимаю что должно в EEPROM записывать но почему-то при выключении Дуня забывает все ключи, в написании кода не силен но в коде, который я заливаю функцию записи в память я вижу . Подскажите пож. в чем тогда может быть проблема. Может в коде ошибка? Спасибо
#include <EEPROM.h> // We are going to read and write PICC's UIDs from/to EEPROM #include <SPI.h> // RC522 Module uses SPI protocol #include <MFRC522.h> // Library for Mifare RC522 Devices #define COMMON_ANODE #ifdef COMMON_ANODE #define LED_ON LOW #define LED_OFF HIGH #else #define LED_ON HIGH #define LED_OFF LOW #endif #define redLed 7 // Set Led Pins #define greenLed 6 #define blueLed 5 #define relay 4 // Set Relay Pin #define wipeB 3 // Button pin for WipeMode, HOLD it then reset arduino for wipe mode. boolean match = false; // initialize card match to false boolean programMode = false; // initialize programming mode to false int successRead; // Variable integer to keep if we have Successful Read from Reader byte storedCard[4]; // Stores an ID read from EEPROM byte readCard[4]; // Stores scanned ID read from RFID Module byte masterCard[4]; // Stores master card's ID read from EEPROM /* We need to define MFRC522's pins and create instance Pin layout should be as follows (on Arduino Uno): MOSI: Pin 11 / ICSP-4 MISO: Pin 12 / ICSP-1 SCK : Pin 13 / ICSP-3 SS : Pin 10 (Configurable) RST : Pin 9 (Configurable) look MFRC522 Library for other Arduinos' pin configuration */ #define SS_PIN 10 #define RST_PIN 9 MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance. ///////////////////////////////////////// Setup /////////////////////////////////// void setup() { //Arduino Pin Configuration pinMode(redLed, OUTPUT); pinMode(greenLed, OUTPUT); pinMode(blueLed, OUTPUT); pinMode(wipeB, INPUT_PULLUP); // Enable pin's pull up resistor pinMode(relay, OUTPUT); //Be careful how relay circuit behave on while resetting or power-cycling your Arduino digitalWrite(relay, HIGH); // Make sure door is locked digitalWrite(redLed, LED_OFF); // Make sure led is off digitalWrite(greenLed, LED_OFF); // Make sure led is off digitalWrite(blueLed, LED_OFF); // Make sure led is off //Protocol Configuration Serial.begin(9600); // Initialize serial communications with PC SPI.begin(); // MFRC522 Hardware uses SPI protocol mfrc522.PCD_Init(); // Initialize MFRC522 Hardware //If you set Antenna Gain to Max it will increase reading distance //mfrc522.PCD_SetAntennaGain(mfrc522.RxGain_max); Serial.println(F("BlueCore Tech Acces Control")); // For debugging purposes ShowReaderDetails(); // Show details of PCD - MFRC522 Card Reader details //Wipe Code if Button Pressed while setup run (powered on) it wipes EEPROM if (digitalRead(wipeB) == LOW) { // when button pressed pin should get low, button connected to ground digitalWrite(redLed, LED_ON); // Red Led stays on to inform user we are going to wipe Serial.println(F("Wipe Button Pressed")); Serial.println(F("You have 5 seconds to Cancel")); Serial.println(F("All records will be removed. This cannot be undone!")); delay(5000); // Give user enough time to cancel operation if (digitalRead(wipeB) == LOW) { // If button still be pressed, wipe EEPROM Serial.println(F("CLEARING DATABASE")); for (int x = 0; x < EEPROM.length(); x = x + 1) { //Loop end of EEPROM address if (EEPROM.read(x) == 0) { //If EEPROM address 0 // do nothing, already clear, go to the next address in order to save time and reduce writes to EEPROM } else { EEPROM.write(x, 0); // if not write 0 to clear, it takes 3.3mS } } Serial.println(F("DATABASE Successfully Wiped")); digitalWrite(redLed, LED_OFF); // visualize successful wipe delay(200); digitalWrite(redLed, LED_ON); delay(200); digitalWrite(redLed, LED_OFF); delay(200); digitalWrite(redLed, LED_ON); delay(200); digitalWrite(redLed, LED_OFF); } else { Serial.println(F("Wiping Cancelled")); digitalWrite(redLed, LED_OFF); } } // Check if master card defined, if not let user choose a master card // This also useful to just redefine Master Card // You can keep other EEPROM records just write other than 143 to EEPROM address 1 // EEPROM address 1 should hold magical number which is '143' if (EEPROM.read(1) != 143) { Serial.println(F("No Master Card Set")); Serial.println(F("Scan A RFID Card to Set as Master Card")); do { successRead = getID(); // sets successRead to 1 when we get read from reader otherwise 0 digitalWrite(blueLed, LED_ON); // Visualize Master Card need to be defined delay(200); digitalWrite(blueLed, LED_OFF); delay(200); } while (!successRead); // Program will not go further while you not get a successful read for ( int j = 0; j < 4; j++ ) { // Loop 4 times EEPROM.write( 2 + j, readCard[j] ); // Write scanned PICC's UID to EEPROM, start from address 3 } EEPROM.write(1, 143); // Write to EEPROM we defined Master Card. Serial.println(F("Master Card Set")); } Serial.println(F("-------------------")); Serial.println(F("Master Card's UID = ")); for ( int i = 0; i < 4; i++ ) { // Read Master Card's UID from EEPROM masterCard[i] = EEPROM.read(2 + i); // Write it to masterCard Serial.print(masterCard[i], HEX); } Serial.println(""); Serial.println(F("-------------------")); Serial.println(F("Everything Ready")); Serial.println(F("Waiting for Keys or cards to be scanned")); cycleLeds(); // Everything ready lets give user some feedback by cycling leds } ///////////////////////////////////////// Main Loop /////////////////////////////////// void loop () { do { successRead = getID(); // sets successRead to 1 when we get read from reader otherwise 0 if (programMode) { cycleLeds(); // Program Mode cycles through RGB waiting to read a new card } else { normalModeOn(); // Normal mode, blue Power LED is on, all others are off } } while (!successRead); //the program will not go further while you not get a successful read if (programMode) { if ( isMaster(readCard) ) { //If master card scanned again exit program mode Serial.println(F("Master Card Scanned")); Serial.println(F("Exiting Programming Mode")); Serial.println(F("-----------------------------")); programMode = false; return; } else { if ( findID(readCard) ) { // If scanned card is known delete it Serial.println(F("I know this key, removing...")); deleteID(readCard); Serial.println("-----------------------------"); } else { // If scanned card is not known add it Serial.println(F("I do not know this key, adding...")); writeID(readCard); Serial.println(F("-----------------------------")); } } } else { if ( isMaster(readCard) ) { // If scanned card's ID matches Master Card's ID enter program mode programMode = true; Serial.println(F("Hello Master - Entered Programming Mode")); int count = EEPROM.read(0); // Read the first Byte of EEPROM that Serial.print(F("I have ")); // stores the number of ID's in EEPROM Serial.print(count); Serial.print(F(" record(s) in DATABASE")); Serial.println(""); Serial.println(F("Scan a Card or key to ADD or REMOVE")); Serial.println(F("-----------------------------")); } else { if ( findID(readCard) ) { // If not, see if the card is in the EEPROM Serial.println(F("Welcome, Acces Granted")); granted(300); // Open the door lock for 300 ms } else { // If not, show that the ID was not valid Serial.println(F("Acces Denied!")); denied(); } } } } ///////////////////////////////////////// Access Granted /////////////////////////////////// void granted (int setDelay) { digitalWrite(blueLed, LED_OFF); // Turn off blue LED digitalWrite(redLed, LED_OFF); // Turn off red LED digitalWrite(greenLed, LED_ON); // Turn on green LED digitalWrite(relay, LOW); // Unlock door! delay(4000); // Hold door lock open for given seconds digitalWrite(relay, HIGH); // Relock door delay(1000); // Hold green LED on for a second } ///////////////////////////////////////// Access Denied /////////////////////////////////// void denied() { digitalWrite(greenLed, LED_OFF); // Make sure green LED is off digitalWrite(blueLed, LED_OFF); // Make sure blue LED is off digitalWrite(redLed, LED_ON); // Turn on red LED delay(1000); } ///////////////////////////////////////// Get PICC's UID /////////////////////////////////// int getID() { // Getting ready for Reading PICCs if ( ! mfrc522.PICC_IsNewCardPresent()) { //If a new PICC placed to RFID reader continue return 0; } if ( ! mfrc522.PICC_ReadCardSerial()) { //Since a PICC placed get Serial and continue return 0; } // There are Mifare PICCs which have 4 byte or 7 byte UID care if you use 7 byte PICC // I think we should assume every PICC as they have 4 byte UID // Until we support 7 byte PICCs Serial.println(F("Scanned KEY's UID:")); for (int i = 0; i < 4; i++) { // readCard[i] = mfrc522.uid.uidByte[i]; Serial.print(readCard[i], HEX); } Serial.println(""); mfrc522.PICC_HaltA(); // Stop reading return 1; } void ShowReaderDetails() { // Get the MFRC522 software version byte v = mfrc522.PCD_ReadRegister(mfrc522.VersionReg); Serial.print(F("MFRC522 Version: 0x")); Serial.print(v, HEX); if (v == 0x91) Serial.print(F(" = v1.0")); else if (v == 0x11) Serial.print(F(" = BlueCore Tech. RFID Acces v2.0")); else Serial.print(F(" (unknown)")); Serial.println(""); // When 0x00 or 0xFF is returned, communication probably failed if ((v == 0x00) || (v == 0xFF)) { Serial.println(F("WARNING: Communication failure, is the RFID-MFRC522 properly connected?")); while(true); // do not go further } } ///////////////////////////////////////// Cycle Leds (Program Mode) /////////////////////////////////// void cycleLeds() { digitalWrite(redLed, LED_OFF); // Make sure red LED is off digitalWrite(greenLed, LED_ON); // Make sure green LED is on digitalWrite(blueLed, LED_OFF); // Make sure blue LED is off delay(200); digitalWrite(redLed, LED_OFF); // Make sure red LED is off digitalWrite(greenLed, LED_OFF); // Make sure green LED is off digitalWrite(blueLed, LED_ON); // Make sure blue LED is on delay(200); digitalWrite(redLed, LED_ON); // Make sure red LED is on digitalWrite(greenLed, LED_OFF); // Make sure green LED is off digitalWrite(blueLed, LED_OFF); // Make sure blue LED is off delay(200); } //////////////////////////////////////// Normal Mode Led /////////////////////////////////// void normalModeOn () { digitalWrite(blueLed, LED_ON); // Blue LED ON and ready to read card digitalWrite(redLed, LED_OFF); // Make sure Red LED is off digitalWrite(greenLed, LED_OFF); // Make sure Green LED is off digitalWrite(relay, HIGH); // Make sure Door is Locked } //////////////////////////////////////// Read an ID from EEPROM ////////////////////////////// void readID( int number ) { int start = (number * 4 ) + 2; // Figure out starting position for ( int i = 0; i < 4; i++ ) { // Loop 4 times to get the 4 Bytes storedCard[i] = EEPROM.read(start + i); // Assign values read from EEPROM to array } } ///////////////////////////////////////// Add ID to EEPROM /////////////////////////////////// void writeID( byte a[] ) { if ( !findID( a ) ) { // Before we write to the EEPROM, check to see if we have seen this card before! int num = EEPROM.read(0); // Get the numer of used spaces, position 0 stores the number of ID cards int start = ( num * 4 ) + 6; // Figure out where the next slot starts num++; // Increment the counter by one EEPROM.write( 0, num ); // Write the new count to the counter for ( int j = 0; j < 4; j++ ) { // Loop 4 times EEPROM.write( start + j, a[j] ); // Write the array values to EEPROM in the right position } successWrite(); Serial.println(F("Succesfully added ID record to DATABASE")); } else { failedWrite(); Serial.println(F("Failed! There is something wrong with ID or bad DATABASE")); } } ///////////////////////////////////////// Remove ID from EEPROM /////////////////////////////////// void deleteID( byte a[] ) { if ( !findID( a ) ) { // Before we delete from the EEPROM, check to see if we have this card! failedWrite(); // If not Serial.println(F("Failed! There is something wrong with ID or bad DATABASE")); } else { int num = EEPROM.read(0); // Get the numer of used spaces, position 0 stores the number of ID cards int slot; // Figure out the slot number of the card int start; // = ( num * 4 ) + 6; // Figure out where the next slot starts int looping; // The number of times the loop repeats int j; int count = EEPROM.read(0); // Read the first Byte of EEPROM that stores number of cards slot = findIDSLOT( a ); // Figure out the slot number of the card to delete start = (slot * 4) + 2; looping = ((num - slot) * 4); num--; // Decrement the counter by one EEPROM.write( 0, num ); // Write the new count to the counter for ( j = 0; j < looping; j++ ) { // Loop the card shift times EEPROM.write( start + j, EEPROM.read(start + 4 + j)); // Shift the array values to 4 places earlier in the EEPROM } for ( int k = 0; k < 4; k++ ) { // Shifting loop EEPROM.write( start + j + k, 0); } successDelete(); Serial.println(F("Succesfully removed ID record from DATABASE")); } } ///////////////////////////////////////// Check Bytes /////////////////////////////////// boolean checkTwo ( byte a[], byte b[] ) { if ( a[0] != NULL ) // Make sure there is something in the array first match = true; // Assume they match at first for ( int k = 0; k < 4; k++ ) { // Loop 4 times if ( a[k] != b[k] ) // IF a != b then set match = false, one fails, all fail match = false; } if ( match ) { // Check to see if if match is still true return true; // Return true } else { return false; // Return false } } ///////////////////////////////////////// Find Slot /////////////////////////////////// int findIDSLOT( byte find[] ) { int count = EEPROM.read(0); // Read the first Byte of EEPROM that for ( int i = 1; i <= count; i++ ) { // Loop once for each EEPROM entry readID(i); // Read an ID from EEPROM, it is stored in storedCard[4] if ( checkTwo( find, storedCard ) ) { // Check to see if the storedCard read from EEPROM // is the same as the find[] ID card passed return i; // The slot number of the card break; // Stop looking we found it } } } ///////////////////////////////////////// Find ID From EEPROM /////////////////////////////////// boolean findID( byte find[] ) { int count = EEPROM.read(0); // Read the first Byte of EEPROM that for ( int i = 1; i <= count; i++ ) { // Loop once for each EEPROM entry readID(i); // Read an ID from EEPROM, it is stored in storedCard[4] if ( checkTwo( find, storedCard ) ) { // Check to see if the storedCard read from EEPROM return true; break; // Stop looking we found it } else { // If not, return false } } return false; } ///////////////////////////////////////// Write Success to EEPROM /////////////////////////////////// // Flashes the green LED 3 times to indicate a successful write to EEPROM void successWrite() { digitalWrite(blueLed, LED_OFF); // Make sure blue LED is off digitalWrite(redLed, LED_OFF); // Make sure red LED is off digitalWrite(greenLed, LED_OFF); // Make sure green LED is on delay(200); digitalWrite(greenLed, LED_ON); // Make sure green LED is on delay(200); digitalWrite(greenLed, LED_OFF); // Make sure green LED is off delay(200); digitalWrite(greenLed, LED_ON); // Make sure green LED is on delay(200); digitalWrite(greenLed, LED_OFF); // Make sure green LED is off delay(200); digitalWrite(greenLed, LED_ON); // Make sure green LED is on delay(200); } ///////////////////////////////////////// Write Failed to EEPROM /////////////////////////////////// // Flashes the red LED 3 times to indicate a failed write to EEPROM void failedWrite() { digitalWrite(blueLed, LED_OFF); // Make sure blue LED is off digitalWrite(redLed, LED_OFF); // Make sure red LED is off digitalWrite(greenLed, LED_OFF); // Make sure green LED is off delay(200); digitalWrite(redLed, LED_ON); // Make sure red LED is on delay(200); digitalWrite(redLed, LED_OFF); // Make sure red LED is off delay(200); digitalWrite(redLed, LED_ON); // Make sure red LED is on delay(200); digitalWrite(redLed, LED_OFF); // Make sure red LED is off delay(200); digitalWrite(redLed, LED_ON); // Make sure red LED is on delay(200); } ///////////////////////////////////////// Success Remove UID From EEPROM /////////////////////////////////// // Flashes the blue LED 3 times to indicate a success delete to EEPROM void successDelete() { digitalWrite(blueLed, LED_OFF); // Make sure blue LED is off digitalWrite(redLed, LED_OFF); // Make sure red LED is off digitalWrite(greenLed, LED_OFF); // Make sure green LED is off delay(200); digitalWrite(blueLed, LED_ON); // Make sure blue LED is on delay(200); digitalWrite(blueLed, LED_OFF); // Make sure blue LED is off delay(200); digitalWrite(blueLed, LED_ON); // Make sure blue LED is on delay(200); digitalWrite(blueLed, LED_OFF); // Make sure blue LED is off delay(200); digitalWrite(blueLed, LED_ON); // Make sure blue LED is on delay(200); } ////////////////////// Check readCard IF is masterCard /////////////////////////////////// // Check to see if the ID passed is the master programing card boolean isMaster( byte test[] ) { if ( checkTwo( test, masterCard ) ) return true; else return false; }Сорри разобрался, был не внимателен с кнопкой сброса
Подскажите пожалуйста какиеми ключами более надежно пользоваться 125 кГц или 13,56 мГц
Идея сделать замок на калитку во двор на метках , нужно установить антивандальную антену и что-то от наводок
Может у кого есть наработки на эту тему что посоветуете ? На что обратить внимание ?
Ещё вопрос как понять сколько можно ключей записать в ПЗУ ?
Прошу помощи сообщества.
Пробую подключить RFID RC522 совместно с NANO V3.0. Подключаю библиотеку, соединяю все как в скетче. Пробовал RFID-модуль запитывать от NANO и от отдельного источника. Ни в какую не считывается. В чем проблема?
Уже второй модуль RFID купил. Так и не хочет работать. Где подводный камень?
мошт, ключи на 125 кГц?
Ключи использовал из комплекта к модулям.
а распаяли как? схему откуда брали? Штуки четыре к мне приходила RFIDfа, вместе на Nano прекрасно все работают. Пробовали стандартные примеры из библиотеки?
нужно локализовать проблему: в стандартном примере функция ShowReaderDetails() - выводит номер версии ридера. если он выдает некорректную информацию, значит ридер подключен к ардуине неправильно и нужно решать проблему с подключением, а потом уже за ключи браться.
День добрый.
Подскажите новичку... Правильно ли я понял. У меня у домофонного ключа читается все, кроме нулевого сектора. Картина такая:
какой ключ?
Хм... Я спрашивл правильно ли я понял, а вы - какой ключ...
Информацию о существовании неких ключей я нашел в нет-е.
Мол хранятся в нулевом секторе и позволяют при таких ограничениях читать/записывать нулевой сектор...
"У меня у домофонного ключа читается все, кроме нулевого сектора" - вот я и интересуюсь какой именно у вас домофонный ключ.
Я вас неправильно понял. Какой именно ключ - не знаю.
Но раз почти все читается, логично предположить, что такой же как те, что шли в комплекте с RC522, только закрыт/зашифрован нулевой сектор.
https://github.com/miguelbalboa/rfid библа со множеством примеров
но не копмилируется скетч RFID-Cloner
Подправите не в ущерб функционалу?
Вечер в хату, уважаемые!
Есть проблема: сделал замок на rc522, раздал домашним наклейки ntag213, на которых одинаковый номер uid (шел с завода), по которому, собственно, и велась идентификация. Дочь потеряла (сперли?) брелок с наклейкой пару дней назад, а сегодня буквально за руку поймал малолетнего "медвежатника" с этим брелоком, который решил, что дома никого и открыл дверь на моих глазах.
Посему вопрос: можно ли и каким образом сменить uid на других наклейках на различные, которые потом пропишу в код замка? Наклейки вроде перезаписываемые. Курил гугл, но четкой инфы именно про смену uid в 10-значном формате не нашел...
Подскажите, плз, кто что знаеет.
Гопнег - вообще в любом пособии по РФИД обычно крупными буквами написано, что категорически нельзя строить систему безопасности на значениях UID, так как метки можно копировать и подменять. Так что делать замок на UID - это почти тоже самое что просто не запирать двери или, к примеру. запирать их на сортирный шпингалет. В этот раз дочь потеряла метку, а в следующий более продвинутый медвежатник просто скопирует ее метку потихоньку, пока она отвернулась - вы даже и не узнаете.
Для использования РФИД в качестве электронного замка необходимо привязываться к защищенным полям метки, которые читаются только по паролю. Тогда вашу метку нельзя будет так легко скопировать.
Ну и возвращаясь к первому вопросу - в случае использования защищенных полей РФИД вы сможете записать на каждую метку свой код и в случае утери метки просто заблокировать этот код в программе замка.
Разобрался с проблемой. Благодарю.
Хотела считать информацию со своего пропуска, не читается.
Другие частоты...?
125 кГц?
Такой купить?
125 кГц?
Такой купить?
К сехретному заводу пропуска клонировать собрались?))))
Хотела считать информацию со своего пропуска, не читается.
Другие частоты...?
народ пишет, что некоторые карты этим ридером плохо читаются - слегка расстроена антенна. Видел в сети рецепт - необходимо заменить один из конденсаторов на лицевой стороне модуля. Поищите.
ЗЫ а пропуск то какой знакомый, у меня тоже такой когда-то был :) Это не РАН случайно?
Школьный пропуск, без обложки)
Вы про RC522, плохо читает?
Или про EM4100
Ещё есть RDM6300
Хотела считать информацию со своего пропуска, не читается.
Другие частоты...?
Да. Это 125КГц, этот ридер не берет такое. Ему 13.56МГц хочется, майфер какой или фелицию.
Здравствуйте. Возникла необходимость работы с картами Icode Slix (SL2S2002) от NXP . Работает ли модуль RC522 с такими?
если нет, то какие ардуиносовместимые недорогие модули нужно использовать?
Может у вас есть какие-то материалы и библиотеки, расшифровывающие данные, буду рад любой помощи.
Бывают ли такие карты перезаписываемые болванки и где их купить (желательно не китай, а NXP) ?
"У меня у домофонного ключа читается все, кроме нулевого сектора" - вот я и интересуюсь какой именно у вас домофонный ключ.
В итоге выяснилось, что всё даже хуже: на команде (из наиболее распространенной библиотеки Мигеля Бальбо) mfrc522.PICC_IsNewCardPresent() ардуино
1. без резета - зависает раз в полчаса.
2. с хардварным и софтварным резетом раз в 2 секунды - зависает раз в 7 часов
3. с вот таким полным отключаением питания раз в 4 секунды - не зависает сутки (а мне больше и не надо)
Добрый день. Подскажите как это сделать -3й вариант - как это прописать в коде. Похоже это мой случай. Подключил RFID RC522 к Arduino UNO - всё работает, но сам модуть RC522 постоянно виснет и помогает только отключение питания всей схемы либо RESET кнопкой на UNO. Сама Arduina при этом продолжает работать - все подвязанные кнопки и выводы работают.
#include <SPI.h> #include <MFRC522.h> // библиотека "RFID". #define tonePin 5 #define zamok 6 #define buttonZvonok 7 #define buttonZamok 8 #define RST_PIN 9 #define SS_PIN 10 #define c3 7634 #define d3 6803 #define e3 6061 #define f3 5714 #define g3 5102 #define a3 4545 #define b3 4049 #define c4 3816 #define d4 3401 #define e4 3030 #define f4 2865 #define g4 2551 #define a4 2272 #define a4s 2146 #define b4 2028 #define c5 1912 #define d5 1706 #define d5s 1608 #define e5 1517 #define f5 1433 #define g5 1276 #define a5 1136 #define a5s 1073 #define b5 1012 #define c6 955 #define R 0 MFRC522 mfrc522(SS_PIN, RST_PIN); unsigned long uidDec, uidDecTemp; // для храниения номера метки в десятичном формате int melody2[] = {f4, f4, f4, a4s, f5, d5s, d5, c5, a5s, f5, d5s, d5, c5, a5s, f5, d5s, d5, d5s, c5}; int beats2[] = {21, 21, 21, 128, 128, 21, 21, 21, 128, 64, 21, 21, 21, 128, 64, 21, 21, 21, 128}; long tempo = 10000; int rest_count = 50; int toneM = 0; int beat = 0; long duration = 0; int MAX_COUNT2 = sizeof(melody2) / 2; int buttonState = 0; // переменная для хранения состояния кнопки int DelaySound = 500; // Пауза 0.5 секунды void setup() { Serial.begin(9600); Serial.println("Waiting for card..."); SPI.begin(); // инициализация SPI / Init SPI bus. mfrc522.PCD_Init(); // инициализация MFRC522 / Init MFRC522 card. pinMode(zamok, OUTPUT); // инициализация пина управления замком digitalWrite(zamok, LOW); // установка этого пина в 0 pinMode(buttonZvonok, INPUT); // инициализация пина кнопки pinMode(buttonZamok, INPUT); // инициализация пина кнопки pinMode(tonePin, OUTPUT); // инициализация пина Спикера } void playTone() { long elapsed_time = 0; if (toneM > 0) { while (elapsed_time < duration) { digitalWrite(tonePin,HIGH); delayMicroseconds(toneM / 2); digitalWrite(tonePin, LOW); delayMicroseconds(toneM / 2); elapsed_time += (toneM); } } else { for (int j = 0; j < rest_count; j++) { delayMicroseconds(duration); } } } void loop() { /* delay(4000); digitalWrite( rfid_VCC ,LOW); digitalWrite( rfid_RST,LOW); // not connected digitalWrite( rfid_MISO,LOW); digitalWrite( rfid_MOSI,LOW); digitalWrite( rfid_SCK,LOW); digitalWrite( rfid_SS,LOW); */ buttonState = digitalRead(buttonZvonok); // считываем значения с входа кнопки if(buttonState == HIGH){ // если нажата, то buttonState будет HIGH for (int i=0; i<MAX_COUNT2; i++) { //звонок toneM = melody2[i]; beat = beats2[i]; duration = beat * tempo; playTone(); delayMicroseconds(DelaySound*2);} delay(100); } buttonState = digitalRead(buttonZamok); // считываем значения с входа кнопки if(buttonState == HIGH){ // если нажата, то buttonState будет HIGH Serial.println("Open Door"); tone(tonePin, 200, 500); // Делаем звуковой сигнал, Открытие digitalWrite(zamok, HIGH); // Открываем замок delay(1000); // пауза digitalWrite(zamok, LOW); // возврат в режим ожидания tone(tonePin, 500, 500); // Делаем звуковой сигнал, Закрыт delay(3000); // пауза } if ( ! mfrc522.PICC_IsNewCardPresent()) {return;} // Поиск новой метки if ( ! mfrc522.PICC_ReadCardSerial()) {return;} // Выбор метки - Считывание uidDec = 0; for (byte i = 0; i < mfrc522.uid.size; i++) // Выдача серийного номера метки. { uidDecTemp = mfrc522.uid.uidByte[i]; uidDec = uidDec * 256 + uidDecTemp; } //Serial.println("Card UID: "); //Serial.println(uidDec); // Выводим UID метки в консоль. switch(uidDec) { case 2854147817: // Сравниваем Uid метки { Serial.println("MasterCard Activated! "); tone(tonePin, 200, 500); // Делаем звуковой сигнал, Открытие digitalWrite(zamok, HIGH); // Открываем замок delay(1000); // пауза digitalWrite(zamok, LOW); // возврат в режим ожидания tone(tonePin, 500, 500); // Делаем звуковой сигнал, Закрыт delay(3000); // пауза } break; case 107948874: // Сравниваем Uid метки { Serial.println("Activated Uid №0 "); tone(tonePin, 200, 500); // Делаем звуковой сигнал, Открытие digitalWrite(zamok, HIGH); // Открываем замок delay(1000); // пауза digitalWrite(zamok, LOW); // возврат в режим ожидания tone(tonePin, 500, 500); // Делаем звуковой сигнал, Закрыт delay(3000); // пауза } break; case 589333868: // Сравниваем Uid метки { Serial.println("Activated Uid №1 "); tone(tonePin, 200, 500); // Делаем звуковой сигнал, Открытие digitalWrite(zamok, HIGH); // Открываем замок delay(1000); // пауза digitalWrite(zamok, LOW); // возврат в режим ожидания // Star Wars forever ! tone(tonePin, 392, 350); delay(350); tone(tonePin, 392, 350); delay(350); tone(tonePin, 392, 350); delay(350); tone(tonePin, 311, 250); delay(250); tone(tonePin, 466, 100); delay(100); tone(tonePin, 392, 350); delay(350); tone(tonePin, 311, 250); delay(250); tone(tonePin, 466, 100); delay(100); tone(tonePin, 392, 700); delay(700); tone(tonePin, 587, 350); delay(350); tone(tonePin, 587, 350); delay(350); tone(tonePin, 587, 350); delay(350); tone(tonePin, 622, 250); delay(250); tone(tonePin, 466, 100); delay(100); tone(tonePin, 369, 350); delay(350); tone(tonePin, 311, 250); delay(250); tone(tonePin, 466, 100); delay(100); tone(tonePin, 392, 700); delay(700); tone(tonePin, 784, 350); delay(350); tone(tonePin, 392, 250); delay(250); tone(tonePin, 392, 100); delay(100); tone(tonePin, 784, 350); delay(350); tone(tonePin, 739, 250); delay(250); tone(tonePin, 698, 100); delay(100); tone(tonePin, 659, 100); delay(100); tone(tonePin, 622, 100); delay(100); tone(tonePin, 659, 450); delay(450); tone(tonePin, 415, 150); delay(150); tone(tonePin, 554, 350); delay(350); tone(tonePin, 523, 250); delay(250); tone(tonePin, 493, 100); delay(100); tone(tonePin, 466, 100); delay(100); tone(tonePin, 440, 100); delay(100); tone(tonePin, 466, 450); delay(450); tone(tonePin, 311, 150); delay(150); tone(tonePin, 369, 350); delay(350); tone(tonePin, 311, 250); delay(250); tone(tonePin, 466, 100); delay(100); tone(tonePin, 392, 750); delay(750); } break; case 62422892: // Сравниваем Uid метки { Serial.println("Activated Uid №2 "); tone(tonePin, 200, 500); // Делаем звуковой сигнал, Открытие digitalWrite(zamok, HIGH); // Открываем замок delay(1000); // пауза digitalWrite(zamok, LOW); // возврат в режим ожидания tone(tonePin, 500, 500); // Делаем звуковой сигнал, Закрыт delay(3000); // пауза } break; case 2254900729: // Сравниваем Uid метки { Serial.println("Activated Uid №3 "); tone(tonePin, 200, 500); // Делаем звуковой сигнал, Открытие digitalWrite(zamok, HIGH); // Открываем замок delay(1000); // пауза digitalWrite(zamok, LOW); // возврат в режим ожидания tone(tonePin, 500, 500); // Делаем звуковой сигнал, Закрыт delay(3000); // пауза } break; case 3872380725: // Сравниваем Uid метки { Serial.println("Activated Uid №4"); tone(tonePin, 200, 500); // Делаем звуковой сигнал, Открытие digitalWrite(zamok, HIGH); // Открываем замок delay(1000); // пауза digitalWrite(zamok, LOW); // возврат в режим ожидания tone(tonePin, 500, 500); // Делаем звуковой сигнал, Закрыт delay(3000); // пауза } break; case 2794969653: // Сравниваем Uid метки { Serial.println("Activated Uid №5 "); tone(tonePin, 200, 500); // Делаем звуковой сигнал, Открытие digitalWrite(zamok, HIGH); // Открываем замок delay(1000); // пауза digitalWrite(zamok, LOW); // возврат в режим ожидания tone(tonePin, 500, 500); // Делаем звуковой сигнал, Закрыт delay(3000); // пауза } break; case 1567200011: // Сравниваем Uid метки { Serial.println("Activated Uid №6 "); tone(tonePin, 200, 500); // Делаем звуковой сигнал, Открытие digitalWrite(zamok, HIGH); // Открываем замок delay(1000); // пауза digitalWrite(zamok, LOW); // возврат в режим ожидания tone(tonePin, 500, 500); // Делаем звуковой сигнал, Закрыт delay(3000); // пауза } break; case 2372643851: // Сравниваем Uid метки { Serial.println("Activated Uid №7 "); tone(tonePin, 200, 500); // Делаем звуковой сигнал, Открытие digitalWrite(zamok, HIGH); // Открываем замок delay(1000); // пауза digitalWrite(zamok, LOW); // возврат в режим ожидания tone(tonePin, 500, 500); // Делаем звуковой сигнал, Закрыт delay(3000); // пауза } break; case 2475988844: // Сравниваем Uid метки { Serial.println("Activated Uid №8 "); tone(tonePin, 200, 500); // Делаем звуковой сигнал, Открытие digitalWrite(zamok, HIGH); // Открываем замок delay(1000); // пауза digitalWrite(zamok, LOW); // возврат в режим ожидания tone(tonePin, 500, 500); // Делаем звуковой сигнал, Закрыт delay(3000); // пауза } break; case 225747723: // Сравниваем Uid метки { Serial.println("Activated Uid №9 "); tone(tonePin, 200, 500); // Делаем звуковой сигнал, Открытие digitalWrite(zamok, HIGH); // Открываем замок delay(1000); // пауза digitalWrite(zamok, LOW); // возврат в режим ожидания tone(tonePin, 500, 500); // Делаем звуковой сигнал, Закрыт delay(3000); // пауза } break; case 1183243573: // Сравниваем Uid метки { Serial.println("Activated Uid №10 "); tone(tonePin, 200, 500); // Делаем звуковой сигнал, Открытие digitalWrite(zamok, HIGH); // Открываем замок delay(1000); // пауза digitalWrite(zamok, LOW); // возврат в режим ожидания tone(tonePin, 500, 500); // Делаем звуковой сигнал, Закрыт delay(3000); // пауза } break; case 1570480139: // Сравниваем Uid метки { Serial.println("Activated Uid №11 "); tone(tonePin, 200, 500); // Делаем звуковой сигнал, Открытие digitalWrite(zamok, HIGH); // Открываем замок delay(1000); // пауза digitalWrite(zamok, LOW); // возврат в режим ожидания tone(tonePin, 500, 500); // Делаем звуковой сигнал, Закрыт delay(3000); // пауза } break; case 3325480757: // Сравниваем Uid метки { Serial.println("Activated Uid №12 "); tone(tonePin, 200, 500); // Делаем звуковой сигнал, Открытие digitalWrite(zamok, HIGH); // Открываем замок delay(1000); // пауза digitalWrite(zamok, LOW); // возврат в режим ожидания tone(tonePin, 500, 500); // Делаем звуковой сигнал, Закрыт delay(3000); // пауза } break; case 3809443948: // Сравниваем Uid метки { Serial.println("Activated Uid №13 "); tone(tonePin, 200, 500); // Делаем звуковой сигнал, Открытие digitalWrite(zamok, HIGH); // Открываем замок delay(1000); // пауза digitalWrite(zamok, LOW); // возврат в режим ожидания tone(tonePin, 500, 500); // Делаем звуковой сигнал, Закрыт delay(3000); // пауза } break; case 1992022837: // Сравниваем Uid метки { Serial.println("Activated Uid №14 "); tone(tonePin, 200, 500); // Делаем звуковой сигнал, Открытие digitalWrite(zamok, HIGH); // Открываем замок delay(1000); // пауза digitalWrite(zamok, LOW); // возврат в режим ожидания tone(tonePin, 500, 500); // Делаем звуковой сигнал, Закрыт delay(3000); // пауза } break; case 1981007925: // Сравниваем Uid метки { Serial.println("Activated Uid №15 "); tone(tonePin, 200, 500); // Делаем звуковой сигнал, Открытие digitalWrite(zamok, HIGH); // Открываем замок delay(1000); // пауза digitalWrite(zamok, LOW); // возврат в режим ожидания tone(tonePin, 500, 500); // Делаем звуковой сигнал, Закрыт delay(3000); // пауза } break; case 2634521611: // Сравниваем Uid метки { Serial.println("Activated Uid №16 "); tone(tonePin, 200, 500); // Делаем звуковой сигнал, Открытие digitalWrite(zamok, HIGH); // Открываем замок delay(1000); // пауза digitalWrite(zamok, LOW); // возврат в режим ожидания tone(tonePin, 500, 500); // Делаем звуковой сигнал, Закрыт delay(3000); // пауза } break; default: { Serial.println("Card UID: "); Serial.println(uidDec); // Выводим UID метки в консоль. Serial.println("Доступ запрещён!"); tone(tonePin, 1500); delay(DelaySound/4); noTone(tonePin); delay(DelaySound/4); tone(tonePin, 1500); delay(DelaySound/4); noTone(tonePin); delay(3000); // пауза } } }А точно у вас RFID виснет - может просто слишком много задержек в коде? Код-то у вас написан отвратительно, такой код должен непрерывно виснуть - он же считайте 99% времени сидит в задержках.
И еще одно замечание - если вам надо сделать 10 раз одно и то же действие - не надо копировать соответвующий кусок кода десять раз, так программы не пишут. В вашей программе строчки с 237 по 400 - это 15 повторов, которые можно записать строчек в 20 максимум
Я знаю) Код слеплен из разных источников и еще не оптимизирован. Но виснет точно не код, так как ардуина продолжает откликатся на нажатия кнопок и выполнять куски кода связанные с их обработкой. А вот RFID модуль глохнет намертво..=\