Arduino UNO Q - Electromagnetic Lock

An electromagnetic lock (maglock) uses an electromagnet to hold a door shut — when energized, it creates a powerful magnetic force that keeps the door locked. With Arduino UNO Q and a relay, you can lock and unlock a door programmatically. Add Bridge and Telegram for full remote control from anywhere.

In this tutorial, you will learn:

Arduino UNO Q Electromagnetic Lock

Hardware Preparation

1×Arduino UNO Q
1×USB Cable for Arduino Uno Q
1×Electromagnetic Lock
1×Relay
1×12V Power Adapter
1×DC Power Jack
1×Jumper Wires
1×Recommended: Screw Terminal Block Shield for Arduino Uno
1×Recommended: Sensors/Servo Expansion Shield for Arduino Uno
1×Recommended: Breadboard Shield for Arduino Uno
1×Recommended: Enclosure for Arduino Uno
1×Recommended: Prototyping Base Plate & Breadboard Kit for Arduino UNO

Or you can buy the following kits:

1×DIYables Sensor Kit (18 sensors/displays)
Disclosure: Some of the links provided in this section are Amazon affiliate links. We may receive a commission for any purchases made through these links at no additional cost to you.
Additionally, some of these links are for products from our own brand, DIYables .

Overview of the Electromagnetic Lock

Pinout

An electromagnetic lock has two parts:

  • Electromagnet — has two terminals; connect to 12V power through a relay
  • Armature plate — attaches to the door; no wiring needed
Electromagnetic Lock Pinout

Install the electromagnet on the door frame (fixed part) and the armature plate on the door (moving part). When the door is closed, the two parts should be flush against each other.

How It Works

  • When the electromagnet receives power → magnetic field is generated → armature plate is attracted → door is locked
  • When the electromagnet has no power → no magnetic field → armature plate is released → door is unlocked

※ NOTE THAT:

The electromagnetic lock requires 12V DC — it must NEVER be connected directly to an Arduino UNO Q pin. Always use a relay as the interface. The MCU controls the relay, which switches the 12V supply to the electromagnet.

When the relay is wired in normally open configuration:

  • Relay open (pin LOW) → no power to electromagnet → door unlocked
  • Relay closed (pin HIGH) → power to electromagnet → door locked

This is the opposite of a solenoid lock: energized = locked.

Wiring Diagram

The wiring diagram between Arduino UNO Q Electromagnetic Lock

This image is created using Fritzing. Click to enlarge image

Connect the relay module IN pin to MCU pin D3. Connect the relay's COM and NO terminals between the 12V supply and the electromagnet. Connect the relay's VCC to 5V and GND to GND.

Relay Pin Arduino UNO Q MCU
GND GND
VCC 5V
IN D3

How To Program For Electromagnetic Lock

  • Set up the relay pin as output:
pinMode(RELAY_PIN, OUTPUT);
  • Lock and unlock the electromagnetic lock:
digitalWrite(RELAY_PIN, HIGH); // lock (electromagnet ON) delay(5000); digitalWrite(RELAY_PIN, LOW); // unlock (electromagnet OFF) delay(5000);

Arduino UNO Q Code

The Arduino UNO Q has two processors working together:

  • The STM32 MCU controls the relay that switches power to the electromagnet — all timing and state logic runs on the MCU
  • The Qualcomm MPU runs Debian Linux and handles Wi-Fi, Python, and cloud connectivity
  • In this section, only the MCU is programmed — the Linux side stays idle. A later section shows how both processors work together via Bridge.

This code locks the electromagnetic lock for 5 seconds, then unlocks it — repeating continuously.

/* * This Arduino UNO Q code was developed by newbiely.com * * This Arduino UNO Q code is made available for public use without any restriction * * For comprehensive instructions and wiring diagrams, please visit: * https://newbiely.com/tutorials/arduino-uno-q/arduino-uno-q-electromagnetic-lock */ // COPYRIGHT newbiely.com // AUTHOR: newbiely // This code is made available for public use without restriction. // For complete instructions, tutorials, and further information, visit: // https://newbiely.com/tutorials/arduino-uno-q/arduino-uno-q-electromagnetic-lock // This code locks and unlocks the electromagnetic lock every 5 seconds. // The relay is connected to the electromagnetic lock which requires a 12V power supply. // HIGH = electromagnet ON = door LOCKED // LOW = electromagnet OFF = door UNLOCKED #define RELAY_PIN 3 // The Arduino UNO Q MCU pin connected to the relay IN pin void setup() { Serial.begin(9600); pinMode(RELAY_PIN, OUTPUT); Serial.println("Arduino UNO Q Electromagnetic Lock ready"); } void loop() { Serial.println("Locking..."); digitalWrite(RELAY_PIN, HIGH); // lock the door (electromagnet ON) delay(5000); Serial.println("Unlocking..."); digitalWrite(RELAY_PIN, LOW); // unlock the door (electromagnet OFF) delay(5000); }

