Electronic lock for arduino nano. Making an RFID lock using Arduino

In this lesson, we will learn how to make a simple system that will unlock the lock using an electronic key (Tag).

In the future, you can modify and expand the functionality. For example, add the function "add new keys and remove them from memory". In the basic case, consider a simple example, when a unique key identifier is preset in the program code.

In this tutorial we will need:

To implement the project, we need to install the libraries:

2) Now you need to connect a Buzzer, which will give a signal if the key is triggered and the lock opens, and a second signal when the lock is closed.

We connect the buzzer in the following sequence:

Arduino Buzzer
5V VCC
GND GND
pin 5 IO

3) The servo will be used as an unlocking mechanism. Any servo can be chosen, depending on the dimensions and forces required by you, which the servo creates. The servo has 3 pins:

More clearly, you can see how we connected all the modules in the picture below:

Now, if everything is connected, then you can proceed to programming.

Sketch:

#include #include #include // "RFID" library. #define SS_PIN 10 #define RST_PIN 9 MFRC522 mfrc522 (SS_PIN, RST_PIN); unsigned long uidDec, uidDecTemp; // to store the label number in decimal format Servo servo; void setup () (Serial.begin (9600); Serial.println ("Waiting for card ..."); SPI.begin (); // initialization SPI / Init SPI bus.mfrc522.PCD_Init (); // initialization MFRC522 / Init MFRC522 card.servo.attach (6); servo.write (0); // set the servo to closed) void loop () (// Find a new label if (! Mfrc522.PICC_IsNewCardPresent ()) (return; ) // Select a label if (! Mfrc522.PICC_ReadCardSerial ()) (return;) uidDec = 0; // Issue the serial number of the label.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 метки в консоль. if (uidDec == 3763966293) // Сравниваем Uid метки, если он равен заданому то серва открывает. { tone(5, 200, 500); // Делаем звуковой сигнал, Открытие servo.write(90); // Поворациваем серву на угол 90 градусов(Отпираем какой либо механизм: задвижку, поворациваем ключ и т.д.) delay(3000); // пауза 3 сек и механизм запирается. tone(5, 500, 500); // Делаем звуковой сигнал, Закрытие } servo.write(0); // устанавливаем серву в закрытое сосотояние }

Let's take a closer look at the sketch:

In order to find out the UID of the card (Tags), you need to write this sketch to arduino, assemble the circuit described above, and open the Console (Serial port monitoring). When you bring the tag to the RFID, a number will be displayed in the console

The resulting UID must be entered in the following line:

If (uidDec == 3763966293) // Compare the Uid of the label, if it is equal to the given one then the servo opens the valve.

Each card has a unique identifier and does not repeat itself. Thus, when you bring the card, the identifier of which you have set in the program, the system will open access using a servo drive.

Video:

Arduino is the best system for copying any hardware. Most ideas would not have been possible without her. There has long been such a thought: to create a special combination lock on the arduino. To open it, you need to hold down a certain key. In this case, the lock should not open, even if you know the desired button. To open it, it is necessary to maintain certain intervals using muscle memory. Such a criminal cannot do. But this is all just theory.

To collect it, you need to use a special device of rectangular pulses, as well as several counters and a heap. But the finished device would have large dimensions and would be inconvenient to use. As a rule, such thoughts do not give rest. The first step in making this dream come true was the creation of a program for Arduino. It is she who will serve as a combination lock. In order to open it, you need to press not one key, but several, and do it simultaneously. The finished circuit looks like this:

The picture quality is not the best, but connections are made to ground, D3, D5, D7, D9 and D11.

The code is shown below:

