Automatic "smart" lock and Arduino. arduino code lock

In this article I will show you how to make a combination lock from arduino. To do this, we need red and green LEDs, a buzzer, an arduino nano, an LCD display with an I2C converter, a servo drive and a 4x4 matrix keyboard. When turned on, the display will write "Enter code.",

the red LED will turn on,

and the green turns off, the servo will be set to 0°. When numbers are entered, * will light up on the display.

If the code is entered incorrectly, the display will show "Enter cod.". If the code is correct, a beep will sound, the servo will turn 180°, the display will read "Open."

the green LED will turn on,

and red will turn off. After 3 seconds, the servo will return to its home position, the red LED will turn on and the green LED will turn off, the display will write "Close.",

then the display will write "Enter code.". Now about the scheme. First we connect the arduino with wires with breadboard(power contacts).

Then we connect a matrix keyboard to contacts D9 - D2.

Then the servo. We connect it to pin 10.

Red LED to pin 11.

Green - to pin 12.

Buzzer - to pin 13.

Now upload the sketch.

#include #include #include #include iarduino_KB KB(9, 8, 7, 6, 5, 4, 3, 2); LiquidCrystal_I2C lcd(0x27, 16, 2); Servo servo int pass = (3, 6, 1, 8); int in; int r = 11; int g = 12; void setup() ( KB.begin(KB1); pinMode(r, OUTPUT); pinMode(g, OUTPUT); lcd.init(); lcd.backlight(); digitalWrite(g, LOW); digitalWrite(r, HIGH ); servo.attach(10); servo.write(0); lcd.setCursor(0, 0); ) void loop() ( lcd.clear(); lcd.print("Enter code."); while ( !KB.check(KEY_DOWN)) ( delay(1); ) in = KB.getNum; lcd.clear(); lcd.setCursor(0, 0); lcd.print("*"); while (!KB. check(KEY_DOWN)) ( delay(1); ) in = KB.getNum; lcd.print("*"); while (!KB.check(KEY_DOWN)) ( delay(1); ) in = KB.getNum; lcd.print("*"); while (!KB.check(KEY_DOWN)) ( delay(1); ) in = KB.getNum; lcd.print("*"); if (in == pass) ( if (in == pass) ( if (in == pass) ( if (in == pass) ( lcd.clear(); lcd.setCursor(0, 0); lcd.print("Open."); tone( 13, 400, 750); servo.write(180); digitalWrite(r, LOW); digitalWrite(g, HIGH); delay(3000); lcd.clear(); lcd.setCursor(0, 0); lcd. print("Close."); tone(13, 300, 700); servo.write(0); digitalWrite(g, LOW); digitalWrite(r, HIGH); dela y(1000); ) ) ) ) )

That's all. Enjoy code lock!

List of radio elements

Designation Type Denomination Quantity NoteScoreMy notepad
E1 Arduino board

Arduino Nano 3.0

1 5V To notepad
E8, E9 Resistor

220 ohm

2 smd To notepad
E6 Light-emitting diode

AL102G

1 Red To notepad
E7 Light-emitting diode

AL307G

1 Green To notepad
E3 LCD displayWith I2C interface1 Green backlight To notepad
E5 ServoSG901 180 degrees To notepad
E2 Buzzer5V1 Bu To notepad
E4 Keyboard4x41 matrix To notepad
Not BreadBoard640 points1 without soldering

In this lesson we will learn how to do simple system, which will unlock the lock by electronic key(Metke).

In the future, you can refine and expand the functionality. For example, add the function "adding new keys and removing them from memory". In the base case, consider a simple example, when a unique key identifier is pre-specified 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 the Buzzer, which will give a signal if the key worked and the lock opens, and the second signal when the lock closes.

We connect the buzzer in the following sequence:

Arduino Buzzer
5V VCC
GND GND
pin 5 IO

