Components · 9 min read

Arduino Solenoid Lock: 12V Door Lock with MOSFET, Keypad and RFID

Arduino solenoid lock guide: how a 12V lock works, MOSFET or relay drive, flyback diode, heating, keypad and RFID locks, fail-safe vs fail-secure, ESP32.

A solenoid lock is an electric latch that pulls its bolt back when current flows through the coil inside and lets a spring push it out again when the current stops. With an Arduino solenoid lock you can build a code-protected cabinet, a door that opens with an RFID card, a drawer that opens with your fingerprint or a mailbox you unlock from your phone. The most common type in hobby projects is the small 12 V "cabinet lock" that draws about 0.5-1 A. That's 25 to 50 times what an Arduino pin can supply, so the lock isn't driven straight from a pin but through a MOSFET or a relay.

In this guide I'll explain what's inside a solenoid lock, how to work out its current and power, two ways of driving it with a MOSFET or a relay, the flyback diode you need so you don't destroy your board, and why the coil should only be energised briefly. Then we'll write code for a keypad code lock, an RC522 card lock and an ESP32 lock you open from your phone. Finally we'll look at fail-safe and fail-secure, which decide what happens when the power goes out. If MOSFETs are new to you, Using a MOSFET with Arduino is a good start.

What is a solenoid lock and how does it work?

The word "solenoid" describes a coil of wire wound around a tube. When current flows through the coil a magnetic field forms inside it, and that field pulls the iron core (plunger) in the middle towards itself. In a lock the plunger is attached to a slanted bolt. With no current a spring keeps the bolt out and the door stays locked; apply 12 V and the plunger is pulled in, the bolt retracts and the door opens. Thanks to the bolt's slanted face, closing the door pushes the bolt in and lets it snap back into place, so locking needs no power at all. If you're curious about how coils behave electrically, see What is an inductor?.

PropertyTypical 12 V cabinet solenoid lockNote
Operating voltage12 V DCWeak pull at 9 V; at 5 V it usually won't open
Current0.5-1 A (0.6-0.8 A is common)Check the label or measure the coil resistance
Coil resistanceAbout 12-24 ΩI = V / R; 0.75 A at 16 Ω
Power6-12 WP = V × I; 12 V × 0.75 A = 9 W
Energising timeA few seconds (10 s max on most models)Heats up if held open continuously
On power lossStays locked (fail-secure)Magnetic door locks do the opposite and open

If you don't know your lock's current, set the multimeter to ohms, measure the resistance between the coil's two leads and work out the current with the Ohm's law calculator. If you measure 16 Ω at 12 V, the lock draws 0.75 A; pick a supply rated for at least twice that, so 12 V 2 A. The current can spike briefly at the first pull, and if a weak adapter's voltage sags the lock won't open fully.

Driving the solenoid lock with a MOSFET or a relay

There are two common methods. A MOSFET is silent, fast, doesn't wear out and takes up little space; chosen correctly it doesn't even get warm. The feature to look for is "logic level": its gate must turn fully on at 5 V, or at 3.3 V if you use an ESP32. The IRLZ44N has about 0.025 Ω of resistance at 5 V; at 0.75 A the power it dissipates is P = I² × R ≈ 14 mW, so no heatsink is needed. The popular IRF520 modules, on the other hand, are designed for a 10 V gate and stay half on and hot at 5 V. A relay module is simple and also isolates the two circuits; its downsides are the click, contact wear and the current its own coil draws. To choose a transistor or MOSFET, check the values in the transistor tool.