Const int ina = 3; const int inb = 5; const int inc = 9; const int ledPin = 13; int i = 1000; byte a = 0; byte b = 0; byte c = 0; byte d = 0; unsigned long time = 0; // don't forget everything that millis () takes on unsigned long temp = 0; // store in unsigned long byte keya = (0, 0, 0, 0, 0, 0, 0, 0); // codes proper byte keyb = (1, 1, 1, 1, 0, 1, 0, 0); byte keyc = (1, 0, 1, 0, 1, 1, 1, 0); byte k = 0; void setup () (pinMode (ina, INPUT_PULLUP); // 3 inputs connected to the buttons pinMode (inb, INPUT_PULLUP); pinMode (inc, INPUT_PULLUP); pinMode (ledPin, OUTPUT); // built-in LED on the 13th pin pinMode (7, OUTPUT); pinMode (11, OUTPUT); digitalWrite (7, LOW); // replace the ground digitalWrite (11, LOW); time = millis (); // needed for timing) void blinktwice () ( // double blinking of the LED digitalWrite (ledPin, HIGH); delay (100); digitalWrite (ledPin, LOW); delay (100); digitalWrite (ledPin, HIGH); delay (100); digitalWrite (ledPin, LOW); delay ( 200);) void loop () (if (k == 0) (blinktwice (); // prompt for code) if (k == 8) (digitalWrite (ledPin, HIGH); delay (3000); k = 0 ;) a = digitalRead (ina); // signal levels are read from buttons - pressed / not pressed b = digitalRead (inb); c = digitalRead (inc); delay (100); // next if - protection against false positives, you don't need to use if ((digitalRead (ina) == a) && (digitalRead (inb) == b) && (digitalRead (inc) == c)) (if (a == keya [k]) (if (b == keyb [k]) (if (c == keyc [k]) (k ++; )))) if (k == 1) (if (d == 0) (time = millis (); d ++;)) temp = millis (); temp = temp - time; if (temp> 10000) (k = 0; d = 0; time = millis ();))

To avoid unnecessary questions about the code, some points should be clarified. The setup function is used to assign ports. The next function is Input_Pullup, which is needed to increase the pin voltage by 5 V. This is done with a resistor. Due to this, various short circuits will not occur. For more convenience, it is recommended to use the blinktwice function. In general, when creating various programs, you need to try other functions.

After assigning the functions, the signal is read from the ports. If the button is pressed, it will be indicated by the number 1, and if not - 2. Further, all values ​​are analyzed. For example, a combination such as 0,1,1 appeared. This means that the first key is pressed and the other two are not. If all values ​​are true, then condition 8 is also true. This is evidenced by the illuminated LED on the front panel. Next, you need to enter a specific code that will serve to open the door.

The last elements of the code are used to reset the counter values. This function is performed if more than 10 seconds have passed since the last key press. Without this code, it was possible to enumerate all possible options, although there are quite a few of them. After creating this device, you need to test it. More

I was watching The Amazing Spider-Man the other day and in one scene Peter Parker remotely opens and closes the door from his laptop. As soon as I saw this, I immediately realized that I also needed such an electronic lock on the front door.

With a little tinkering, I put together a working model of a smart lock. In this article, I will tell you how I put it together.

Step 1: List of materials





To assemble an electronic lock on Arduino, you will need the following materials:

Electronics:

  • 5V wall adapter

Components:

  • 6 screws for latch
  • cardboard
  • wires

Tools:

  • soldering iron
  • glue gun
  • drill
  • drill
  • pilot hole drill
  • stationery knife
  • computer with Arduino IDE program

Step 2: how the lock works

The idea is that I can open or close the door without a key, and without even going to it. But this is just the basic idea, because you can also add a knock sensor so that it responds to a special knock, or you can add a voice recognition system!

The servo arm connected to the latch will close it (0 °) and open it (60 °) using commands received via the Bluetooth module.

Step 3: Wiring diagram


Let's first connect the servo to the Arduino board (note that although I have an Arduino Nano board, the pinout is the same on the Uno board).

  • the brown wire of the servo is ground, we connect it to ground on the Arduino
  • the red wire is a plus, we connect it to the 5V connector on the Arduino
  • orange wire - the output of the source of the servo, we connect it to the 9th pin on the Arduino

