---
# System prepended metadata

title: Tutorial on how to build a simple securtiy system

---

# Tutorial on how to build a simple security system

Name: Ahmad Zeeb
Credentials: az222hp

## Short project overview
This project will focus on the process and steps of bulding a simple security system, i will be using a Raspberry pi pico W and a RC522 card reader and two led lights.The system will be conected to the Wifi and will send information to Adafruit. To make this project you will need to know how to use Python to some degree, assembiling the board and connecting the pico to the card reader is not that hard it will take around 30min to an hour using a pico pin diagram. The is where this project gets a bit tricky as it requiers research to be done, for example to be able to use a RC522 reader you will need to have a library, but some Python envioerments do not offer it so you have to find it online and using it manually.

## Objective
The main reason i chose to do this project is a personal challenge, i study Software technology and i was always interested in the hardware part of the equation, i wanted to see how firstly to see how a piece of empty hardware can be changed and used in many different ways using software, secondly i wanted to see what can one do with hardware when connected to the internet hence the iot.
The reason i chose to make the simple security system was more like a challenge, i did some research and i found fast and easy iot projects that can be done but i was not really convinced with the projects. While i was searching i found the RC522 piece and i got interested to see what this piece did, after i found that it was a card reader i got interested and thats how i decided to chose this project.

## Material 
For the materials i went with what the teacher recommended which was the pico W and i am happy i did, it was nice and easy to use, i also needed and expantion board which i got with the package i ordered and some led lights, and finally the most impostant sensor which was the RC522 reader which i bought from amazon.