Connection (MOSFET circuit)Where?Why?
Lock red (+)12 V adapter +The coil always sits on the positive side
Lock black (-)MOSFET drain (D)The MOSFET switches the negative side
MOSFET source (S)12 V adapter - and Arduino GNDCommon ground
MOSFET gate (G)Arduino D10 through 220 ΩLimits the pin's charging current spike
10 kΩ resistorBetween gate and GNDKeeps the lock from opening at power-up
1N4007 diodeReverse-biased across the lock; striped end to +12 VAbsorbs the coil's reverse voltage spike
470 µF capacitorBetween 12 V + and -, close to the lockReduces the voltage dip at pull-in
Never skip the flyback diode. When the current in a coil is cut suddenly, the magnetic field collapses and the coil produces a reverse voltage spike of hundreds of volts across its leads to keep the current flowing. Without a diode that spike punches through the MOSFET, resets the Arduino or burns its pin. Connect the diode across the lock's two leads with the silver-striped end (cathode) on the +12 V side; in normal operation it carries no current and only routes the spike at switch-off back into the coil, where it dies out. You need the same diode when driving the lock with a relay, otherwise the relay contacts wear away with a spark at every opening. See What is a diode? for details.

Powering the Arduino and the lock from the same 12 V adapter is practical: you can feed the Uno 12 V through its DC jack. But the voltage dips for a moment when the lock pulls in, and the Uno's regulator gets warm dropping 12 V to 5 V; a sturdier option is to drop the 12 V to 5 V with an LM2596 module and feed the board through its 5V pin. Either way, the MOSFET source, the adapter's negative and the Arduino's GND must meet at one point; I explain why in detail in GND and common ground.

Short energising and heat: how long can you keep the lock open?

Burning 9 W in a small coil is like running a little soldering iron in the space of your palm. Cheap cabinet locks are usually designed for intermittent duty: opening for a few seconds is fine, but held open for minutes the coil gets too hot to touch, the insulation varnish degrades and the lock weakens over time. That's why you should always define a maximum open time in software; in this article's code it's 3 seconds. If the door has to stay open for a long time, there are two solutions: choose a lock that holds its bolt open mechanically, or give full power at pull-in and then reduce it with PWM. A coil needs much more force to pull the bolt in than to hold it; after 200 ms at full power, 30-40% PWM holds the bolt in on most locks and cuts the heating several times. You'll find how PWM works in What is PWM?.

A keypad code lock with a solenoid

4x4 membrane keypad
4x4 membrane keypad: reads 16 keys with 4 row and 4 column pins; the Keypad library does the scanning for you.

The first project uses a 4x4 keypad to enter a code. Connect the keypad's row pins to D9, D8, D7, D6 and its column pins to D5, D4, D3, D2; the MOSFET gate goes to D10 and a small active buzzer to A0. Install Mark Stanley's Keypad library from the Library Manager. You type the code and confirm with #, while * clears the entry. After three wrong attempts the keypad locks for 30 seconds; this small measure makes guessing the code by trial and error practically impossible. You'll find how the keypad works inside in the keypad article.