I advise you to test the servo before proceeding with the assembly. To do this, in the Arduino IDE program in the examples, select Sweep. After making sure that the servo is working, we can connect the Bluetooth module. You need to connect the rx pin of the Bluetooth module to the tx pin of the Arduino, and the tx pin of the module to the rx pin of the Arduino. But don't do it yet! Once these connections are soldered, you will no longer be able to upload any codes to the Arduino, so download all your codes first and only then solder the connections.

Here is the wiring diagram for the module and the microcontroller:

  • Rx Module - Tx Arduino Board
  • Tx module - Rx boards
  • Vcc (positive) of the module - 3.3v of Arduino board
  • Ground is connected to Ground (ground to ground)

If the explanation seems confusing to you, follow the wiring diagram provided.

Step 4: Test

Now that we have all the parts in action, let's make sure the servo can move the bolt. Before mounting the latch on the door, I put together a test piece to make sure the servo is powerful enough. At first it seemed to me that my servo was weak and I added a drop of oil to the bolt, after that it worked fine. It is very important that the mechanism glides well, otherwise you risk being trapped in your room.

Step 5: housing for electrical components



I decided to put only the controller and the Bluetooth module in the case, and leave the servo outside. To do this, on a piece of cardboard, we circle the outline of the Arduino Nano board and add 1 cm of space around the perimeter and cut it out. After that we also cut out five more sides of the case. In the front wall, you will need to cut a hole for the controller's power cord.

Dimensions of the sides of the case:

  • Bottom - 7.5x4 cm
  • Cover - 7.5x4 cm
  • Left side wall - 7.5x4 cm
  • Right side wall - 7.5x4 cm
  • Front wall - 4x4 cm (with a slot for the power cord)
  • Back wall - 4x4 cm

Step 6: Application

To control the controller, you need an Android or Windows gadget with built-in Bluetooth. I have not had the opportunity to test the operation of the application on apple devices, maybe some drivers will be needed.

I'm sure some of you have the opportunity to test this. For Android, download the Bluetooth Terminal app, for Windows, download TeraTerm. Then you need to connect the module to your smartphone, the name should be linvor, the password should be 0000 or 1234. As soon as the pairing is established, open the installed application, enter the options and select "Establish connection (insecure)". Your smartphone is now an Arduino serial monitor, meaning you can communicate with the controller.

If you enter 0, the door will close, and the message “Door closed” will be displayed on the smartphone screen.
If you enter 1, you will see the door open and the message "Door open" will be displayed on the screen.
On Windows, the process is the same, except that you need to install the TeraTerm application.

Step 7: mount the bolt


First you need to connect the servo to the latch. To do this, cut off the plugs from the mounting holes of the drive housing. If we put the servo, the mounting holes should be flush with the latch. Then you need to place the servo lever in the latch slot, where the latch handle was. Check how the lock moves in the case. If everything is ok, secure the servo arm with glue.

Now you need to drill pilot holes for the screws in the door. To do this, attach the latch to the door and mark the screw holes on the door leaf with a pencil. Drill approximately 2.5 cm deep screw holes in the marked places. Attach the latch and secure with the screws. Check the servo again.

Step 8: Power


To complete the device, you will need a power supply, a cord, and a mini usb plug to connect to the Arduino.
Connect the ground pin of the power supply to the ground pin of the mini usb port, connect the red wire to the red wire of the mini usb port, then run the wire from the lock to the door hinge and from there to the outlet.

Step 9: Code

#include Servo myservo; int pos = 0; int state; int flag = 0; void setup () (myservo.attach (9); Serial.begin (9600); myservo.write (60); delay (1000);) void loop () (if (Serial.available ()> 0) (state = Serial.read (); flag = 0;) // if the state is "0" the DC motor will turn off if (state == "0") (myservo.write (8); delay (1000); Serial. println ("Door Locked");) else if (state == "1") (myservo.write (55); delay (1000); Serial.println ("Door UnLocked");))