|Material|Items          |Cost & links                                |Usage                                                          |
|--------|---------------|--------------------------------------------|---------------------------------------------------------------|
|1.      |PicoW          |70kr [pico](https://www.electrokit.com/en/product/raspberry-pi-pico-w/)|It is the brain and the acting cpu.|
|2.      |Extention board|100kr  [Expansion board](https://www.amazon.se/s?k=expansion+board&crid=2YX9QL91DBP76&sprefix=expansion+board%2Caps%2C96&ref=nb_sb_noss_1)|Used to connect the Pico and all the other sensors|
|3.      |led lights     |Free  |I used two lights, green and read in which green is for granted access and red is for denied access.|
|4.      |RC522 reader   |50kr [RC522](https://www.amazon.se/s?k=rc522&crid=2AW2UKL22ULJ1&sprefix=rc522%2Caps%2C87&ref=nb_sb_noss_1)|It is used to read cards and tags|
|5.      |Cables         |Free |Used to connect all the sensors to the expansion board|
|6.|Resistors|Free|Used to connect the led|
|7.|Micro-usb|Free|Used to connect the pico to the laptop|


## Computer Setup
There are different IDE's you can use, i chose to go with Visual studio code as i have used it before many times and I'm comfortable with it.

Note this process might differ depending on the os and the needs of the projects.

* **Step 1: Install an IDE**
I chose Visual studi code as IDE for this project, it is easy to work with, you can download it by searching on google vscode and download it from the Microsoft website.
* **Step 2: Download the extentions**
After opening vscode you will need to download few extentions to make the enviorment work, the first one is python extention and the second one is Pymakr. Pymakr is very important as it allows the IDE to acess and read the pico.
steps: Settings>extentions>search for the needed extention>Download.

* **Step 3: Connect the pico**
You will need to connect the pico to you laptop, this step might differ for different people. When i connected my pico i did not need to flash it but some will have to flash it.

## Putting everything together
As i mentioned before assembling the pico and the card reader was not the difficult, lets start:

First we need to connect the pico to the extention board and that is done by placing the pico into the pico with the usb side facing outside and pressing down on to the board.
![Pico](https://hackmd.io/_uploads/r173jnJph.jpg)



Next step is to connect the RC522 card reader to the pico.![RC522](https://hackmd.io/_uploads/HyoLzayph.jpg)



And finally you will have to connect to led, one red and one green, in which the red is connected to pin 16 and the green is connected to pin 15.![Led](https://hackmd.io/_uploads/B1ptz6k63.jpg)


To know how all the connections work i made a circut diagram

![](https://hackmd.io/_uploads/HynCGTy63.png)

The Rc522 card reader has 8 pins in which we will need to use 7, SDA to pin 5, SCK to pin 6. Mosi to pin 7, Miso to pin 4, GND to GND, RST to pin 3 and finally 3.3v to 3.3v

![](https://hackmd.io/_uploads/SytqVpJT3.jpg)

## Platform
I chose Adafruit as the base platform for my project, i felt it was easy to use. I established the connection over MQTT. There is a lot of forms you can find online and given by the course that will help guid you through the process of connecting to Wifi and establishing a MQTT connection. After you managed to connect the pico, you can customize your dashboard to show different information the gets sent from the pico. You need to understand the the information that is sent is usually binary, on(1) or off(0) and it is up to you to decide how to use these information.

## Code

As i mentioned before making the code and finding the needed libraries was a bit challenging.

The structure of the project was as follows:
```
lib
/mfrc522.py
/umqttsimple.py
boot.py
main.py
```
The lib or library folder contais all the neccesirly libraries to make the project work. ```mfrc522.py``` is the library that will make Python understand what this sensor is. ```umpttsimple.py``` is the library that allows pyhton to establish a connection. ```boot.py``` is usually when you put code that you want to start when you run the project but in my case i put everything in ```main.py```.

Here is the code for ```main.py```.
```python
from lib.mfrc522 import MFRC522
import utime
from machine import Pin
import network
from umqttsimple import MQTTClient
 
led = Pin(15, Pin.OUT)
ledRed = Pin(16, Pin.OUT)

mqtt_server = "io.adafruit.com"
client_id = "{your id}"
topic = "{your topic}"
user = "{your user name}"
password = "{your password}"
client = None

def connect_wifi():
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    if not wlan.isconnected():
        wlan.connect("TN-{your SSD}", "{Your password}")
        while not wlan.isconnected():
            pass
    print("WiFi = True. IP:", wlan.ifconfig()[0])

def connect_mqtt():
    global client
    client = MQTTClient(client_id, mqtt_server, 1883, user, password, keepalive=3600)
    client.connect()
    print('Connected to %s MQTT Broker' % (mqtt_server))

def send_mqtt_message(topic, message):
    global client  
    client.publish(topic, bytes(str(message), 'utf-8'))
    print("MQTT publish:", topic, "about:", message)

connect_wifi()
connect_mqtt()

 
def uidToString(uid):
    mystring = ""
    for i in uid:
        mystring = "%02X" % i + mystring
    return mystring
                  
rc522 = MFRC522(spi_id=0,sck=6,miso=4,mosi=7,cs=5,rst=3)
 
print("")
print("Place the card")
print("")
 
 
while True:
    (stat, tag_type) = rc522.request(rc522.REQALL)
    if stat == rc522.OK:
        (status, raw_uid) = rc522.SelectTagSN()
        if status == rc522.OK:  
            rfid_data = "{:02x}{:02x}{:02x}{:02x}".format(raw_uid[0], raw_uid[1], raw_uid[2], raw_uid[3])
            print("Card detected! UID: {}".format(rfid_data))
            if rfid_data == "8389a305":
                send_mqtt_message(topic, 0)
                led.value(1)
                utime.sleep(3)
                led.value(0)
            else:
                send_mqtt_message(topic, 1)
                ledRed.value(1)
                utime.sleep(3)
                ledRed.value(0)
```
So the main includes all the important code that makes the application funciton, it starts by importing the libraries needed such as mfrc522, mqtt, machine and utime.

We start by initilizing the pins for both led's we have to tell the pico where to look for them.
Then you establish the values the mqtt by use this code:
```pyhton
mqtt_server = "io.adafruit.com"
client_id = "[ur id]"
topic = "[ur topic]"
user = "[ur user name]"
password = "[ur password]"
client = None
```
Then this is the method for Wifi connection:
```python
def connect_wifi():
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    if not wlan.isconnected():
        wlan.connect("{Your SSD}", "{Your password}")
        while not wlan.isconnected():
            pass
    print("WiFi = True. IP:", wlan.ifconfig()[0])
```
The method appove will be called to establish a Wifi connection, also the method bellow is used to connect to mqtt and will also be called after the wifi is connected:
```python
def connect_mqtt():
    global client
    client = MQTTClient(client_id, mqtt_server, 1883, user, password, keepalive=3600)
    client.connect()
    print('Connected to %s MQTT Broker' % (mqtt_server))
```
In this part of the code we tell python the pin's that the rc522 reader is connected to:
```pyhton
def uidToString(uid):
    mystring = ""
    for i in uid:
        mystring = "%02X" % i + mystring
    return mystring
                  
rc522 = MFRC522(spi_id=0,sck=6,miso=4,mosi=7,cs=5,rst=3)
```
Finally to make everything work i used a while loop to keep the code running, it will read the card/tag and identify the id, if the id is accepted then the green light will turn on and a package will be sent to adafruit, if not then the red light will turn on and a package will be sent to adafruit.
```python
while True:
    (stat, tag_type) = rc522.request(rc522.REQALL)
    if stat == rc522.OK:
        (status, raw_uid) = rc522.SelectTagSN()
        if status == rc522.OK:  
            rfid_data = "{:02x}{:02x}{:02x}{:02x}".format(raw_uid[0], raw_uid[1], raw_uid[2], raw_uid[3])
            print("Card detected! UID: {}".format(rfid_data))
            if rfid_data == "8389a305":
                send_mqtt_message(topic, 0)
                led.value(1)
                utime.sleep(3)
                led.value(0)
            else:
                send_mqtt_message(topic, 1)
                ledRed.value(1)
                utime.sleep(3)
                ledRed.value(0)
```
## Tansmitting the data / connectivity

For this project as i mentioned before i connected the pico through wifi, the reason for that is that Wifi is the easiest and the fastest to connect to, knowing that we need to understand that Wifi connection will limit the connectivity of the pico as it is limited to a place and one wifi signal.The data will be sent when ever an attempt to access happens, so when a user tries to read a card the data will be sent to Adrfruit

The wifi connection happens using this method:
```python
def connect_wifi():
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    if not wlan.isconnected():
        wlan.connect("{Your SSD}", "{Your password}")
        while not wlan.isconnected():
            pass
    print("WiFi = True. IP:", wlan.ifconfig()[0])
```
For data transfer from i used MQTT protocal, the reason i used that because it was suggested by the teacher and i found it interesting to use. Adrfruit offers different dashboards to show the information recived from the Pico.
The Mqtt connection was made using this method:
```ptyhon
def connect_mqtt():
    global client
    client = MQTTClient(client_id, mqtt_server, 1883, user, password, keepalive=3600)
    client.connect()
    print('Connected to %s MQTT Broker' % (mqtt_server))
```

## Presenting the data
Its time to setup the Mqtt connection:

* Make an account in Adafruit
* After making an account and loging in go to keys and find you private key
* Then in you code as mentioned before in the code section you will have to initilize few variables including the key
* use the method shown before to connect to Mqtt
* After the connection is established you can go to Adafruit dashboard and creat your interface and customize it the way you want.

The following is what the dashboard will look like:

Thats how it will look like when the right card is used and the user is granted acess.
![](https://hackmd.io/_uploads/r1Tvl1x63.png)

Thats how it will look like when the wrong card is used and the user did not get acess.
![](https://hackmd.io/_uploads/rJ5Zb1eT2.png)

## Finalizing the design

Here is the final design, as you can see the pico is connected to the expantion board, the RC522 is connected to the board to the pin's and finally the led's are also connected to the pini's with resistors in which one side of the resistors is connected to the ground and the other is connected to the ground side of the led.
![](https://hackmd.io/_uploads/rk0rN1gT3.jpg)


[Demo of the project](https://youtube.com/shorts/2DSSdm_oKhE)