C++ (Arduino IDE)
1// Keypad şifreli solenoid kilit / keypad-code solenoid lock
2#include <Keypad.h>
3
4const int LOCK_PIN = 10;                 // MOSFET gate (220 ohm üzerinden / via 220 ohm)
5const int BUZZER_PIN = A0;               // aktif buzzer / active buzzer
6const unsigned long OPEN_MS = 3000;      // kilit açık süresi / unlock time
7const unsigned long LOCKOUT_MS = 30000;  // 3 hatadan sonra bekleme / lockout after 3 errors
8const char* PASSWORD = "2580";           // şifreyi değiştir / change the code
9
10const byte ROWS = 4, COLS = 4;
11char keys[ROWS][COLS] = {
12  {'1', '2', '3', 'A'},
13  {'4', '5', '6', 'B'},
14  {'7', '8', '9', 'C'},
15  {'*', '0', '#', 'D'}
16};
17byte rowPins[ROWS] = {9, 8, 7, 6};
18byte colPins[COLS] = {5, 4, 3, 2};
19Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
20
21String input = "";
22int wrongCount = 0;
23bool lockedOut = false;
24unsigned long lockoutStart = 0;
25
26void beep(int ms) {
27  digitalWrite(BUZZER_PIN, HIGH);
28  delay(ms);
29  digitalWrite(BUZZER_PIN, LOW);
30}
31
32void unlock() {
33  digitalWrite(LOCK_PIN, HIGH);   // bobine enerji ver, dil çekilir / energise coil, bolt retracts
34  delay(OPEN_MS);                 // yalnız kısa süre / short time only
35  digitalWrite(LOCK_PIN, LOW);    // yay dili geri iter / spring pushes the bolt back
36}
37
38void setup() {
39  pinMode(LOCK_PIN, OUTPUT);
40  digitalWrite(LOCK_PIN, LOW);    // açılışta kilitli / locked at power-up
41  pinMode(BUZZER_PIN, OUTPUT);
42}
43
44void loop() {
45  char k = keypad.getKey();
46  if (!k) return;
47
48  if (lockedOut) {
49    if (millis() - lockoutStart < LOCKOUT_MS) { beep(300); return; }
50    lockedOut = false;
51  }
52  beep(30);
53
54  if (k == '*') { input = ""; return; }          // temizle / clear
55  if (k == '#') {                                 // onayla / confirm
56    if (input == PASSWORD) {
57      wrongCount = 0;
58      unlock();
59    } else {
60      beep(600);
61      if (++wrongCount >= 3) {                    // kaba kuvvete karşı / against brute force
62        lockedOut = true;
63        lockoutStart = millis();
64        wrongCount = 0;
65      }
66    }
67    input = "";
68    return;
69  }
70  if (input.length() < 8) input += k;            // en fazla 8 hane / max 8 digits
71}

A lock that opens with an RFID card (RC522)

RC522 RFID reader module
RC522: reads 13.56 MHz MIFARE cards and key fobs from a few centimetres; it connects over SPI and runs on 3.3 V.

In the second project the lock opens when a registered RFID card is scanned. Wire the RC522 to the Uno as SDA → D10, SCK → D13, MOSI → D11, MISO → D12, RST → D9, 3.3V → 3.3V and GND → GND; since SPI uses D10-D13, the MOSFET gate goes to D6 this time. Install the MFRC522 library, upload the code, scan your card and copy the UID shown in the Serial Monitor into the ALLOWED list. Because card UIDs can be cloned, this method suits cabinets and drawers; on its own it isn't enough where high security is needed, such as an outside door. For details on the RC522, see the RFID RC522 guide.

C++ (Arduino IDE)
1// RFID kartla solenoid kilit / RFID card solenoid lock
2#include <SPI.h>
3#include <MFRC522.h>
4
5const int SS_PIN = 10;              // RC522 SDA
6const int RST_PIN = 9;              // RC522 RST
7const int LOCK_PIN = 6;             // MOSFET gate
8const unsigned long OPEN_MS = 3000;
9
10// Yetkili kart UID'leri, Seri Monitör'den oku / authorised UIDs, read them from the Serial Monitor
11const byte ALLOWED[][4] = {
12  {0xDE, 0xAD, 0xBE, 0xEF},
13  {0x12, 0x34, 0x56, 0x78}
14};
15const int ALLOWED_COUNT = sizeof(ALLOWED) / sizeof(ALLOWED[0]);
16
17MFRC522 rfid(SS_PIN, RST_PIN);
18
19bool isAllowed(const byte* uid, byte size) {
20  if (size != 4) return false;
21  for (int i = 0; i < ALLOWED_COUNT; i++) {
22    if (memcmp(uid, ALLOWED[i], 4) == 0) return true;
23  }
24  return false;
25}
26
27void setup() {
28  Serial.begin(9600);
29  pinMode(LOCK_PIN, OUTPUT);
30  digitalWrite(LOCK_PIN, LOW);
31  SPI.begin();
32  rfid.PCD_Init();
33}
34
35void loop() {
36  if (!rfid.PICC_IsNewCardPresent() || !rfid.PICC_ReadCardSerial()) return;
37
38  Serial.print("UID:");
39  for (byte i = 0; i < rfid.uid.size; i++) {
40    Serial.print(rfid.uid.uidByte[i] < 0x10 ? " 0" : " ");
41    Serial.print(rfid.uid.uidByte[i], HEX);
42  }
43  Serial.println();
44
45  if (isAllowed(rfid.uid.uidByte, rfid.uid.size)) {
46    Serial.println("Açıldı / unlocked");
47    digitalWrite(LOCK_PIN, HIGH);
48    delay(OPEN_MS);
49    digitalWrite(LOCK_PIN, LOW);
50  } else {
51    Serial.println("Yetkisiz kart / unknown card");
52  }
53  rfid.PICC_HaltA();               // kartı beklemeye al / halt the card
54}
You can build a fingerprint lock the same way: just call the unlock function when the AS608 fingerprint sensor finds a matching finger. Combining keypad, card and fingerprint for two-step verification (card first, then code) raises security noticeably.