Step 10: Finished Arduino Lock

Enjoy your remote control lock and don't forget to "accidentally" lock your friends in the room.

Today's lesson on how to use an RFID reader with an Arduino to create a simple locking system, in simple words - an RFID lock.

RFID (English Radio Frequency IDentification) is a method of automatic identification of objects, in which data stored in so-called transponders, or RFID tags, are read or written by means of radio signals. Any RFID system consists of a reader (reader, reader or interrogator) and a transponder (aka RFID tag, sometimes the term RFID tag is also used).

This tutorial will use an RFID tag from an Arduino. The device reads the unique identifier (UID) of each RFID tag that we place next to the reader and displays it on the OLED display. If the UID of the tag is equal to the predefined value that is stored in the Arduino memory, then we will see the message “Unlocked” on the display. If the unique identifier is not equal to the predefined value, the message "Unlocked" will not appear - see the photo below.

The lock is closed

The lock is open

Details required to create this project:

  • RFID Reader RC522
  • OLED display
  • Bread board
  • Wires

Additional details:

  • Battery (powerbank)

The total cost of the project components was approximately $ 15.

Step 2: RFID reader RC522

Each RFID tag has a small chip (white card pictured). If you aim the flashlight at this RFID card, you can see a small chip and a coil that surrounds it. This chip does not have a battery to generate power. It receives power from the reader wirelessly using this large coil. An RFID card like this can be read from up to 20mm away.

The same chip exists in the tags of the RFID key fob.

Each RFID tag has a unique number that identifies it. This is the UID that is shown on the OLED display. Except for this UID, each tag can store data. This type of card can store up to 1,000 data. Impressive, isn't it? This feature will not be used today. Today, all that interests is the identification of a particular card by its UID. The cost of the RFID reader and these two RFID cards is around US $ 4.

Step 3: OLED display

This tutorial uses a 0.96 "128x64 I2C OLED monitor.

This is a very good display for use with Arduino. It is an OLED display and that means it has low power consumption. The power consumption of this display is about 10-20mA and it depends on the number of pixels.

The display has a resolution of 128 by 64 pixels and is tiny. There are two display options. One of them is monochrome, and the other, like the one used in the tutorial, can display two colors: yellow and blue. The top of the screen can only be yellow and the bottom blue.

This OLED display is very bright and has a great and very nice library that Adafruit has developed for this display. In addition to this, the display uses an I2C interface, so connecting to the Arduino is incredibly easy.

You only need to connect two wires, excluding Vcc and GND. If you are new to Arduino and want to use an inexpensive and simple display in your project, start here.

Step 4: connect all the details

The communication with the Arduino Uno board is very simple. First, connect power to both the reader and the display.

Be careful, the RFID reader must be connected to the 3.3V output of the Arduino Uno or it will get corrupted.

Since the display can also run at 3.3V, we connect the VCC from both modules to the positive rail of the breadboard. This bus is then connected to the 3.3V output from the Arduino Uno. Then we connect both grounds (GND) to the grounding bus of the breadboard. Then we connect the GND bus of the breadboard to the Arduino GND.

OLED Display → Arduino

SCL → Analog Pin 5

SDA → Analog Pin 4

RFID Reader → Arduino

RST → Digital Pin 9

IRQ → Not connected

MISO → Digital Pin 12

MOSI → Digital Pin 11

SCK → Digital Pin 13

SDA → Digital Pin 10

The RFID reader module uses the SPI interface to communicate with the Arduino. Therefore, we are going to use the hardware SPI pins from the Arduino UNO.

The RST pin goes to digital pin 9. The IRQ pin remains disconnected. The MISO pin goes to digital pin 12. The MOSI pin goes to digital pin 11. The SCK pin goes to digital pin 13, and finally the SDA pin goes to digital pin 10. That's it.

