Overview: In this tutorial, you’ll learn how to transform your Raspberry Pi 5 into a functional IoT lock controlled via a Flutter app. We will cover hardware setup, programming the Raspberry Pi, and Flutter app development. 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:
- 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.
- 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.
- Diode Placement:
- Place the diode across the solenoid’s terminals, with the cathode connected to the positive side.
- 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:
- Install Necessary Libraries:
- Ensure your Raspberry Pi is up-to-date and install the necessary libraries:
sudo apt-get update sudo apt-get install python3-pip pip3 install paho-mqtt RPi.GPIO
- 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()
- Running the Script:
- Save the script as
iot_lock.py
and run it on your Raspberry Pi:
python3 iot_lock.py
- Save the script as
Part 2: Flutter App Development
Flutter App Setup:
- Install Flutter SDK:
- Ensure Flutter SDK is installed on your development machine.
- Create a New Project:
- Create a new Flutter project using your preferred IDE or the command line.
- Add MQTT Client Package:
- Open
pubspec.yaml
and addmqtt_client
and optionallyflutter_bloc
for state management.
- Open
yamlCopy codedependencies:
flutter:
sdk: flutter
mqtt_client: ^9.0.0
flutter_bloc: ^7.0.0
Flutter MQTT Service:
- Create a Service for MQTT:
- This service will manage the MQTT connection, subscription, and message publishing.
dartCopy codeimport 'package:mqtt_client/mqtt_client.dart' as mqtt;
class MQTTService {
late mqtt.MqttClient client;
late mqtt.MqttConnectionState connectionState;
void connect() async {
client = mqtt.MqttClient('broker.hivemq.com', '');
client.port = 1883;
client.keepAlivePeriod = 60;
try {
await client.connect();
} catch (e) {
print('Exception: $e');
client.disconnect();
}
client.updates!.listen((List<mqtt.MqttReceivedMessage<mqtt.MqttMessage>> c) {
final mqtt.MqttPublishMessage message = c[0].payload as mqtt.MqttPublishMessage;
final payload = mqtt.MqttPublishPayload.bytesToStringAsString(message.payload.message);
print('Received message:$payload from topic: ${c[0].topic}>');
});
}
void publish(String topic, String message) {
final builder = mqtt.MqttClientPayloadBuilder();
builder.addString(message);
client.publishMessage(topic, mqtt.MqttQos.exactlyOnce, builder.payload!);
}
}
Flutter UI for Lock Control:
- Build a Simple UI:
- Create a UI with buttons to send “LOCK” and “UNLOCK” commands to your Raspberry Pi via MQTT.
dartCopy codeimport 'package:flutter/material.dart';
import 'mqtt_service.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final MQTTService _mqttService = MQTTService();
@override
void initState() {
super.initState();
_mqttService.connect();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('IoT Lock Control'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
onPressed: () => _mqttService.publish("lock/control", "LOCK"),
child: Text('Lock'),
),
ElevatedButton(
onPressed: () => _mqttService.publish("lock/control", "UNLOCK"),
child: Text('Unlock'),
),
],
),
),
),
);
}
}
Conclusion
This tutorial has provided a detailed guide for setting up an IoT lock using a Raspberry Pi 5 and controlling it via a Flutter app using MQTT. The Raspberry Pi code handles the lock mechanism and communicates with an MQTT broker to receive commands, while the Flutter app acts as a client, sending lock/unlock commands. By following these steps, you can integrate hardware with mobile applications 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 Flutter app.
- Verify that the MQTT messages are being sent and received correctly.