Detailed Instructions

First time with Arduino UNO Q? Follow the Getting Started with Arduino UNO Q tutorial before proceeding.

  • Install: Attach the electromagnet to the door frame and the armature plate to the door.
  • Connect: Wire the electromagnetic lock, relay, and 12V power supply to the Arduino UNO Q MCU as shown in the wiring diagram.
  • Open Arduino App Lab: Launch Arduino App Lab and wait until it detects your Arduino UNO Q.
  • Create a new App: Click the Create New App button.
Create New App in Arduino App Lab on Arduino UNO Q
  • Give the App a name, for example: ElectromagneticLock
  • Click Create to confirm.
Arduino App Lab App folders and files on Arduino UNO Q
  • Paste the sketch: Copy the MCU code above and paste it into sketch/sketch.ino. Keep other files as default.
  • No library required — uses only the built-in digitalWrite() function.
  • Upload: Click the Run button in Arduino App Lab.
Click Run button in Arduino App Lab on Arduino UNO Q
  • Bring the armature plate close to the electromagnet and observe it being held and released every 5 seconds.

App Lab Console Output

DIYables_Apps
Stop
sketch.ino
1#include "Arduino_RouterBridge.h"
Serial Monitor
Python
Message (Enter to send a message to "Newbiely" on usb(2820070321))
New Line
9600 baud
[2026-04-29 09:00:01] Arduino UNO Q Electromagnetic Lock ready [2026-04-29 09:00:01] Locking... [2026-04-29 09:00:06] Unlocking... [2026-04-29 09:00:11] Locking... [2026-04-29 09:00:16] Unlocking...

Bridge: Linux + MCU

This section shows how to program both processors of the Arduino UNO Q so the Linux side can lock and unlock the electromagnetic lock via Bridge:

  • The electromagnetic lock is connected to the MCU via relay — the MCU controls the relay output pin
  • The MPU cannot control the relay directly — it calls Bridge functions to lock or unlock
  • The MPU has Wi-Fi — running full Debian Linux, it can accept commands from Telegram or any web service and translate them into lock/unlock actions
  • Arduino_RouterBridge enables RPC communication between the two processors
  • ⚠️ /dev/ttyHS1 (Linux) and Serial1 (MCU) are RESERVED by the router — never open them in user code

In short: MPU receives lock/unlock commands → calls Bridge → MCU controls relay → electromagnetic lock activates.

MCU Code (Bridge)

/* * This Arduino UNO Q code was developed by newbiely.com * * This Arduino UNO Q code is made available for public use without any restriction * * For comprehensive instructions and wiring diagrams, please visit: * https://newbiely.com/tutorials/arduino-uno-q/arduino-uno-q-electromagnetic-lock */ // COPYRIGHT newbiely.com // AUTHOR: newbiely // This code is made available for public use without restriction. // For complete instructions, tutorials, and further information, visit: // https://newbiely.com/tutorials/arduino-uno-q/arduino-uno-q-electromagnetic-lock #include "Arduino_RouterBridge.h" #define RELAY_PIN 3 // The Arduino UNO Q MCU pin connected to the relay IN pin // HIGH = electromagnet ON = LOCKED // LOW = electromagnet OFF = UNLOCKED bool is_locked = false; String lock_door(String arg) { digitalWrite(RELAY_PIN, HIGH); is_locked = true; Monitor.println("Electromagnetic lock: LOCKED"); return "locked"; } String unlock_door(String arg) { digitalWrite(RELAY_PIN, LOW); is_locked = false; Monitor.println("Electromagnetic lock: UNLOCKED"); return "unlocked"; } String get_state(String arg) { return is_locked ? "locked" : "unlocked"; } void setup() { Bridge.begin(); Monitor.begin(); pinMode(RELAY_PIN, OUTPUT); digitalWrite(RELAY_PIN, LOW); // start unlocked is_locked = false; Bridge.provide_safe("lock", lock_door); Bridge.provide_safe("unlock", unlock_door); Bridge.provide("get_state", get_state); Monitor.println("Arduino UNO Q Electromagnetic Lock Bridge ready"); Monitor.println("Initial state: UNLOCKED"); } void loop() {}