What happens in a power cut? Fail-safe vs fail-secure

The first question to ask when choosing an electric lock: should the door stay open or locked when the power goes out? Fail-secure locks stay locked without power; cabinet-style solenoids work this way, and they're the right choice for safes, drawers and delivery boxes. Fail-safe locks open when the power is cut; the magnetic door locks (electromagnets) in buildings work like this, because people must be able to get out during a fire or blackout. Fitting a fail-secure lock on a door that's an escape route is dangerous and breaks building rules in most places.

Lock typeOn power lossGood for
Solenoid cabinet lockStays locked (fail-secure)Cabinets, safes, drawers, boxes
Electromagnetic door lockOpens (fail-safe)Building entrances, escape routes
Electric strikeEither, depending on the modelAdded to an existing door lock
Motorised lockStays in its last positionSmart door locks, battery systems

If you use a fail-secure lock, plan a backup so you don't lock yourself out: a mechanical spare key, a hidden emergency release button or a battery backup that can keep the lock and Arduino running for a while. For example, a small 12 V lead-acid battery or a 3S lithium pack with a charging circuit is enough for a few hundred openings during an outage.

Opening the solenoid lock from your phone with an ESP32

The ESP32 is the easiest way to open the lock over Wi-Fi. The code below sets up a small web server; when you open the IP address shown in the Serial Monitor in your phone's browser, it asks for a user name and password and then shows a big OPEN button. Pressing it unlocks the lock for 3 seconds and relocks it automatically with millis(), while the server keeps running. One important difference: the ESP32's pins output 3.3 V. An IRLZ44N may not turn fully on at that voltage; use a MOSFET specified to switch at 2.5-4.5 V such as the IRLB8721 or AO3400, or drive the lock with a relay module that triggers at 3.3 V. To power the ESP32 from 12 V, drop it to 5 V with an LM2596 and feed the 5V (VIN) pin.