RFID reader connected. Now we need to connect the OLED display to the Arduino using the I2C interface. So the SCL pin on the display goes to the analog pin of Pin 5 and SDA on the display to the analog Pin 4. If we now turn on the project and place the RFID card next to the reader, we can see that the project is working fine.

Step 5: Project Code

In order for the project code to be compiled, we need to include some libraries. First of all, we need the MFRC522 Rfid library.

To install it, go to Sketch -> Include Libraries -> Manage libraries(Library management). Find MFRC522 and install it.

We also need the Adafruit SSD1306 library and the Adafruit GFX library for mapping.

Install both libraries. The Adafruit SSD1306 library needs a little modification. Go to folder Arduino -> Libraries, open the Adafruit SSD1306 folder and edit the library Adafruit_SSD1306.h... Comment out line 70 and uncomment line 69 because the display has a resolution of 128x64.

First, we declare the value of the RFID tag that the Arduino needs to recognize. This is an array of integers:

Int code = (69,141,8,136); // UID

Then we initialize the RFID reader and display:

Rfid.PCD_Init (); display.begin (SSD1306_SWITCHCAPVCC, 0x3C);

After that, in the loop function, we check the tag on the reader every 100ms.

If there is a tag on the reader, we read its UID and print it to the display. We then compare the UID of the tag we just read with the value stored in the code variable. If the values ​​are the same, we print the UNLOCK message, otherwise we will not display this message.

If (match) (Serial.println ("\ nI know this card!"); PrintUnlockMessage ();) else (Serial.println ("\ nUnknown Card");)

Of course, you can change this code to store more than 1 UID value so that more RFID tags are recognized by the project. This is just an example.

Project code:

#include #include #include #include #define OLED_RESET 4 Adafruit_SSD1306 display (OLED_RESET); #define SS_PIN 10 #define RST_PIN 9 MFRC522 rfid (SS_PIN, RST_PIN); // Instance of the class MFRC522 :: MIFARE_Key key; int code = (69,141,8,136); // This is the stored UID int codeRead = 0; String uidString; void setup () (Serial.begin (9600); SPI.begin (); // Init SPI bus rfid.PCD_Init (); // Init MFRC522 display.begin (SSD1306_SWITCHCAPVCC, 0x3C); // initialize with the I2C addr 0x3D (for the 128x64) // Clear the buffer.display.clearDisplay (); display.display (); display.setTextColor (WHITE); // or BLACK); display.setTextSize (2); display.setCursor (10,0); display.print ("RFID Lock"); display.display (); ) void loop () (if (rfid.PICC_IsNewCardPresent ()) (readRFID ();) delay (100);) void readRFID () (rfid.PICC_ReadCardSerial (); Serial.print (F ("\ nPICC type:") ); MFRC522 :: PICC_Type piccType = rfid.PICC_GetType (rfid.uid.sak); Serial.println (rfid.PICC_GetTypeName (piccType)); // Check is the PICC of Classic MIFARE type! = PICMType22 && piccType! = MFRC522 :: PICC_TYPE_MIFARE_1K && piccType! = MFRC522 :: PICC_TYPE_MIFARE_4K) (Serial.println (F ("Your tag is not of type MIFARE Classic.")); return;) clearUID (); return;) clearUID (); Scanned PICC "s UID:"); printDec (rfid.uid.uidByte, rfid.uid.size); uidString = String (rfid.uid.uidByte) + "" + String (rfid.uid.uidByte) + "" + String (rfid.uid.uidByte) + "" + String (rfid.uid.uidByte); printUID (); int i = 0; boolean match = true; while (i

Step 6: the final result

As you can see from the lesson - for a little money, you can add an RFID reader to your projects. You can easily create a security system using this reader or create more interesting projects, for example, so that data from a USB disk is read only after unlocking.