Python Code (Bridge)

/* * This Arduino UNO Q code was developed by newbiely.com * * This Arduino UNO Q code is made available for public use without any restriction * * For comprehensive instructions and wiring diagrams, please visit: * https://newbiely.com/tutorials/arduino-uno-q/arduino-uno-q-electromagnetic-lock */ # COPYRIGHT newbiely.com # AUTHOR: newbiely # This code is made available for public use without restriction. # For complete instructions, tutorials, and further information, visit: # https://newbiely.com/tutorials/arduino-uno-q/arduino-uno-q-electromagnetic-lock from arduino.app_utils import * import time def loop(): state = Bridge.call("get_state") print(f"Electromagnetic lock state: {state}") # Example: lock for 5 seconds, then unlock if state == "unlocked": print("Locking...") Bridge.call("lock") time.sleep(5) print("Unlocking...") Bridge.call("unlock") time.sleep(1) App.run(user_loop=loop)

Detailed Instructions

  • Connect: Wire the electromagnetic lock, relay, and 12V power supply to the Arduino UNO Q as shown in the wiring diagram.
  • Open Arduino App Lab: Launch Arduino App Lab and wait for the board to be detected.
  • Create a new App: Click Create New App, name it ElectromagneticLockBridge, then click Create.
  • Paste the MCU sketch: Copy the MCU Bridge code above and paste it into sketch/sketch.ino.
  • Paste the Python code: Copy the Python Bridge code above and paste it into the Python file in the App.
  • Install the library: Click the Add sketch library button (the open book icon with a + sign) in the left sidebar.
Add sketch library in Arduino App Lab on Arduino UNO Q
  • Search for Arduino_RouterBridge created by Arduino and click the Install button.
My Apps / DIYables Apps
Run
Bricks
No bricks added...
Sketch Libraries
No sketch libra...
Files
python
sketch
.gitignore
README.md
app.yaml
sketch.ino
Add sketch library
Arduino_RouterBridge Arduino

This library provides a simple RPC bridge for Arduino UNO Q boards, allowing communication between the board and other devices using MsgPack serialization.

0.4.1
Install
More Info
  • Upload: Click the Run button in Arduino App Lab.
Click Run button in Arduino App Lab on Arduino UNO Q
  • Watch the lock cycle: lock → wait 5 seconds → unlock → wait 1 second → repeat.

App Lab Console Output

DIYables_Apps
Stop
sketch.ino
1#include "Arduino_RouterBridge.h"
Serial Monitor
Python
Message (Enter to send a message to "Newbiely" on usb(2820070321))
New Line
9600 baud
[2026-04-29 09:00:01] Arduino UNO Q Electromagnetic Lock Bridge ready [2026-04-29 09:00:01] Initial state: UNLOCKED [2026-04-29 09:00:02] Electromagnetic lock: LOCKED [2026-04-29 09:00:07] Electromagnetic lock: UNLOCKED
DIYables_Apps
Stop
sketch.ino
1#include "Arduino_RouterBridge.h"
Serial Monitor
Python
[2026-04-29 09:00:02] Electromagnetic lock state: unlocked [2026-04-29 09:00:02] Locking... [2026-04-29 09:00:07] Unlocking... [2026-04-29 09:00:08] Electromagnetic lock state: unlocked

Telegram

Control the electromagnetic lock remotely via Telegram — lock and unlock a door from anywhere with a simple command.

MCU sketch: Keep the same MCU sketch from the previous Bridge section.

Python Code (Telegram)