C++ (Arduino IDE)
1// ESP32: telefondan solenoid kilit açma / open the solenoid lock from your phone
2#include <WiFi.h>
3#include <WebServer.h>
4
5const char* WIFI_SSID = "AgAdi";        // Wi-Fi adın / your Wi-Fi name
6const char* WIFI_PASS = "Sifre123";     // Wi-Fi şifren / your Wi-Fi password
7const char* WEB_USER  = "kapi";         // sayfa kullanıcı adı / page user name
8const char* WEB_PASS  = "degistir-beni"; // sayfa şifresi, değiştir / page password, change it
9const int LOCK_PIN = 26;                // MOSFET gate (3,3 V ile tam açılan / fully on at 3.3 V)
10const unsigned long OPEN_MS = 3000;
11
12WebServer server(80);
13bool isOpen = false;
14unsigned long openedAt = 0;
15
16const char PAGE[] = R"html(<!DOCTYPE html><html><head>
17<meta name="viewport" content="width=device-width,initial-scale=1"><title>Kapi</title></head>
18<body style="font-family:sans-serif;text-align:center;margin-top:40px">
19<h2>Solenoid kilit / lock</h2>
20<form method="POST" action="/open"><button style="font-size:28px;padding:20px 40px">AC / OPEN</button></form>
21</body></html>)html";
22
23bool checkAuth() {
24  if (server.authenticate(WEB_USER, WEB_PASS)) return true;
25  server.requestAuthentication();         // tarayıcı şifre sorar / browser asks for a password
26  return false;
27}
28
29void handleRoot() {
30  if (!checkAuth()) return;
31  server.send(200, "text/html", PAGE);
32}
33
34void handleOpen() {
35  if (!checkAuth()) return;
36  if (!isOpen) {
37    digitalWrite(LOCK_PIN, HIGH);         // kilidi aç / unlock
38    isOpen = true;
39    openedAt = millis();
40  }
41  server.sendHeader("Location", "/");
42  server.send(303);                       // ana sayfaya dön / back to the main page
43}
44
45void setup() {
46  pinMode(LOCK_PIN, OUTPUT);
47  digitalWrite(LOCK_PIN, LOW);
48  Serial.begin(115200);
49  WiFi.mode(WIFI_STA);
50  WiFi.begin(WIFI_SSID, WIFI_PASS);
51  while (WiFi.status() != WL_CONNECTED) delay(500);
52  Serial.println(WiFi.localIP());         // bu adresi telefonda aç / open this on your phone
53
54  server.on("/", HTTP_GET, handleRoot);
55  server.on("/open", HTTP_POST, handleOpen);
56  server.begin();
57}
58
59void loop() {
60  server.handleClient();
61  if (isOpen && millis() - openedAt >= OPEN_MS) {   // süre dolunca kilitle / relock when time is up
62    digitalWrite(LOCK_PIN, LOW);
63    isOpen = false;
64  }
65}
  • The server is only reachable on your home network; to open it from outside, use an intermediary such as a Telegram bot or MQTT instead of opening a port on your router.
  • The password the browser asks for travels almost as plain text on the network; that's acceptable at home, but your Wi-Fi password must be strong and you must change WEB_PASS.
  • The open request is sent as POST, so the browser preloading the page or reopening it from history can't trigger the lock by itself.
  • For more on the web page and showing live status, see ESP32 web server and WebSocket.

Common mistakes and how to fix them

SymptomCauseFix
The lock clicks but doesn't openNot enough adapter current or the voltage sagsUse a 12 V 2 A supply and a 470 µF capacitor
Arduino resets when the lock opensNo flyback diode or grounds not sharedFit the diode and join grounds at one point
The MOSFET gets hotNot logic level (e.g. IRF520) or gate resistor too largeUse an IRLZ44N, or IRLB8721/AO3400 on an ESP32
The lock opens briefly at power-upThe gate is floatingAdd 10 kΩ between gate and GND
The lock never closes, always openMOSFET shorted (often from running without a diode)Replace the MOSFET and add the diode
The coil gets very hotIt stays energised too longLimit the open time or lower the holding power with PWM
When testing the lock for the first time, set the code aside and touch the lock's two leads straight to the 12 V adapter for one second. If the bolt retracts, the lock and adapter are fine and the problem is in the driver circuit. If it doesn't, first check with a multimeter that the adapter really delivers 12 V and enough current.

With a MOSFET, a diode and a few lines of code, a solenoid lock can be one of your first projects that physically opens and closes something in the real world. In the BlueGrays app you'll find projects such as RFID authentication, a keypad and LCD code lock, a smart electronic safe and an ESP32 RFID door lock, each with circuit diagrams and code step by step, ready for the solenoid driver circuit from this article.

Frequently asked questions

Can a solenoid lock be connected directly to an Arduino?

No. A 12 V solenoid lock draws 0.5-1 A, while an Arduino pin supplies at most 20-40 mA at 5 V. Power the lock from a separate 12 V supply through a logic-level MOSFET (such as an IRLZ44N) or a relay module. Don't forget the flyback diode across the coil.

How many amps does a solenoid lock draw?

