Arduino MKR WiFi 1010 - Electromagnetic Lock

Learn how to control an electromagnetic lock (also called magnetic lock, maglock, or EM lock) with the Arduino MKR WiFi 1010 to create secure access control systems for doors, cabinets, gates, and automated entry points. Electromagnetic locks are essential components for building smart door systems, office security, apartment entry control, cabinet locking mechanisms, automatic gates, server room access, storage lockers, museum display cases, and IoT security projects. In this comprehensive tutorial, you'll discover how to connect an electromagnetic lock to your Arduino MKR WiFi 1010 board through a relay module, understand the difference between electromagnetic locks and solenoid locks, control high-power locks safely with relay isolation, program lock and unlock sequences with proper timing, implement fail-safe vs fail-secure configurations, integrate with buttons, keypads, and RFID systems, and create intelligent access control logic. This guide includes complete wiring diagrams for Arduino MKR WiFi 1010 electromagnetic lock connections with relay control, working example code with detailed explanations, power supply recommendations for 12V/24V electromagnetic locks, troubleshooting tips for magnetic holding force and relay control issues, and 10 creative challenge projects to expand your Arduino MKR WiFi 1010 electromagnetic lock applications. Whether you're building a smart door lock, automated access control system, security cabinet, or magnetic entry gate with your Arduino MKR WiFi 1010, this tutorial provides everything you need to work with electromagnetic locks safely and effectively.

Arduino MKR WiFi 1010 Electromagnetic Lock

Hardware Preparation

1×Arduino MKR WiFi 1010
1×Micro USB Cable
1×Electromagnetic Lock
1×Relay
1×12V Power Adapter
1×Optionally, DC Power Jack
1×Breadboard
1×Jumper Wires

Or you can buy the following kits:

1×DIYables Sensor Kit (30 sensors/displays)
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 Electromagnetic Lock

An electromagnetic lock (maglock) uses electromagnetic force to secure doors and entry points. When electricity flows through the electromagnet coil, it creates a powerful magnetic field that holds the metal armature plate with significant force - typically ranging from 280 kg (600 lbs) to over 550 kg (1200 lbs) of holding force. Unlike mechanical locks with moving parts, electromagnetic locks have no latches, bolts, or cylinders, making them extremely reliable and resistant to picking or tampering. They're commonly used in commercial buildings, access control systems, and high-security areas where fail-safe operation is required (lock releases when power is lost for emergency exit).

Electromagnetic Lock vs Solenoid Lock

Feature Electromagnetic Lock Solenoid Lock
Operation Principle Magnetic attraction force Mechanical bolt movement
Holding Force Very high (280-550+ kg) Lower (up to 100 kg)
Moving Parts None (except armature alignment) Moving bolt/latch mechanism
Durability Extremely high (no wear) Moderate (mechanical wear)
Failure Mode Fail-safe (unlocks on power loss) Fail-secure (stays locked)
Installation Surface mount, needs alignment Requires door frame drilling
Noise Level Silent operation Audible clicking sound
Power Consumption Continuous (while locked) Momentary pulse to actuate
Typical Voltage 12V DC or 24V DC 12V DC
Best Use Case Emergency exit doors, offices Cabinets, drawers, gates

Electromagnetic Lock Pinout

The electromagnetic lock consists of two main components:

  • Armature plate: Metal plate attached to the moving door/gate section. Contains ferromagnetic material that responds to magnetic fields.
  • Electromagnet: Mounted on the fixed door frame. Has two wire terminals (red positive, black negative) that connect to DC power supply.

When the door is closed, the armature plate and electromagnet surfaces make full contact for maximum holding force.

Electromagnetic Lock Pinout

How Electromagnetic Lock Works

Electromagnetic locks operate on the principle of electromagnetism:

LOCKED STATE (Power Applied):

  • Arduino MKR WiFi 1010 pin is set HIGH (3.3V)
  • This activates the relay module
  • Relay switches ON and connects 12V DC power to the electromagnet
  • Electric current flows through the electromagnet coil, creating a strong magnetic field
  • The magnetic field generates attractive force (280-550 kg)
  • Armature plate is pulled tightly against the electromagnet
  • Door is securely LOCKED and cannot be opened

UNLOCKED STATE (Power Removed):

  • Arduino MKR WiFi 1010 pin is set LOW (0V)
  • This deactivates the relay module
  • Relay switches OFF and disconnects power from the electromagnet
  • No current flows through the electromagnet coil
  • Magnetic field collapses immediately
  • No attractive force between electromagnet and armature plate
  • Door is free to open - UNLOCKED state

Why Use a Relay?

  • Electromagnetic locks require high voltage (12V DC) and high current (500mA-1A)
  • Arduino MKR WiFi 1010 pins can only provide 3.3V at 7mA maximum
  • Direct connection would damage the Arduino board
  • Relay acts as an electrical switch controlled by low-power Arduino signal
  • Relay safely controls high-power electromagnet circuit

Control Logic with Arduino MKR WiFi 1010:

Electromagnetic locks require high voltage (12V or 24V DC) and high current (500mA to 1A), which exceeds the Arduino MKR WiFi 1010's pin capabilities (3.3V, 7mA maximum). Therefore, we use a relay module as an electrical switch:

  • Arduino Pin LOW (0V) Relay OFF No power to electromagnet Door UNLOCKED
  • Arduino Pin HIGH (3.3V) Relay ON 12V power to electromagnet Door LOCKED

The relay provides electrical isolation between the Arduino MKR WiFi 1010's low-power control circuit and the electromagnetic lock's high-power circuit, protecting your board from damage. Check out the Arduino MKR WiFi 1010 Relay tutorial for detailed relay operation principles.

Wiring Diagram

This image is created using Fritzing. Click to enlarge image.

The wiring diagram between Arduino MKR WiFi 1010 Electromagnetic Lock

This image is created using Fritzing. Click to enlarge image

If you're unfamiliar with how to supply power to the Arduino MKR WiFi 1010 and other components, please refer to the Arduino MKR WiFi 1010 - How to Power tutorial for detailed instructions.

Wiring Instructions:

Arduino MKR WiFi 1010 Relay Module 12V Power Supply Electromagnetic Lock
Pin 2 IN
GND GND
VCC (not used)
COM (+) Positive
NO (+) Red Wire
NC (don't use)
(-) Negative (-) Black Wire

Important Wiring Notes:

  • Connect relay VCC to 5V if your relay module requires 5V (most relay modules have onboard voltage regulators)
  • Some relay modules can work with 3.3V signal - check your relay specifications
  • The electromagnetic lock typically comes with red (+) and black (-) wires
  • CRITICAL: Never connect the electromagnetic lock directly to Arduino pins - always use a relay
  • Use a 12V DC power adapter rated for at least 1A (check your electromagnetic lock specifications)
  • Keep high-power wires (12V supply, lock wires) separated from Arduino signal wires
  • Ensure all ground connections are secure for proper relay operation

Arduino MKR WiFi 1010 Code

The code below locks and unlocks the door every five seconds.

/* * This Arduino MKR WiFi 1010 code was developed by newbiely.com * * This Arduino MKR WiFi 1010 code is made available for public use without any restriction * * For comprehensive instructions and wiring diagrams, please visit: * https://newbiely.com/tutorials/arduino-mkr/arduino-mkr-wifi-1010-electromagnetic-lock */ // constants won't change const int RELAY_PIN = A5; // the Arduino pin, which connects to the IN pin of relay // the setup function runs once when you press reset or power the board void setup() { // initialize digital pin A5 as an output. pinMode(RELAY_PIN, OUTPUT); } // the loop function runs over and over again forever void loop() { digitalWrite(RELAY_PIN, HIGH); // lock the door delay(5000); digitalWrite(RELAY_PIN, LOW); // unlock the door delay(5000); }

Detailed Instructions

New to Arduino MKR WiFi 1010? Complete our Getting Started with Arduino MKR WiFi 1010 tutorial first to set up your development environment.

Follow these steps to control your electromagnetic lock:

  • Wire the components according to the wiring diagram above. Double-check all connections:
    • Arduino Pin 2 to Relay IN
    • Arduino GND to Relay GND
    • 12V Power (+) to Relay COM
    • Relay NO to Electromagnetic Lock (+) red wire
    • 12V Power (-) to Electromagnetic Lock (-) black wire
  • Connect the 12V power adapter to your relay circuit (do NOT connect to Arduino)
  • Mount the electromagnetic lock on a fixed surface (door frame)
  • Position the armature plate on the moving part (door) so it aligns with the electromagnet when closed
  • Plug your Arduino MKR WiFi 1010 into your computer's USB port
  • Launch the Arduino IDE on your computer
  • Select the correct board and port:
    • Go to Tools → Board → Arduino SAMD Boards → Arduino MKR WiFi 1010
    • Go to Tools → Port and select your Arduino's COM port
  • Copy the code provided above
  • Paste it into the Arduino IDE
  • Click the Upload button (right arrow icon) to compile and upload the code
  • Wait for the upload to complete - you'll see "Done uploading" when finished
  • Open the Serial Monitor by clicking the magnifying glass icon (top-right) or pressing Ctrl+Shift+M
  • Set the baud rate to 9600 in the Serial Monitor dropdown
  • Observe the behavior:
    • Bring the armature plate close to the electromagnet surface
    • You should hear a click from the relay when it switches
    • The electromagnet will pull and hold the armature plate firmly (locked state)
    • After 5 seconds, the relay clicks again and the armature plate releases (unlocked state)
    • The cycle repeats automatically every 5 seconds

    Result on Serial Monitor

    You should see output similar to this in the Serial Monitor:

    COM6
    Send
    The door is locked The door is unlocked The door is locked The door is unlocked The door is locked The door is unlocked ...
    Autoscroll Show timestamp
    Clear output
    9600 baud  
    Newline  

    Testing Tips:

    • You should feel strong magnetic attraction when the lock is engaged (locked state)
    • The armature plate should be difficult to pull away when locked (280-550 kg holding force)
    • The lock should release immediately when unlocked (no holding force)
    • If the lock doesn't hold well, ensure surfaces are clean and making full contact
    • Check the Serial Monitor to verify the lock/unlock sequence timing

Troubleshooting

Here are solutions to common issues when working with electromagnetic locks and Arduino MKR WiFi 1010:

Problem 1: Lock Doesn't Hold at All

Symptoms: Door can be opened easily even when system shows "locked" state.

Possible Causes:

  • Insufficient power supply to electromagnet
  • Poor contact between armature plate and electromagnet
  • Relay not switching properly
  • Wrong polarity connection (though DC electromagnets usually work either way)

Solution:

// Add diagnostic code to verify relay operation const int RELAY_PIN = 2; void setup() { Serial.begin(9600); pinMode(RELAY_PIN, OUTPUT); } void loop() { digitalWrite(RELAY_PIN, HIGH); Serial.println("Relay ON - Check if electromagnet pulls"); Serial.println("Measure voltage at lock terminals (should be 12V)"); delay(10000); digitalWrite(RELAY_PIN, LOW); Serial.println("Relay OFF - Lock should release"); delay(10000); }

Check:

  1. Measure voltage at electromagnet terminals when locked (should be 12V)
  2. Verify relay LED indicator turns on/off with Arduino commands
  3. Ensure armature plate and electromagnet surfaces are clean and flat
  4. Check power supply can deliver sufficient current (500mA-1A)

Problem 2: Lock Works Initially, Then Fails

Symptoms: Lock holds for a few seconds then releases, or works once then stops.

Possible Causes:

  • Power supply overheating or insufficient capacity
  • Relay contacts overheating due to high current
  • Electromagnet overheating causing thermal shutdown
  • Loose wiring connections

Solution: Use proper rated components and add status monitoring:

const int RELAY_PIN = 2; const int STATUS_LED = 3; unsigned long lockStartTime = 0; const unsigned long MAX_LOCK_TIME = 300000; // 5 minutes max void setup() { Serial.begin(9600); pinMode(RELAY_PIN, OUTPUT); pinMode(STATUS_LED, OUTPUT); } void lockDoor() { digitalWrite(RELAY_PIN, HIGH); digitalWrite(STATUS_LED, HIGH); lockStartTime = millis(); Serial.println("Door LOCKED"); } void unlockDoor() { digitalWrite(RELAY_PIN, LOW); digitalWrite(STATUS_LED, LOW); lockStartTime = 0; Serial.println("Door UNLOCKED"); } void loop() { // Safety timeout - unlock after maximum lock duration if (lockStartTime > 0 && (millis() - lockStartTime > MAX_LOCK_TIME)) { unlockDoor(); Serial.println("WARNING: Auto-unlock after max lock time"); } // Your lock/unlock logic here lockDoor(); delay(5000); unlockDoor(); delay(5000); }

Verify:

  • Power supply rated for at least 1.5x the electromagnet's current draw
  • Relay rated for lock's voltage and current (use 10A relay minimum)
  • Adequate ventilation for lock, relay, and power supply

Problem 3: Relay Clicks But Lock Doesn't Engage

Symptoms: You hear the relay switching, but electromagnet has no holding force.

Possible Causes:

  • Lock connected to wrong relay terminals (use COM and NO)
  • Power supply connected incorrectly through relay
  • Blown relay contacts
  • Lock wiring disconnected

Solution: Verify wiring carefully:

┌────────────────────────────────────────────┐ │ Correct Relay Wiring for Electromagnetic │ │ Lock Control │ ├────────────────────────────────────────────┤ │ │ │ Arduino Pin 2 ──────► IN (Relay Signal) │ │ Arduino GND ────────► GND (Relay) │ │ │ │ 12V Power (+) ──────► COM (Relay) │ │ Lock Wire (+) ◄─────── NO (Relay) │ │ Lock Wire (-) ──────► 12V Power (-) │ │ │ │ When Arduino Pin HIGH: │ │ Relay connects COM to NO │ │ 12V flows through lock │ │ Lock engages │ └────────────────────────────────────────────┘

Double-check:

  • Lock positive wire connects to relay NO (Normally Open) terminal
  • Power positive connects to relay COM (Common) terminal
  • Lock negative connects directly to power supply negative
  • Never use NC (Normally Closed) terminal unless you want reversed logic

Problem 4: Arduino Resets When Lock Activates

Symptoms: Arduino MKR WiFi 1010 restarts or freezes when relay switches on.

Possible Causes:

  • Insufficient power supply to Arduino
  • Electrical noise from relay coil back-EMF
  • Shared ground causing voltage spikes
  • Power supply voltage drop when lock engages

Solution: Improve power isolation and filtering:

const int RELAY_PIN = 2; void setup() { Serial.begin(9600); pinMode(RELAY_PIN, OUTPUT); // Start with lock off digitalWrite(RELAY_PIN, LOW); Serial.println("System initialized"); Serial.println("Relay control starting..."); delay(1000); // Settling time } void loop() { Serial.println("Engaging lock..."); delay(100); // Small delay before switching digitalWrite(RELAY_PIN, HIGH); Serial.println("Lock ENGAGED"); delay(5000); Serial.println("Releasing lock..."); delay(100); digitalWrite(RELAY_PIN, LOW); Serial.println("Lock RELEASED"); delay(5000); }

Improvement checklist:

  • Use separate power supplies for Arduino (USB) and electromagnet (12V adapter)
  • Never share power between Arduino and high-power electromagnet
  • Add flyback diode across relay coil if using bare relay module
  • Use optoisolated relay modules for better isolation
  • Keep Arduino and high-power wires separated

Problem 5: Lock Doesn't Release Immediately

Symptoms: Door stays locked for 1-2 seconds after unlock command.

Possible Causes:

  • Residual magnetism in electromagnet core
  • Relay slow to switch off
  • Mechanical binding between armature and electromagnet

Solution: This is usually normal behavior. Add status indication:

const int RELAY_PIN = 2; const int UNLOCK_LED = 3; void unlockDoor() { digitalWrite(RELAY_PIN, LOW); Serial.println("Unlock command sent"); // Brief delay for residual magnetism to dissipate delay(500); digitalWrite(UNLOCK_LED, HIGH); Serial.println("Door unlocked - safe to open"); } void lockDoor() { digitalWrite(UNLOCK_LED, LOW); digitalWrite(RELAY_PIN, HIGH); Serial.println("Door locked"); } void setup() { Serial.begin(9600); pinMode(RELAY_PIN, OUTPUT); pinMode(UNLOCK_LED, OUTPUT); } void loop() { lockDoor(); delay(5000); unlockDoor(); delay(5000); }

Problem 6: Lock Hums or Buzzes When Engaged

Symptoms: Audible humming noise from electromagnet when locked.

Possible Causes:

  • AC voltage applied instead of DC
  • Poor quality DC power supply with ripple
  • Loose mounting causing vibration

Solution:

  • Verify you're using DC power supply (12V DC, not 12V AC)
  • Use filtered/regulated power supply
  • Tighten all mounting screws
  • Add rubber washers to reduce vibration transmission

Electromagnetic locks should operate silently. Any buzzing indicates power quality issues.

Challenge Extensions

Once you've mastered basic electromagnetic lock control with Arduino MKR WiFi 1010, try these creative projects:

Challenge 1: Button-Controlled Door Lock

Add a push button to lock/unlock the door manually:

const int RELAY_PIN = 2; const int BUTTON_PIN = 3; const int STATUS_LED = 4; bool isLocked = false; bool lastButtonState = HIGH; void setup() { Serial.begin(9600); pinMode(RELAY_PIN, OUTPUT); pinMode(BUTTON_PIN, INPUT_PULLUP); pinMode(STATUS_LED, OUTPUT); digitalWrite(RELAY_PIN, LOW); // Start unlocked } void loop() { bool buttonState = digitalRead(BUTTON_PIN); // Button pressed (HIGH to LOW transition) if (lastButtonState == HIGH && buttonState == LOW) { delay(50); // Debounce isLocked = !isLocked; // Toggle lock state digitalWrite(RELAY_PIN, isLocked ? HIGH : LOW); digitalWrite(STATUS_LED, isLocked ? HIGH : LOW); Serial.println(isLocked ? "Door LOCKED" : "Door UNLOCKED"); } lastButtonState = buttonState; delay(10); }

Challenge 2: Keypad Access Control System

Use a 4x4 keypad for password-protected entry:

#include <Keypad.h> const int RELAY_PIN = 2; const char PASSWORD[] = "1234"; char enteredCode[5] = ""; int codeIndex = 0; const byte ROWS = 4; const byte COLS = 4; char keys[ROWS][COLS] = { {'1','2','3','A'}, {'4','5','6','B'}, {'7','8','9','C'}, {'*','0','#','D'} }; byte rowPins[ROWS] = {9, 8, 7, 6}; byte colPins[COLS] = {5, 4, 3, 2}; Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS); void setup() { Serial.begin(9600); pinMode(RELAY_PIN, OUTPUT); digitalWrite(RELAY_PIN, HIGH); // Start locked Serial.println("Door locked. Enter password:"); } void loop() { char key = keypad.getKey(); if (key) { if (key == '#') { // Check password if (strcmp(enteredCode, PASSWORD) == 0) { digitalWrite(RELAY_PIN, LOW); Serial.println("Access GRANTED. Door unlocked!"); delay(5000); // Keep unlocked for 5 seconds digitalWrite(RELAY_PIN, HIGH); Serial.println("Door locked."); } else { Serial.println("Access DENIED. Wrong password!"); } // Reset codeIndex = 0; memset(enteredCode, 0, sizeof(enteredCode)); } else if (key == '*') { // Clear entry codeIndex = 0; memset(enteredCode, 0, sizeof(enteredCode)); Serial.println("Entry cleared."); } else if (codeIndex < 4) { enteredCode[codeIndex++] = key; Serial.print("*"); } } }

Challenge 3: RFID Card Access System

Use RFID reader for contactless entry:

#include <SPI.h> #include <MFRC522.h> const int RELAY_PIN = 2; const int SS_PIN = 10; const int RST_PIN = 9; MFRC522 rfid(SS_PIN, RST_PIN); // Authorized card UIDs (replace with your card IDs) String authorizedCards[] = { "A1 B2 C3 D4", "E5 F6 G7 H8" }; void setup() { Serial.begin(9600); SPI.begin(); rfid.PCD_Init(); pinMode(RELAY_PIN, OUTPUT); digitalWrite(RELAY_PIN, HIGH); // Start locked Serial.println("RFID Access Control Ready"); } void loop() { if (!rfid.PICC_IsNewCardPresent() || !rfid.PICC_ReadCardSerial()) return; String cardUID = ""; for (byte i = 0; i < rfid.uid.size; i++) { cardUID += String(rfid.uid.uidByte[i], HEX); if (i < rfid.uid.size - 1) cardUID += " "; } cardUID.toUpperCase(); Serial.print("Card detected: "); Serial.println(cardUID); // Check if authorized bool authorized = false; for (int i = 0; i < sizeof(authorizedCards)/sizeof(authorizedCards[0]); i++) { if (cardUID == authorizedCards[i]) { authorized = true; break; } } if (authorized) { Serial.println("Access GRANTED"); digitalWrite(RELAY_PIN, LOW); delay(3000); digitalWrite(RELAY_PIN, HIGH); Serial.println("Door locked"); } else { Serial.println("Access DENIED"); } rfid.PICC_HaltA(); }

Challenge 4: WiFi Remote Door Control

Control the lock via web interface over WiFi:

#include <WiFiNINA.h> const char* ssid = "YourWiFiSSID"; const char* password = "YourWiFiPassword"; const int RELAY_PIN = 2; WiFiServer server(80); bool isLocked = true; void setup() { Serial.begin(9600); pinMode(RELAY_PIN, OUTPUT); digitalWrite(RELAY_PIN, HIGH); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println("\nWiFi connected"); Serial.print("Control URL: http://"); Serial.println(WiFi.localIP()); server.begin(); } void loop() { WiFiClient client = server.available(); if (!client) return; String request = client.readStringUntil('\r'); client.flush(); if (request.indexOf("/lock") != -1) { isLocked = true; digitalWrite(RELAY_PIN, HIGH); } else if (request.indexOf("/unlock") != -1) { isLocked = false; digitalWrite(RELAY_PIN, LOW); } // Send HTML response client.println("HTTP/1.1 200 OK"); client.println("Content-Type: text/html"); client.println(); client.println("<html><body>"); client.println("<h1>Door Lock Control</h1>"); client.println("<p>Status: " + String(isLocked ? "LOCKED" : "UNLOCKED") + "</p>"); client.println("<a href='/lock'><button>LOCK</button></a>"); client.println("<a href='/unlock'><button>UNLOCK</button></a>"); client.println("</body></html>"); delay(1); client.stop(); }

Challenge 5: Door Open Detection with Sensor

Add magnetic door sensor to detect forced entry:

const int RELAY_PIN = 2; const int DOOR_SENSOR_PIN = 3; const int ALARM_PIN = 4; bool isLocked = false; void setup() { Serial.begin(9600); pinMode(RELAY_PIN, OUTPUT); pinMode(DOOR_SENSOR_PIN, INPUT_PULLUP); pinMode(ALARM_PIN, OUTPUT); digitalWrite(RELAY_PIN, LOW); } void loop() { bool doorOpen = digitalRead(DOOR_SENSOR_PIN) == HIGH; if (isLocked && doorOpen) { // Door opened while locked - ALARM! digitalWrite(ALARM_PIN, HIGH); Serial.println("SECURITY ALERT: Door opened while locked!"); delay(100); digitalWrite(ALARM_PIN, LOW); delay(100); } else { digitalWrite(ALARM_PIN, LOW); } // Your lock/unlock logic here delay(100); }

Challenge 6: Scheduled Lock/Unlock Times

Automatic locking schedule using RTC module:

#include <RTClib.h> const int RELAY_PIN = 2; RTC_DS1307 rtc; // Lock at 6 PM, unlock at 8 AM const int LOCK_HOUR = 18; const int UNLOCK_HOUR = 8; void setup() { Serial.begin(9600); pinMode(RELAY_PIN, OUTPUT); if (!rtc.begin()) { Serial.println("RTC not found!"); while (1); } // Set time if needed: rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); Serial.println("Scheduled lock system ready"); } void loop() { DateTime now = rtc.now(); int currentHour = now.hour(); // Lock between 6 PM and 8 AM if (currentHour >= LOCK_HOUR || currentHour < UNLOCK_HOUR) { digitalWrite(RELAY_PIN, HIGH); Serial.println("Outside hours - Door LOCKED"); } else { digitalWrite(RELAY_PIN, LOW); Serial.println("Business hours - Door UNLOCKED"); } delay(60000); // Check every minute }

Challenge 7: Multi-Lock System Control

Control multiple doors from one Arduino:

const int LOCK_PINS[] = {2, 3, 4, 5}; // 4 different locks const int NUM_LOCKS = 4; bool lockStates[NUM_LOCKS] = {false, false, false, false}; void setup() { Serial.begin(9600); for (int i = 0; i < NUM_LOCKS; i++) { pinMode(LOCK_PINS[i], OUTPUT); digitalWrite(LOCK_PINS[i], LOW); } Serial.println("Multi-lock system ready"); Serial.println("Commands: L1-L4 (lock), U1-U4 (unlock), LA (lock all), UA (unlock all)"); } void lockDoor(int doorNum) { if (doorNum >= 0 && doorNum < NUM_LOCKS) { digitalWrite(LOCK_PINS[doorNum], HIGH); lockStates[doorNum] = true; Serial.print("Door "); Serial.print(doorNum + 1); Serial.println(" LOCKED"); } } void unlockDoor(int doorNum) { if (doorNum >= 0 && doorNum < NUM_LOCKS) { digitalWrite(LOCK_PINS[doorNum], LOW); lockStates[doorNum] = false; Serial.print("Door "); Serial.print(doorNum + 1); Serial.println(" UNLOCKED"); } } void loop() { if (Serial.available()) { String cmd = Serial.readStringUntil('\n'); cmd.trim(); cmd.toUpperCase(); if (cmd == "LA") { for (int i = 0; i < NUM_LOCKS; i++) lockDoor(i); } else if (cmd == "UA") { for (int i = 0; i < NUM_LOCKS; i++) unlockDoor(i); } else if (cmd.startsWith("L") && cmd.length() == 2) { int door = cmd.charAt(1) - '1'; lockDoor(door); } else if (cmd.startsWith("U") && cmd.length() == 2) { int door = cmd.charAt(1) - '1'; unlockDoor(door); } } }

Challenge 8: Entry Log with SD Card

Log all lock/unlock events with timestamps:

#include <SPI.h> #include <SD.h> #include <RTClib.h> const int RELAY_PIN = 2; const int SD_CS_PIN = 10; RTC_DS1307 rtc; void logEvent(String event) { DateTime now = rtc.now(); File logFile = SD.open("access.log", FILE_WRITE); if (logFile) { logFile.print(now.year()); logFile.print("-"); logFile.print(now.month()); logFile.print("-"); logFile.print(now.day()); logFile.print(" "); logFile.print(now.hour()); logFile.print(":"); logFile.print(now.minute()); logFile.print(":"); logFile.print(now.second()); logFile.print(" - "); logFile.println(event); logFile.close(); Serial.println("Event logged: " + event); } } void setup() { Serial.begin(9600); pinMode(RELAY_PIN, OUTPUT); if (!rtc.begin()) Serial.println("RTC failed"); if (!SD.begin(SD_CS_PIN)) Serial.println("SD card failed"); logEvent("System started"); } void lockDoor() { digitalWrite(RELAY_PIN, HIGH); logEvent("Door LOCKED"); } void unlockDoor() { digitalWrite(RELAY_PIN, LOW); logEvent("Door UNLOCKED"); } void loop() { lockDoor(); delay(5000); unlockDoor(); delay(5000); }

Challenge 9: Fingerprint Scanner Access

Use biometric fingerprint sensor for secure access:

#include <Adafruit_Fingerprint.h> SoftwareSerial mySerial(2, 3); Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerial); const int RELAY_PIN = 4; void setup() { Serial.begin(9600); mySerial.begin(57600); pinMode(RELAY_PIN, OUTPUT); digitalWrite(RELAY_PIN, HIGH); // Start locked if (finger.verifyPassword()) { Serial.println("Fingerprint sensor ready"); } else { Serial.println("Sensor not found!"); } } void loop() { int result = finger.getImage(); if (result != FINGERPRINT_OK) return; result = finger.image2Tz(); if (result != FINGERPRINT_OK) return; result = finger.fingerFastSearch(); if (result == FINGERPRINT_OK) { Serial.print("Fingerprint ID #"); Serial.println(finger.fingerID); Serial.println("Access GRANTED"); digitalWrite(RELAY_PIN, LOW); delay(3000); digitalWrite(RELAY_PIN, HIGH); Serial.println("Door locked"); } else { Serial.println("Fingerprint not recognized - Access DENIED"); } delay(1000); }

Challenge 10: Emergency Override System

Add emergency unlock button with LED indicators:

const int RELAY_PIN = 2; const int EMERGENCY_BTN = 3; const int NORMAL_LED = 4; // Green LED const int EMERGENCY_LED = 5; // Red LED bool emergencyMode = false; bool lastBtnState = HIGH; unsigned long btnPressTime = 0; void setup() { Serial.begin(9600); pinMode(RELAY_PIN, OUTPUT); pinMode(EMERGENCY_BTN, INPUT_PULLUP); pinMode(NORMAL_LED, OUTPUT); pinMode(EMERGENCY_LED, OUTPUT); digitalWrite(RELAY_PIN, HIGH); digitalWrite(NORMAL_LED, HIGH); digitalWrite(EMERGENCY_LED, LOW); } void loop() { bool btnState = digitalRead(EMERGENCY_BTN); // Detect button press start if (lastBtnState == HIGH && btnState == LOW) { btnPressTime = millis(); } // Check for long press (3 seconds) if (btnState == LOW && (millis() - btnPressTime > 3000)) { if (!emergencyMode) { emergencyMode = true; digitalWrite(RELAY_PIN, LOW); // Force unlock digitalWrite(NORMAL_LED, LOW); digitalWrite(EMERGENCY_LED, HIGH); Serial.println("EMERGENCY MODE ACTIVATED - All locks disabled"); } } // Detect button release if (lastBtnState == LOW && btnState == HIGH) { if (millis() - btnPressTime < 3000 && emergencyMode) { // Short press exits emergency mode emergencyMode = false; digitalWrite(RELAY_PIN, HIGH); // Re-lock digitalWrite(NORMAL_LED, HIGH); digitalWrite(EMERGENCY_LED, LOW); Serial.println("Normal mode restored"); } } lastBtnState = btnState; delay(50); }

Video Tutorial

Arduino MKR WiFi 1010 - Button Controls Electromagnetic Lock

Check out the Arduino MKR WiFi 1010 - Button Controls Electromagnetic Lock tutorial

※ 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!