3) A servo will be used as the unlocking mechanism. Any servo can be chosen, depending on the dimensions you require and the forces that 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 tag number in decimal format Servo servo; void setup() ( Serial.begin(9600); Serial.println("Waiting for card..."); SPI.begin(); // SPI initialization / Init SPI bus. mfrc522.PCD_Init(); // initialization MFRC522 / Init MFRC522 card.servo.attach(6); servo.write(0); // set servo to closed state ) void loop() ( // Search for a new label if (! mfrc522.PICC_IsNewCardPresent()) ( return; ) // Selecting a tag if (! mfrc522.PICC_ReadCardSerial()) ( return; ) uidDec = 0; // Issuing the serial number of the tag 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 analyze the sketch in more detail:

In order to find out the UID of the card (Labels), you need to write this sketch to arduino, assemble the circuit described above, and open the Console (Monitoring of the serial port). 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 specified one, then the servo opens the valve.

For each card, this identifier is unique and does not repeat. Thus, when you present a card whose ID you have set in the program, the system will open access using a servo.

Video:

Progress does not stand still and "Smart locks" are increasingly appearing on the doors of apartments, garages and houses.

A similar lock opens when you press a button on your smartphone. Fortunately, smartphones and tablets have already entered our everyday life. In some cases, "smart locks" are connected to "cloud services" like Google Drive and opened remotely. In addition, this option makes it possible to give access to the opening of the door to other people.

In this project, a DIY version of a smart lock on Arduino will be implemented, which can be controlled remotely from anywhere in the world.

In addition, the project has added the ability to open the lock after fingerprint recognition. For this, a fingerprint sensor will be integrated. Both options for opening doors will work based on the Adafruit IO platform.

A lock like this can be a great first step in your Smart Home project.

Setting up the fingerprint sensor

To work with the fingerprint sensor, there is an excellent library for Arduino, which greatly simplifies the process of setting up the sensor. This project uses Arduino Uno. The Adafruit CC3000 board is used to connect to the internet.

Let's start by connecting the power:

  • Connect the 5V pin from the Arduino board to the red power rail;
  • The GND pin from the Arduino connects to the blue rail on the solderless circuit board.

Let's move on to connecting the fingerprint sensor:

  • Connect the power first. To do this, the red wire is connected to the +5 V rail, and the black wire to the GND rail;
  • The white sensor wire connects to pin 4 on the Arduino.
  • Green wire goes to pin 3 on the microcontroller.

Now let's take a look at the CC3000 module:

  • Connect the IRQ pin from the CC3000 board to pin 2 on the Arduino.
  • VBAT - to pin 5.
  • CS - to pin 10.
  • After that, you need to connect the SPI pins to the Arduino: MOSI, MISO and CLK - to pins 11, 12 and 13, respectively.

And finally, you need to provide power: Vin - to Arduino 5V (red rail on your circuit board), and GND to GND (blue rail on the breadboard).

A photo of the fully assembled project is shown below:

Before developing a sketch that will upload data to Adafruit IO, you need to pass your fingerprint data to the sensor. Otherwise, he will not recognize you in the future;). We recommend calibrating the fingerprint sensor using the Arduino separately. If you are working with this sensor for the first time, we recommend that you read the calibration process and detailed instructions for working with the fingerprint sensor.

If you haven't done so already, then sign up for an Adafruit IO account.

After that, we can move on to the next stage of developing a "smart lock" on Arduino: namely, the development of a sketch that will transmit data to Adafruit IO. Since the program is quite voluminous, in the article we will highlight and consider only its main parts, and then we will give a link to GitHub, where you can download the full sketch.

The sketch begins by loading all the necessary libraries:

#include

#include

#include

#include "Adafruit_MQTT.h"

#include "Adafruit_MQTT_CC3000.h"

#include

#include >

After that, you need to slightly correct the sketch by inserting the parameters of your WiFi network, specifying the SSID and password (password):

#define WLAN_SECURITY WLAN_SEC_WPA2>

In addition, you must enter a name and AIO key (key) to enter your Adafruit IO account:

#define AIO_SERVERPORT 1883

#define AIO_USERNAME "adafruit_io_name"

#define AIO_KEY "adafruit_io_key">

The following lines are responsible for the interaction and processing of data from the fingerprint sensor. If the sensor was activated (fingerprint matched), it will be "1":

const char FINGERPRINT_FEED PROGMEM = AIO_USERNAME "/feeds/fingerprint";

Adafruit_MQTT_Publish fingerprint = Adafruit_MQTT_Publish(&mqtt, FINGERPRINT_FEED);

In addition, we need to create an instance of the SoftwareSerial object for our sensor:

SoftwareSerial mySerial(3, 4);

After that, we can create an object for our sensor:

Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerial);

Inside the sketch, we specify which fingerID should activate the lock in the future. In this example, 0 is used, which corresponds to the ID of the first fingerprint used by the sensor:

