Arduino Mega - Solenoid Lock
This guide shows you how to use the Arduino Mega board and a solenoid lock to lock or unlock a door, cabinet, or drawer. Here is what we will learn:
- How to connect a solenoid lock to an Arduino Mega.
- How to write code for the Arduino Mega to control the solenoid lock.

Hardware Preparation
| 1 | × | Arduino Mega | |
| 1 | × | USB 2.0 cable type A/B (for USB-A PC) | |
| 1 | × | USB 2.0 cable type C/B (for USB-C PC) | |
| 1 | × | Solenoid Lock | |
| 1 | × | Relay | |
| 1 | × | 12V Power Adapter | |
| 1 | × | DC Power Jack |
Or you can buy the following kits:
| 1 | × | DIYables Sensor Kit (30 sensors/displays) | |
| 1 | × | DIYables Sensor Kit (18 sensors/displays) |
Additionally, some of these links are for products from our own brand, DIYables .
Overview of Solenoid Lock
A solenoid lock, also called an electric strike lock, locks and unlocks cabinets, drawers, and doors.
Pinout
A solenoid lock uses two wires.
- Connect the red wire (positive) to the 12V DC power supply.
- Connect the black wire (negative) to the ground (GND) of the power supply.

How It Works
- When the electric lock has power, the latch extends and the door is locked.
- When there is no power, the latch retracts and the door is unlocked.
※ NOTE THAT:
The solenoid lock usually needs a power supply of 12V, 24V, or 48V. Do not connect the lock directly to an Arduino Mega pin. Instead, use a relay between the lock and the Arduino Mega pin.
If we connect the solenoid lock to a relay that is normally open:
- If the switch is off, the door is unlocked.
- If the switch is on, the door is locked.
Connect an Arduino Mega to a relay to control a solenoid lock. Learn more about using a relay with Arduino Mega in our guide: Arduino Mega - Relay Tutorial.
Wiring Diagram

This image is created using Fritzing. Click to enlarge image
Arduino Mega Code
This program locks and unlocks the door every five seconds.
Detailed Instructions
Follow these steps one by one.
- Connect the solenoid lock to the Arduino Mega as shown in the diagram.
- Connect the Arduino Mega to your computer with a USB cable.
- Open the Arduino IDE on your computer.
- Choose the correct board (Arduino Mega) and the right COM port.
- Copy the code and open it in the Arduino IDE.
- Click the Upload button in the Arduino IDE to send the code to the Arduino Mega.
- Check the lock bolt position.