The 12 V cabinet-style locks used in hobby projects usually draw 0.5-1 A, most often 0.6-0.8 A. You can measure the coil resistance and calculate it with I = V / R; a 16 Ω coil draws 0.75 A at 12 V. Pick a power supply rated for at least twice that.

Which MOSFET should I use for a solenoid lock?

On 5 V boards like the Arduino Uno, logic-level MOSFETs such as the IRLZ44N or IRL540N work well. On 3.3 V boards like the ESP32 and Pico, choose models that turn fully on at low voltage, such as the IRLB8721 or AO3400. IRF520 modules aren't recommended because they need a 10 V gate.

Why is a flyback diode needed?

When the current in a coil is cut, the magnetic field collapses and produces a reverse voltage spike of hundreds of volts. That spike damages the MOSFET, resets the Arduino or harms its pin. A diode such as a 1N4007, connected in reverse across the lock, safely absorbs the spike.

Can a solenoid lock be kept open continuously?

Most cheap cabinet locks are designed for intermittent duty and get very hot within minutes when energised continuously. Limit the open time in software to a few seconds. If it must stay open longer, give full power at pull-in and then lower the holding power with PWM.

Does a solenoid lock open when the power goes out?

Cabinet-style solenoid locks are fail-secure, which means they stay locked when the power is cut. Electromagnetic door locks are fail-safe and open when power is lost. Fail-safe locks are preferred on escape-route doors, fail-secure locks on safes and cabinets.

See all projects
Smart Electronic Safe
AR-92Advanced
Premium

Smart Electronic Safe

A small safe for your valuables that opens with a code. You type your four-digit code on the keypad; if it is right, the servo motor opens the lock, the green light comes on and the screen shows the…

4.7(42)
63
Password Lock with 4x4 Keypad and LCD
AR-64Advanced
Premium

Password Lock with 4x4 Keypad and LCD

A small electronic door lock that keeps out anyone who doesn't know the code. You press the hash key and type the code on the keypad; if it is right, the screen says access granted, the green LED…

4.8(59)
75
RFID Authentication
AR-54Intermediate
Premium

RFID Authentication

Just like the card entry at an apartment door: you hold your card near the RFID reader, and the Arduino compares its number with the one it has saved.

4.8(65)
84
RFID Value Reading
AR-53Beginner
Premium

RFID Value Reading

Your building key fob or access card hides a secret ID number, and this project reads it. Hold the card near the RFID reader and the Arduino writes the card's number to your computer screen.

4.7(47)
61
ESP32 RFID Door Lock (RC522 + Servo + OLED + Buzzer + LED)
ES-35Advanced
Premium

ESP32 RFID Door Lock (RC522 + Servo + OLED + Buzzer + LED)

We build a smart door lock with an ESP32, an RC522 RFID module, an SG90 servo, an SSD1306 OLED display, an active buzzer and 2 LEDs. When a card is scanned, its UID is checked against the authorized cards defined in the code; if it matches, the servo unlocks (green LED + 2 short beeps) and locks again after 5 seconds. An unknown card lights the red LED, gives 3 quick beeps and shows its UID on the OLED.

4.8(9)
16
ESP32 RFID RC522 Card Reader (with LCD)
ES-21Intermediate

ESP32 RFID RC522 Card Reader (with LCD)

In this project, we will connect the MFRC522-based RC522 RFID module to the ESP32 via SPI and read the card/tag UID. This forms the basis for applications such as door locks, membership systems, and access control. We will display the read UID on an LCD screen; this version does not compare it with an authorized card list. WARNING: The RC522 operates only at 3.3V; supplying 5V will burn out the module!

4.8(21)
42
3x4 Keypad Operation
AR-61Beginner

3x4 Keypad Operation

The Arduino instantly knows which key you press on a 12-key keypad that looks like a phone dial pad, and writes it on your computer screen.

4.5(24)
32
Lighting 220V Bulb with Push Button
AR-19Advanced
Premium

Lighting 220V Bulb with Push Button

As long as you hold the button, a real 220-volt bulb stays lit, and it goes out the moment you let go.

4.4(30)
38