int fingerID = 0;

After that, we initialize the counter and the delay (delay) in our project. Basically, we want the lock to automatically work after opening. This example uses a delay of 10 seconds, but you can adjust this value to suit your needs:

int activationCounter = 0;

int lastActivation = 0;

int activationTime = 10 * 1000;

In the body of the setup() function, we initialize the fingerprint sensor and ensure that the CC3000 chip is connected to your WiFi network.

In the body of the loop() function, we connect to Adafruit IO. The following line is responsible for this:

After connecting to the Adafruit IO platform, we check the last fingerprint. If it matches and the lock is not enabled, we send a "1" to Adafruit IO for processing:

if (fingerprintID == fingerID && lockState == false) (

Serial.println(F("Access granted!"));

lockState=true;

Serial.println(F("Failed"));

Serial.println(F("OK!"));

lastActivation = millis();

If, within the loop() function, the lock is activated and we have reached the delay value indicated above, we send "0":

if ((activationCounter - lastActivation > activationTime) && lockState == true) (

lockState=false;

if (! fingerprint.publish(state)) (

Serial.println(F("Failed"));

Serial.println(F("OK!"));

You can download the latest version of the code on GitHub.

It's time to test our project! Don't forget to download and install all required Arduino libraries!

Make sure you've made all the necessary changes to the sketch and upload it to your Arduino. Then open the serial monitor window.

When the Arduino connects to WiFi networks, the fingerprint sensor will flash red. Put your finger on the sensor. The serial monitor window should display the ID number. If it matches, a message will appear, "OK!". This means that the data has been sent to the Adafruit IO servers.

Scheme and sketch for further setting up the lock using the example of an LED

Now let's deal with the part of the project that is directly responsible for managing door lock. To connect to a wireless network and activate / deactivate the lock, you will need an additional Adafruit ESP8266 module (ESP8266 module does not have to be from Adafruit). The example below will show you how easy it is to communicate between two platforms (Arduino and ESP8266) using Adafruit IO.

In this section, we will not work directly with the lock. Instead, we will simply connect the LED to the pin where the lock will be connected later on. This will make it possible to test our code without delving into the specifics of the lock design.

The circuit is quite simple: first install the ESP8266 on the breadboard. Then install the LED. Don't forget that the long (positive) leg of the LED is connected through a resistor. The second leg of the resistor is connected to pin 5 on the ESP8266 module. The second (cathode) LED is connected to the GND pin on the ESP8266.

Fully assembled circuit shown in the photo below.


Now let's take a look at the sketch we're using for this project. Again, the code is quite large and complex, so we will only cover the main parts of it:

We start by including the necessary libraries:

#include

#include "Adafruit_MQTT.h"

#include "Adafruit_MQTT_Client.h"

Configure WiFi settings:

#define WLAN_SSID "your_wifi_ssid"

#define WLAN_PASS "your_wifi_password"

#define WLAN_SECURITY WLAN_SEC_WPA2

We also configure the Adafruit IO parameters. Same as in the previous section:

#define AIO_SERVER "io.adafruit.com"

#define AIO_SERVERPORT 1883

#define AIO_USERNAME "adafruit_io_username"

#define AIO_KEY "adafruit_io_key"

We indicate to which pin we connected the LED (in the future it will be our lock or relay):

int relayPin = 5;

Interaction with the fingerprint sensor, as in the previous section:

const char LOCK_FEED PROGMEM = AIO_USERNAME "/feeds/lock";

Adafruit_MQTT_Subscribe lock = Adafruit_MQTT_Subscribe(&mqtt, LOCK_FEED);

In the body of the setup() function, we indicate that the pin to which the LED is connected should work in OUTPUT mode:

pinMode(relayPin, OUTPUT);

Within the loop() loop, we first check if we have connected to Adafruit IO:

After that, we check what signal is coming. If "1" is transmitted, we activate the pin we declared earlier, to which our LED is connected. If we received "0", we put the contact in the "low" state:

Adafruit_MQTT_Subscribe *subscription;

while ((subscription = mqtt.readSubscription(1000))) (

if (subscription == &lock) (

Serial.print(F("Got: "));

Serial.println((char *)lock.lastread);

// Save the command as string data

String command = String((char *)lock.lastread);

if (command == "0") (

digitalWrite(relayPin, LOW);

if (command == "1") (

digitalWrite(relayPin, HIGH);

To find latest version You can check out the sketch on GitHub.

It's time to test our project. Don't forget to download all the necessary libraries for your Arduino and check if you made the correct changes to the sketch.

A simple USB-FTDI converter can be used to program the ESP8266 chip.

Upload the sketch to the Arduino and open the serial monitor window. At this stage, we just checked if we were able to connect to Adafruit IO: we will look at the available functionality further.

Testing the project

Now let's start testing! Go to the user menu of your Adafruit IO, in the Feeds menu. Check if channels for fingerprint and lock are created or not (on the print screen below, these are the fingerprint and lock lines):


If they don't exist, you'll have to create them manually.

Now we need to ensure data exchange between the fingerprint and lock channels. The lock channel must be set to "1" when the fingerprint channel is set to "1" and vice versa.

To do this, we use a very powerful Adafruit IO tool: triggers. Triggers are essentially conditions that you can apply to configured channels. That is, they can be used to interconnect two channels.

Create a new reactive trigger from the Triggers section in Adafruit IO. This will provide the ability to exchange data between the channels of the fingerprint sensor and the lock:


Here's what it should look like when both triggers are configured:

All! Now we can really test our project! We put our finger on the sensor and see how the Arduino began to wink with the LED, which corresponds to the data transfer. After that, the LED on the ESP8266 module should start blinking. This means that he began to receive data through MQTT. The LED on the circuit board should also turn on at this point.

After the delay you set in the sketch (default is 10 seconds), the LED will turn off. Congratulations! You can control the LED with your fingerprint from anywhere in the world!

Setting up an electronic lock

We have reached the last part of the project: directly connecting and controlling an electronic lock using an Arduino and a fingerprint sensor. The project is not easy, you can use all the sources in the form in which they are presented above, but instead of an LED, connect a relay.

To connect the lock directly, you will need additional components: a 12 V power supply, a power jack, a transistor (in this example an IRLB8721PbF MOSFET is used, but another one, such as a TIP102 bipolar transistor, can be used. If you are using a bipolar transistor, you will need to add a resistor.

Shown below circuit diagram connecting all components to the ESP8266 module:


Note that if you are using a MOSFET, you will not need a resistor between ESP8266 pin 5 and the transistor.

The fully assembled project is shown in the photo below:


Power up the ESP8266 module using the FTDI module and connect the 12V power supply to the jack. If you used the pins recommended above for connection, you won't have to change anything in the sketch.

Now you can put your finger on the sensor: the lock should work in response to your fingerprint. The video below shows the automatic smart lock project in action:

Further development of the Smart Lock project

In our project released remote control door lock with fingerprint.

Feel free to experiment, modify the sketch and harness. For example, you can replace the door electronic lock on a relay to control the power of your 3D printer, arm or quadcopter...

You can develop your smart House". For example, remotely activate the irrigation system on the Arduino or turn on the light in the room ... Do not forget that you can simultaneously activate an almost unlimited number of devices using Adafruit IO.

Leave your comments, questions and share personal experience below. In the discussion, new ideas and projects are often born!

It just so happened that at work we decided to install a combination lock on our door, because, as we constantly run in, we run out of the office, the door to which must be constantly closed in the absence of inhabitants. Keys are often forgotten inside. In general, we decided that a combination lock is a great way out.

After rummaging through Chinese flea markets and ebay, I didn’t find anything cheap and more or less serious and decided to make it myself. I will make a reservation right away that the Arduino platform was chosen for its simplicity, since there was no experience at all with microcontrollers.

Idea

On the door, on the outside of the door, there should be a keypad on which the password is entered, and the rest of the structure is fixed on the inside. A reed switch is used to control the complete closing of the door. Leaving the office, a person presses “*” on the keyboard and, without waiting for the door to close, the door closer goes about his business, when the door is completely closed, the reed switch will close and the lock will be closed. The door is opened by entering a 4-digit password and pressing "#".

Accessories

Arduino UNO = $18
Arduino protoshield + breadboard = $6
L293D = $1
Bundle of wires 30pcs for bredboard = $4
2 RJ45 sockets = $4
2 RJ45 plugs = $0.5
central lock actuator = 250 rubles.
Reed switch = torn free of charge from the old window.
Espagnolette metal gigantic sizes = free
Case from an old D-LINK hub made of 1.5 mm iron = free
Power supply from the same D-LINK hub for 12 and 5v = also free
A bunch of screws and nuts for attaching all this stuff to the case = 100 rubles.
Control panel from burglar alarm= free.

Total:$33.5 and 350 rubles.

Not so little, you say, and you will definitely be right, but you have to pay for pleasure! And it's always nice to collect something with your own hands. In addition, the design can be greatly reduced in price if you use a bare MK without an Arduino.

Assembly preparation

I would like to say a few words about the purchase of a key element of the actuator design. At a local auto shop, they offered me two types of actuators: "with two wires and with five." According to the saleswoman, they were exactly the same and the difference in the number of wires meant absolutely nothing. However, as it turned out later, this is not so! I chose a device with two wires, it was powered by 12v. The five-wire design features limit switches to control the movement of the lever. I realized that I bought the wrong one only when I took it apart and it was too late to change it. The stroke of the lever turned out to be too short to properly push the latch, therefore, it was necessary to modify it a little, namely, to remove two rubber washers shortening the stroke of the actuator lever. To do this, the body had to be sawn along with a regular hacksaw, because the second washer was inside. The blue duct tape to us, as always, helped us later on when assembling it back.
To control the actuator motor, the L293D motor driver was used, which can withstand a peak load of up to 1200 mA, in our case, when the actuator motor was stopped, the peak load increased to only 600 mA.
Contacts from the keyboard, speaker and two LEDs were removed from the control panel from the security alarm. The remote control and the main device were supposed to be connected using a twisted pair and RJ45 connectors

Programming.

So, as I have not had any experience with Arduino programming until now. I took advantage of other people's developments and articles from the arduino.cc website. Who cares, can look at this ugly code :)

Photo and video



Arduino and actuator


Power Supply


Keyboard


Espagnolette (connected to the actuator with a metal needle and on which heat shrink is put on for beauty)

Video of the device operation process:

The host of the youtube channel “AlexGyver” was asked to make an electronic lock with his own hands. Welcome to the video cycle about electronic locks on arduino. AT in general terms the master will explain the idea.

There are several options for creating an electronic lock system. Most often used to lock doors and drawers, cabinets. And also to create hiding places and secret safes. Therefore, you need to make a layout that is convenient to work with and you can clearly and in detail show the structure of the system from the inside and outside. Therefore, I decided to make a frame with a door. This will require square bar 30 x 30. Plywood 10mm. Door hinges. Initially I wanted to make a plywood box, but I remembered that everything in the room was littered with spare parts. There is nowhere to put such a box. Therefore, a layout will be made. If someone wants to put himself an electronic lock, then looking at the layout, you can easily repeat everything.

Everything you need for a castle can be found in this Chinese store.

The goal is to develop the most efficient circuits and firmware for electronic locks. You will be able to use these results to install these systems on your doors, drawers, cabinets and hiding places.

The door is ready. Now you need to figure out how to open and close electronically. For these purposes, a powerful solenoid latch from aliexpress is suitable (link to the store above). If you apply voltage to the terminals, it will open. The coil resistance is almost 12 ohms, which means that at a voltage of 12 volts, the coil will eat about 1 ampere. Will cope with this task and lithium battery and boost module. We adjust to the appropriate voltage. Although maybe a little more. The heck is attached to inside doors at a distance so that the edge does not cling and can slam shut. The heck should be a counterpart in the form of a metal box. Using it without it is inconvenient and wrong. We'll have to put a step, at least created the appearance of normal operation.

In idle mode, the latch opens normally, that is, if there is a handle on the door, we give an impulse, we open the door by the handle. But if you spring it, this method is no longer suitable. The boost converter can't handle the load. To open the spring-loaded door, you will have to use larger batteries and a more powerful converter. Or a mains power supply and score on the autonomy of the system. There are hecks in Chinese stores large sizes. They fit in boxes. Power can be supplied using a relay or mosfet transistor, or a power switch on the same transistor. A more interesting and less expensive option is a servo connected to a connecting rod with any locking element - a latch or a more serious valve. He may also need a piece of steel knitting needle that acts as a connecting rod. Such a system does not need a large current. But it takes up more space and more cunning control logic.

There are two types of servos. Small weak and large powerful ones, which can be easily pushed into holes in serious metal pins. Both options shown work on both doors and drawers. You will have to tinker with the box, making a hole in the sliding wall.

Second part

What else to read