This project is modular, i.e. you can connect / disconnect different elements and get different functionality. The pictures above show the option with full functionality, namely:

  • Locking mechanism... Serves for OPENING and CLOSING the door. This project covers the use of three different mechanisms:
    • Servo. There are big ones, there are small ones. Very compact, and with a heavy bolt is a great option
    • Electric drive of the car door lock. A big and powerful thing, but it eats just insane currents
    • Solenoid latch. A good option, since it slams itself

    In the firmware settings, you can choose any of three types (setting lock_type)

  • Button inside... Serves for OPENING and CLOSING the door from the inside. Can be placed on the door handle (palm or finger side), on the door itself, or on the jamb
  • Button outside... Serves for CLOSING the door, as well as for AWAKENING from energy saving. Can be placed on the door handle (palm or finger side), on the door itself, or on the jamb
  • End stop to close the door. Serves to automatically close the lock when the door is closed. They can be:
    • Tact button
    • Hall sensor + magnet on the door itself
    • Reed switch + magnet on the door itself
  • Secret access reset button... Serves to reset the password / enter a new password / memorize a new key / combination, etc. May be hidden somewhere in the case
  • Light-emitting diode to indicate work. RGB LED, red and green colors are used (when mixed, they give yellow):
    • Lights up green - the lock is OPEN. Burns so as not to forget to close the door
    • Solid yellow - the system has woken up and is awaiting password entry
    • Blinking red - the battery is dead

Any of these elements can be excluded from the system:

  • We remove the end switch. In the firmware in the settings, we also disable it (setting tail_button). Now to close the lock, you need to press the button
  • We remove the outer button. In the firmware in the settings, we also disable it (setting wake_button). Now the system does not need to be woken up, it wakes up by itself (energy consumption is slightly higher). And also we no longer have a close button on the front of the door, and we need a limit switch. Either the lock is the heck
  • We remove the inner button. This option is suitable for cabinets and safes. You don't need to change anything in the settings
  • We remove the LED. You don't need to change anything in the settings
  • The access reset button can be unsoldered after the first use, or you can rewrite the code for yourself
  • Door closed, pressed OUTSIDE - wake up, wait for password / RFID tag / electronic key / fingerprint
  • The door is closed, the system has woken up, waiting for the password to be entered. The time can be adjusted (setting sleep_time)
  • The door is closed, a password / tag / key has been entered, etc. - open
  • Door closed, pressed INSIDE - open
  • Door open, pressed OUTSIDE - close
  • Door open, pressed INSIDE - close
  • The door is open, the END is pressed - close

The lock provides for battery operation in low power saving mode (turn on turn off: setting sleep_enable), namely:

  • Wake up every few seconds, follow the EVENT (optional if there is no button outside. You can enable it in the setting wake_button)
  • Every few minutes, monitor the voltage of Akum (on / off setting battery_monitor)
  • If Akum is discharged (voltage is set in the setting bat_low):
    • open the door (optional, can be configured in the firmware open_bat_low)
    • prohibit further opening and closing
    • when the buttons are pressed, blink red LED
    • stop monitoring the EVENT (i.e. enter password / tag, etc.)

When the system is awake, press the change password button (hidden button). We fall into password change mode:
Enter the password from numbers ( MAXIMUM 10 DIGITS !!!)

  • When you press *, the password is saved in memory and the system exits from changing the password
  • When you press #, the password is reset (you can enter it again)
  • If you do not press anything for 10 seconds, we will automatically exit the password change mode, the password will remain old

When the system is awake (woke up by buttons or sleep is disabled), press * to enter the password entry mode
If the system sleeps and periodically wakes up to check the EVENT, then press * and hold until the red LED lights up
Password input mode:

  • Password processing is done in such a way that the correct password is counted only when the correct sequence of numbers is typed, that is, if the password is 345, then any numbers can be entered until the sequence 345 appears, i.e. 30984570345 will open the lock as it ends in 345.
  • If the password is entered correctly, the door will open
  • If you do not press anything, after 10 seconds the system will return to normal (standby) mode
  • If you press #, we will immediately exit the password entry mode
  • If you press the secret button for changing the password in the password input mode, then we will also exit from it