IoT Lock: Raspberry Pi 5 with HTML, CSS, and JavaScript Webpage Tutorial

In this tutorial, you’ll learn how to transform your Raspberry Pi 5 into a functional IoT lock controlled via a web application built with HTML, CSS, and JavaScript. We will cover hardware setup, programming the Raspberry Pi, and developing the web app. By following this step-by-step guide, you’ll create a fully operational IoT lock system.


Part 1: Hardware Setup and Raspberry Pi Programming

Hardware Required:

  • Raspberry Pi 5 (with Raspbian OS installed)
  • Solenoid lock or motorized lock
  • NPN transistor (e.g., 2N2222)
  • Diode (e.g., 1N4007 for EMF protection)
  • Power supply appropriate for the lock
  • Jumper wires and breadboard
  • 1kΩ resistor
  • (Optional) Pull-down resistor

Raspberry Pi Circuit Setup:

  1. Connect the Solenoid Lock:
    • Connect the solenoid lock’s positive wire to the power supply’s positive terminal.
    • Connect the solenoid lock’s negative wire to the collector of the NPN transistor.
  2. Transistor Connections:
    • Connect the emitter of the NPN transistor to the ground of the power supply.
    • Connect the base of the NPN transistor to a GPIO pin on the Raspberry Pi (e.g., GPIO 23) through a 1kΩ resistor.
  3. Diode Placement:
    • Place the diode across the solenoid’s terminals, with the cathode connected to the positive side.
  4. Optional:
    • Add a pull-down resistor between the GPIO pin and ground to prevent unintended triggering of the transistor due to floating states.

Raspberry Pi Code:

  1. Install Necessary Libraries:
    • Ensure your Raspberry Pi is up-to-date and install the necessary libraries:
    bashCopy codesudo apt-get update sudo apt-get install python3-pip pip3 install paho-mqtt RPi.GPIO
  2. Programming the Raspberry Pi:
    • Connect to WiFi.
    • Connect to an MQTT broker.
    • Subscribe to a topic for receiving lock commands (e.g., lock/control).
    • Use a GPIO pin to control the lock.
pythonCopy codeimport paho.mqtt.client as mqtt
import RPi.GPIO as GPIO
import time

# GPIO setup
GPIO.setmode(GPIO.BCM)
GPIO.setup(23, GPIO.OUT)  # GPIO pin 23

# MQTT setup
broker = "broker.hivemq.com"
port = 1883
topic = "lock/control"

def on_connect(client, userdata, flags, rc):
    client.subscribe(topic)

def on_message(client, userdata, msg):
    message = msg.payload.decode()
    if message == "LOCK":
        GPIO.output(23, GPIO.HIGH)  # Lock the lock
    elif message == "UNLOCK":
        GPIO.output(23, GPIO.LOW)  # Unlock the lock

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message

client.connect(broker, port, 60)

try:
    client.loop_forever()
except KeyboardInterrupt:
    GPIO.cleanup()
  1. Running the Script:
    • Save the script as iot_lock.py and run it on your Raspberry Pi:
    bashCopy codepython3 iot_lock.py

Part 2: Web App Development (HTML, CSS, JavaScript)

HTML Structure:

  1. Create an index.html file:
    • This file will contain the structure of the web app.
htmlCopy code<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>IoT Lock Control</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="container">
        <h1>IoT Lock Control</h1>
        <button id="lockButton">Lock</button>
        <button id="unlockButton">Unlock</button>
    </div>
    <script src="mqtt.min.js"></script> <!-- Include MQTT.js library -->
    <script src="script.js"></script>
</body>
</html>

CSS Styling:

  1. Create a styles.css file:
    • This file will contain the styling for the web app.
cssCopy codebody {
    font-family: Arial, sans-serif;
    background-color: #f4f4f4;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    margin: 0;
}

.container {
    text-align: center;
    background: #fff;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

h1 {
    margin-bottom: 20px;
}

button {
    padding: 10px 20px;
    margin: 10px;
    font-size: 16px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

#lockButton {
    background-color: #e74c3c;
    color: #fff;
}

#unlockButton {
    background-color: #2ecc71;
    color: #fff;
}

JavaScript Functionality:

  1. Create a script.js file:
    • This file will handle the MQTT communication and button interactions.
javascriptCopy code// MQTT broker details
const brokerUrl = "wss://broker.hivemq.com:8000/mqtt"; // WebSocket URL for the broker
const topic = "lock/control";

// Initialize the MQTT client
const client = mqtt.connect(brokerUrl);

// Handle connection
client.on('connect', () => {
    console.log('Connected to MQTT broker');
});

// Handle button clicks
document.getElementById('lockButton').addEventListener('click', () => {
    client.publish(topic, 'LOCK');
    console.log('Lock command sent');
});

document.getElementById('unlockButton').addEventListener('click', () => {
    client.publish(topic, 'UNLOCK');
    console.log('Unlock command sent');
});
  1. Include the MQTT.js Library:
    • Download and include the mqtt.min.js library in your project. You can obtain it from the MQTT.js repository or via CDN.

Conclusion

This tutorial provided a detailed guide for setting up an IoT lock using a Raspberry Pi 5 and controlling it via a web app using HTML, CSS, and JavaScript. The Raspberry Pi code manages the lock mechanism and communicates with an MQTT broker to receive commands, while the web app acts as a client, sending lock/unlock commands. By following these steps, you can integrate hardware with a web-based interface for IoT solutions.

Safety Note: Always exercise caution when working with electrical components and power supplies to avoid injury or damage.

Final Testing:

  • Ensure your Raspberry Pi is properly connected and powered.
  • Test the lock and unlock functionality using the web app.
  • Verify that the MQTT messages are being sent and received correctly.