/* * This Arduino UNO Q code was developed by newbiely.com * * This Arduino UNO Q code is made available for public use without any restriction * * For comprehensive instructions and wiring diagrams, please visit: * https://newbiely.com/tutorials/arduino-uno-q/arduino-uno-q-electromagnetic-lock */ # COPYRIGHT newbiely.com # AUTHOR: newbiely # This code is made available for public use without restriction. # For complete instructions, tutorials, and further information, visit: # https://newbiely.com/tutorials/arduino-uno-q/arduino-uno-q-electromagnetic-lock from arduino.app_utils import * import requests import time TELEGRAM_BOT_TOKEN = "YOUR_TELEGRAM_BOT_TOKEN" CHAT_ID = "YOUR_CHAT_ID" last_update_id = 0 def get_updates(): global last_update_id url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/getUpdates" params = {"offset": last_update_id + 1, "timeout": 5} try: response = requests.get(url, params=params, timeout=10) data = response.json() if data["ok"]: return data["result"] except Exception as e: print(f"Error getting updates: {e}") return [] def send_message(chat_id, text): url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage" payload = {"chat_id": chat_id, "text": text} try: requests.post(url, data=payload, timeout=10) except Exception as e: print(f"Error sending message: {e}") def loop(): updates = get_updates() for update in updates: last_update_id = update["update_id"] if "message" not in update: continue message = update["message"] chat_id = message["chat"]["id"] text = message.get("text", "").strip() print(f"Received: {text}") if text == "/start": send_message(chat_id, "Arduino UNO Q Electromagnetic Lock Bot\n" "/lock - Lock the electromagnetic lock\n" "/unlock - Unlock the electromagnetic lock\n" "/state - Read current lock state") elif text == "/lock": result = Bridge.call("lock") send_message(chat_id, f"🔒 Lock state: {result}") elif text == "/unlock": result = Bridge.call("unlock") send_message(chat_id, f"🔓 Lock state: {result}") elif text == "/state": result = Bridge.call("get_state") send_message(chat_id, f"Lock state: {result}") else: send_message(chat_id, "Unknown command. Send /start for help.") time.sleep(1) App.run(user_loop=loop)

Detailed Instructions

  • Replace YOUR_TELEGRAM_BOT_TOKEN with your actual bot token from BotFather.
  • Replace YOUR_CHAT_ID with your Telegram chat ID.
  • Paste this Python code into your App's Python file (keep the same MCU sketch).
  • Click the Run button. Send /lock from Telegram to lock the door, then /unlock to release it.

App Lab Console Output

DIYables_Apps
Stop
sketch.ino
1#include "Arduino_RouterBridge.h"
Serial Monitor
Python
[2026-04-29 09:10:00] Waiting for Telegram messages... [2026-04-29 09:10:05] Received: /lock [2026-04-29 09:10:12] Received: /state [2026-04-29 09:10:20] Received: /unlock
Telegram
Telegram 12:45
Welcome to Telegram!
ArduinoBot 10:19
Chatting with Arduino...
telegram-botfather
BotFather Yesterday
Your bot has been created.

ArduinoBot

bot
Today
/state
10:15 AM ✓✓
Lock state: unlocked
10:16 AM
/lock
10:17 AM ✓✓
🔒 Lock state: locked
10:18 AM
/state
10:19 AM ✓✓
Lock state: locked
10:20 AM
/unlock
10:21 AM ✓✓
🔓 Lock state: unlocked
10:22 AM

OpenClaw

...OPENCLAW

OpenClaw support for Arduino UNO Q Electromagnetic Lock is coming soon.

...OPENCLAW

Project Ideas

You can build many useful projects with the electromagnetic lock and Arduino UNO Q:

  • Telegram-Controlled Door Lock: Lock and unlock an office door or storage room remotely via Telegram — /lock to secure it and /unlock to let someone in, all logged with timestamps on the Linux side
  • Time-Based Auto-Lock: Program the MPU to automatically lock at night (e.g., 10 PM) and unlock in the morning (7 AM) using the Linux system clock — no manual intervention required
  • Keypad Security System: Pair the electromagnetic lock with a 4x4 keypad on the MCU — unlock on correct PIN entry, send a Telegram alert on three consecutive failed attempts
  • RFID Access Control: Combine with an RFID reader on the MCU — scan a registered tag to unlock, log every access event to a file on Linux with the tag ID and timestamp
  • Remote Access Log Dashboard: Every lock/unlock event is logged to a CSV file on Linux with timestamp and source (Telegram, automatic, or keypad) — Python sends a daily summary report to Telegram

Challenge Yourself

Ready to go further with the electromagnetic lock on Arduino UNO Q? Try these challenges:

  • Easy: Add a /unlock_10s Telegram command that unlocks the door for exactly 10 seconds using time.sleep(10) on the Python side before calling Bridge.call("lock") to re-engage the electromagnet.
  • Medium: Implement an auto-lock timer: when /unlock is called via Telegram, start a Python timer — if the door is not manually relocked within 60 seconds, the system automatically calls Bridge.call("lock") and sends a Telegram confirmation.
  • Advanced: Build a multi-user access system where an admin file lists authorized Telegram user IDs — only those users can send /unlock, unauthorized attempts trigger a Telegram alert to the admin, and all access attempts are logged with user ID and timestamp.

※ OUR MESSAGES

  • As freelancers, We are AVAILABLE for HIRE. See how to outsource your project to us
  • Please feel free to share the link of this tutorial. However, Please do not use our content on any other websites. We invested a lot of effort and time to create the content, please respect our work!