Full text





The smart mailbox


Bachelor’s Thesis at ITM Supervisor: Nihad Subasic



Den smarta brevlådan

Vi kollar ofta v˚aran virtuella brevl˚ada fler g˚anger om dagen men gl¨ommer ofta att kolla v˚ar faktiska brevl˚ada hemma. M˚alet med det h¨ar projektet ¨ar att skapa en smart brevl˚ada. Denna definieras som en brevl˚ada som kan meddela motta-garen att ett brev har kommit och ¨oppnas ˚at r¨att person. Den slutgiltiga produkten ¨ar ett koncepttest av en smart brevl˚ada. Dess syfte ¨ar att visualisera och testa v˚ara teo-rier. Det h¨ar projektet ¨amnar ocks˚a att bevisa f¨ordelarna med att implementera mer information i standarden f¨or IMB (Intelligent mail barcode)



1 Introduction 1 1.1 Background . . . 1 1.2 Purpose . . . 2 1.3 Scope . . . 2 1.4 Method . . . 3 2 Theory 5 2.1 The internet of things . . . 5

2.2 Microcomputer . . . 5

2.3 Communication . . . 6

2.4 Authorization for access . . . 6

2.5 Identification of mail . . . 7 3 Prototype 9 3.1 Electronics . . . 9 3.2 Servo motor . . . 10 3.3 Solenoid . . . 10 3.4 Relay . . . 10 3.5 Arduino . . . 10 3.6 RFID-reader . . . 10 3.7 Barcode-scanner . . . 11 3.8 Hardware . . . 12 3.9 Software . . . 13 4 Results 15 5 Discussion 17 6 Conclusion 21 Bibliography 23 Appendices 23


List of Figures

2.1 An overview of the barcodesUPC-A,IMB,Code-39, and Code-128 . . . 8

3.1 A circuit diagram of the electronics. The battery represents a 5V power supply. Made in fritzing. . . 9

3.2 A side-view of the mailbox and it’s scanning components. Made in Solid Edge . . . 11

3.3 A rendition of the whole construction. Made in keyshot. . . 12

3.4 The prototype after project completion. . . 12

3.5 A flowchart of the code functionality. Made in draw.io. . . 13


List of Abbreviations


The internet of things


Radio frequency identification


Cluster box unit


Intelligent mail barcode


Printed circuit board


Inter-integrated circuit


Chapter 1




With how busy people are in today’s times, it’s easy to let smaller things fall by the wayside. An everyday task such as opening your mailbox is something many people can neglect due to forgetfulness. It is however, difficult to miss a notification about mail in your virtual mailbox. Integrating the physical mailbox with the virtual can prove beneficial, especially since many important letters are specifically sent in a physical form.

As part of digitalization and the internet of things (IOT), having a connected house is a logical step towards the future. Creating a smart mailbox as part of the smart house is a small but meaningful step towards this goal. This thesis aims to grow understanding in different methods used for reading/scanning, in particular when applied to letters. Some insight into how simplifying everyday chores by making things “smart” is also given.





The purpose of this project is to create a smart mailbox. In this context, “smart” is defined as having the ability to notify the recipient that mail has been received. Secondarily, the mailbox should also be openable by the use of radio frequency identification-technology (RFID), and thus not require actual keys like normal mail-boxes, specifically in apartment complexes. The goal is to build a product that will prove that the concept is both feasible and usable in the future, and the solution has been developed with making it applicable in apartment buildings or offices in mind. In order to realize the concept, the following research question are explored and answered:

• What percentage of letters are identified correctly?

• Which scanning method is the best given presented restrictions?

• What kind of benefits can be expected from implementing such a solution?



The main restriction during this project is that of a time constraint, corresponding to the duration of the course, one semester of half-time studies. Furthermore, a bare minimum feature-set was defined in order to have a baseline for completion of the project, with additional features planned to be implemented as time would allow it, which will be discussed later.

The bare minimum features are defined as:

• A body, conforming to the known Swedish standards for a cluster box unit


• An RFID-sensor able to discern between authorized and unauthorized tags. • An opening mechanism.

• A scanner capable of identifying received letters.

Limitations of project execution have been defined as:

• Controlled and fixed placement for reading and identifying information on the

letters, with the same placement for every letter.

• Our own identification method, namely Code-128 barcodes, not used in

to-day’s mail-service.

Lastly, as this project is a proof of concept, it may not be very applicable in actual everyday use in its current form.





The first step was to define a smart mailbox, and differentiating between which features were considered critical and which desirable. The critical features of the smart mailbox are identification and accessibility, and the desirable features are communication and notifications. The critical features consist of recognizing the authorized people and granting them access, and the desirable ones consist of noti-fying said people when mail has been received.

After deciding these parameters, research was conducted on these chosen features, and with gained knowledge, informed decisions were made on what components were needed to be able to achieve desired functionality.

Since the identification system is a very important part of the project, emphasis was placed on understanding the current system used in today’s postal services and which potential shortcomings it had in order to determine what kind of system would be applied to the project.

After research and setting the scope and boundaries of the project, the box was constructed and the necessary code was written and tested. When this was com-pleted the functionality of the mailbox was evaluated.

To develop the mechanical aspects of the mailbox an iterative design process was used, constructing and testing solutions searching for improvements for a more op-timal design. This was done with computer aided design and virtual simulation of the movements used in combination with rapid practical prototyping.


Chapter 2



The internet of things

The internet of things, a concept introduced by Kevin Ashton in 1999 is a term that describes a collective of objects connected to a mutual network, with capabilities of gathering information autonomously [2]. This allows the objects to communicate with each other and share information. With this, every-day objects can be made “smart” [3]. Interconnected and communicating devices have applications in many different fields, and can simplify and effectivize everything from industrial manu-facturing to assisted living. The realization of the IOT is heavily dependent on the continued development of a couple of key technologies. This can be roughly boiled down to software, hardware identification and communication [3]. These key tech-nologies need to be standardized and regulated to allow for the desired compatibility between units.



A microcomputer is a small inexpensive computer. There are many different ver-sions of microcomputers with different specifications and uses. They all have three components in common. The micro processing unit, memory and input/output pins mounted on a single piece of printed circuit board (PCB). Some micro computers come equipped with an internet module. The small form factor allows for imple-mentation in everyday objects and the internet connection enables communication between them.





An inter-integrated circuit (I2c) is a way of connecting two devices with cable, al-lowing them to communicate. It supports speeds up to 100 kbit per second and only requires two connections. This allows for short range communications asymmetri-cally in a primary-secondary structure, where the primary acts as a communication hub and requests data from the secondary. It is a very simplistic and flexible way of transmitting data compared to other methods.

Wifi is a combination of standards set for Wireless local area network (WLAN) and is used certify the compatibility between these standards. The WLAN allows for communication amongst two or more computers on the same network. It is a common way of communicating between devices.


Authorization for access

Radio frequency identification is a technology that allows wireless identification of tags and objects. The main advantage of RFID is that the tags do not need a battery source. This makes the possibilities for implementation very diverse [4]. There are three different frequencies were RFID operates. Low frequency, High frequency and ultra high frequency. The different frequencies allows for different reading ranges. While the lower frequencies only allows for a reading range of a couple of centimeters, the ultra high frequencies can be read at a distance of one meter. RFID is very accurate which is why it is often used where high accuracy and low service time is preferred, as in access systems or in logistics and supply chains [5]. In this thesis the RFID technology is being used to identify and authorize access to the right person.

Some options exist for the communication component of the mailbox as well. RFID is not the only wireless technology that can be applied for authorization purposes. Bluetooth is a technology developed by ericsson in the mid 90’s. The technology is used for wireless communication between computers and can be used to authorize access, albeit with lower accuracy and higher energy and computational require-ments.

Another option could be NFC, which stands for Near-Field Communication and is based on the RFID protocols of communication. The difference is that a NFC device acts not only as a reader but also as a tag. This allows for communication between two NFC devices and two way authorization [6]. NFC operates at the ultra high frequencies of the RFID spectrum. NFC is commonly used where a higher level of security is needed, for example Google pay, where the two way communication is needed for the authorization of a purchase. Since the technology is common in today’s smartphones a lot more products using this technology can be expected.




Identification of mail

In order to answer the question of which scanning method would be the best other possible methods available need to be explored. One method for scanning and iden-tifying the recipient is OCR (ocular recognition method). It is a method used for recognizing a text in a picture. This method is currently used by the postal service to identify where the mail is going and to whom it is.The method needs a lot of processing power to be able to process all the data in each picture.

Barcodes is a technology used to enable machine reading of visual data. It was first developed to help in the food industry with inventory management and cat-egorization. [7] Today there are many different types of barcodes being used for specific industries. The postal service uses a barcode called intelligent mail barcode (IMB). which is a height-modulated barcode, that encodes up to 31-digits of data. [8] These 31 digits of data contains information about the sender, the routing and identification of the mail and the delivery point zip code. Very little information of the recipient is stored in the barcode. By today’s standard only the zipcode is printed as information. [9]

Many other types of barcodes exist, although most have strict requirements for the format in which the information is stored in. Among the most popular you find Universal product code (UPC). A widely used barcode that can be seen in nearly every retail product. It requires 12 numbers and every item has a unique identifier. This means it cannot be used with any less (or more) than 12 digit-numbers. Another widely used barcode is Code 39. This barcode was the first alphanumerical code and developed in 1974. It is still used in many different applications includ-ing electronics and healthcare. Code 39 supports the full American Standard Code for Information Interchange (ASCII) character set, consisting of 128 characters. It is also a variable length barcode, meaning no format requirements with the only limiting factor being the physical size of the code in relation to where it is printed [11]. Code 128 is a similar type of barcode and can be considered its successor. It was created in the early 1980’s and supports the full ASCII character set as well as being of variable length. It is used most frequently in packaging and shipping appli-cations. Code 128 barcodes have the advantage of being more compact compared to Code 39 [11].


CHAPTER 2. THEORY A key part of the smart mailbox is to not only detect incoming mail, but also distinguish between the potential recipients in a household. Since most names don’t contain any numbers, and are of different lengths, this severely limits the applicable barcodes to those that support the ASCII-character set with a variable length. The two alphanumerical barcodes presented above are capable of this. All mentioned barcodes are shown in the figure below.

Figure 2.1. An overview of the barcodesUPC-A,IMB,Code-39, andCode-128


Chapter 3


This chapter aims to give an overview of the components the mailbox consists of, as well as defining their function in the context of usage.



The electrical components the smart mailbox consists of is an Arduino Uno rev 3, an Arduino Uno Wifi rev2, a servo motor, a relay, a solenoid, an RFID-reader and a barcode scanner. How these components were connected is illustrated in the circuit diagram presented below.




Servo motor

The servo is a small and energy efficient motor used to generate controlled rotation between set angles. Servos are controlled by PWM (pulse width modulation) which means that the length of the pulse determines the position of the shaft [10]. The opening mechanism is powered by a servo. The servo rotates roughly 90 degrees during the closing/opening sequence, which was determined during the synthesis of the mechanism.



A solenoid is an efficient way to have controlled linear movement. it works by creating a controlled electromagnetic field to control valve or a sprint. To ensure the mailbox is securely locked a solenoid is used. By having the solenoid position so that the locking pin retracts when the solenoid is engaged the power usage is minimized and ensures that the mailbox is still locked in case of a power outage.



A relay is an electrically operated switch, and is often used to control high power signals using a low voltage control signal. the relay is used to control the activation of the solenoid.



The prototype uses two arduinos, one for notification and one for access and identifi-cation of the letters. The arduino uno rev 3 is a microcomputer with a ATmega328P as a processing unit. it is in charge of the access and identification of letters. The second microcomputer is an Arduino UNO WIFI rev 2, it has an ATmega328 as a processing unit and a ESP8266-module for internet connection. The arduino uno wifi rev 2 connects to a local wifi network. When a letter is scanned on the arduino uno rev3 it sends the information to the second arduino over I2C. The arduino wifi rev 2 then makes a previously established online server run a php script, which notifies the recipients through email.



Detects and distinguishes between authorized tags. Information about detected tags is sent to the arduino.





Reads 1D barcodes using the Code-128 standard. The data is then translated and processed by the arduino. As the mailbox dimensions did not allow the scanner to read barcodes normally (with the scanner perpendicular to the barcode), the scanner was mounted on a stand on the inside of the mailbox. This stand redirects the laser beam from the scanner roughly 140 degrees and allows it to both fit and read the barcodes well as the letters enter the slit of the box according to the figure below.

Figure 3.2. A side-view of the mailbox and it’s scanning components. Made in Solid Edge





The smart mailbox consists of the body, which houses the components as well as the mail. The circuit containing all the components are powered by a 5V power supply. Their function in the context of usage as well as a figures of the construction as a whole is presented below.

Figure 3.3. A rendition of the whole construction. Made in keyshot.

Figure 3.4. The prototype after project completion.





When a letter is placed in the box, the scanner reads the barcode on the letter, identifies who the recipient is, and via an internet gateway notifies the recipient through e-mail. To access the mail, you hold a valid RFID-tag on the scanner, which will activate the solenoid and servo and open the box. The RFID software is based on a primary/secondary process, where a primary key can be used to save new secondary keys or to clear all saved secondary keys. An overarching flowchart showcasing the functions of the code is shown below.


Chapter 4


The barcode-type chosen for this project is the Code-128 format.

The scanning accuracy was tested by doing 10 scan attempts. Every time the barcode was registered a sound was played and a correct scan was noted. The test was done by Jacob Tunberg, as well as an outsider not familiar with the concept. The results can be seen in the table below.

Table 4.1. Empirical test results

Attempt Familiar Unfamiliar

1 Success Failure 2 Failure Failure 3 Success Success 4 Success Failure 5 Success Failure 6 Success Success 7 Success Failure 8 Success Success 9 Success Success 10 Success Success


Chapter 5


The scanning results showed that the process of scanning a letter, which then sends the recipient an e-mail is quite reliable. For someone familiar with the box, a 90% success-rate was achieved. If the smart mailbox is meant to be used in a real-world application, any lower would be unfeasible. As a letter-carrier even having 1 out of 10 letters failing to register can be a huge time loss over the course of a day, considering the sheer amount of letters that are deposited over a workday. As such, this is an important factor to improve.

The success-rate for scans depend on many different variables and not all can be accounted for. One of the bigger factor is the positioning of the letter relative to the barcode scanner. The smart mailbox has a slot wider than a standard letter to accommodate a broader range of sized letters. This results in having the placement of the barcode relative to the scanner vary from scan to scan, reducing accuracy. Narrowing the slot to the exact width of a standard letter would increase the scan-accuracy greatly, at the cost of limiting compatible letters to standard or smaller. As the result most likely depends on which barcode scanner is being used another solution could be to use a different model with a wider scanning area or add a sec-ondary reader, both increasing the scan area of the mailbox.

For someone unfamiliar with the mailbox, a success rate of 50% was achieved. This is comparatively low, but it was found that as familiarity increased, so did the success-rate. It can reasonably assumed that in a real-world application, letter-carriers would be familiar with the smart mailbox through some kind of workplace


CHAPTER 5. DISCUSSION As for the amount of tries in the test, it was decided that a total number of 10 tries would be enough to find a representative number. As this is a prototype, doing any large-scale testing would yield more data than necessary, which is why it was limited to two trials, familiar and unfamiliar. It was found that scanning letters gradually became easier as you found “the sweet spot” which is why the number of tries was limited to 10. The failed scans were mostly in the beginning, and increas-ing the number of tries would inflate the success-rate, which was undesirable and not indicative of the actual results.

The reason for not using the current IMB standard of the postal service and instead opting to use Code-128 is to include information about the recipient’s name. This visualizes and proves the benefits of implementing information about the recipient into IMB standards.

The project required the barcode to both be alphanumerical and of variable length. Of the two possible options (Code 39 and Code 128), Code 128 was chosen since it is a higher density code, allowing more information to be stored in a limited space. It also supports any character of the ASCII 128 character set (shown in appendix A.1)

The benefits we can expect to see with a smart mailbox is that no more impor-tant mail will be missed. With further development of the software features such as reminders and remote access could be implemented. Using NFC instead of RFID can make it possible to give a person temporary access. This feature could be very desirable as online sales as a proportion of all retailing has increased by roughly 10% in the last decade in the United states [11], and home delivery is chosen more frequently.

Further benefits of a smart mailbox can be seen when it’s connected to a larger system. For instance an entrance system in an apartment complex or applied in larger companies. Letters could be used for very important documents, where se-curity can be a big concern

Detecting that the mailbox received mail can also be done by using a photo in-terrupter as a sensor. The photo inin-terrupter detects when a laser beam between two forks is interrupted and sends out a signal. This is an easy and reliable method that could be implemented well. The drawback however, is the lack of possibility of identifying the recipient, which is why it wasn’t chosen.

As the processing power of the microcomputers rises and further optimization of technology the use of OCR will be made more feasible. This can allow for more features such as detecting what’s an important letter and what’s not, and could solve the issue of registering a mail even though recognition of the person failed.


Regarding the choice of components, all of them could be considered mandatory except one, the Arduino Wifi rev2. The operation of the smart mailbox could be done with a single microprocessor, and the original intention was to only use the Wifi-board for the prototype. A hardware compatibility issue found later during the project resulted in the decision of including an Arduino Uno rev3. This is something that could be improved upon in the future.


Chapter 6


This identification method could prove useful although would require some reconfig-uration in the current mailing system. Furthermore a mailbox such as this would be quite costly compared to a normal one. Because of this, implementation although theoretically viable may not be very cost effective compared to the amount of physi-cal mail we will receive in the future. That being said, the solution proves functional as evidenced by the results, and demonstrates the potential for implementing smart features in smaller products. The main benefit of implementing the smart mailbox by automating the task of checking mail is that of reducing the amount of menial tasks a person has to think about in everyday life. The platform also has room for improvements with features that further simplifies the owners mail-receiving experience.



[1] Riktlinjer och rekommendationer. Forum f¨or fastighetsboxar. [Online]. Available: https://fastighetsboxar.se/om-fastighetsboxar/riktlinjer/

[2] K. Ashtonet al., “That ‘internet of things’ thing,”RFID journal, vol. 22, no. 7, pp. 97–114, 2009.

[3] D. Bandyopadhyay and J. Sen, “Internet of things: Applications and challenges in technology and standardization,”Wireless personal communications, vol. 58, no. 1, pp. 49–69, 2011.

[4] B. Nath, F. Reynolds, and R. Want, “Rfid technology and applications,”IEEE Pervasive computing, vol. 5, no. 1, pp. 22–24, 2006.

[5] X. Zhang, Q. Dong, and F. Hu, “Applications of rfid in logistics and supply chains: An overview,” ICLEM 2012: Logistics for Sustained Economic Devel-opment—Technology and Management for Efficiency, pp. 1399–1404, 2012. [6] M. Masyuk, “Information security of rfid and nfc technologies,” Journal of

Physics: Conference Series, vol. 1399, no. 3, p. 033093, 2019.

[7] The transformation of retail. IBM. [Online]. Available: https://www.ibm. com/ibm/history/ibm100/us/en/icons/upc/

[8] Implementing the intelligent mail ® barcode. PitneyBowes. [Online]. Available: https://www.pb.com/bv70/en us/extranet/contentfiles/editorials/ downloads/ed Intelligent Mail Bar Implementing the IMB.pdf

[9] Intelligent mail barcode 4-state specification. United States postal ser-vice. [Online]. Available: https://postalpro.usps.com/storages/2017-08/ 2190 USPSB3200IntelligentMailBarcode4State 0.pdf


Appendix A

First Appendix


Appendix B

The code for the Arduino Uno rev3

1 /*

2 This code is made to control a smart mailbox.

3 Made by Jonatan Barriel and Jacob Tunberg

4 Developed for:

5 Board: Arduino uno rev 3

6 Usb Host: Sparkfun USB host

7 RFid: Parallax RFid module

8 9 Last edited: 12-04-2020 */ 10 11 //Start 12 #include <EEPROM.h> 13 #include <Servo.h> 14 #include <SoftwareSerial.h> 15 #include <usbhid.h> 16 #include <usbhub.h> 17 #include <hiduniversal.h> 18 #include <hidboot.h> 19 #include <SPI.h> 20 #include <Wire.h> 21 22 //Initialise


APPENDIX B. THE CODE FOR THE ARDUINO UNO REV3 30 #define RFID_Enabled_Pin 2 // sets RFID enable pin to pin 2

31 #define servoPin 3 // sets the servo’s pin to pin 3

32 #define LockedPos 81 // sets the locked possition

33 #define UnlockedPos 140 // sets the unlocked possistion


35 byte checkPosition; //used to check if the incomming number is true or false

36 byte buffer[100]; //used to store the incoming bytes from the RFID

37 byte RFID_Master[10] = {’0’, ’4’, ’1’, ’5’, ’E’, ’D’, ’9’, ’ 0’, ’E’, ’0’}; //the secound RFID fob (key) to look for

38 byte RFID_Slave1[10], RFID_Slave2[10], RFID_Slave3[10]; // the first RFID fob (key) to look for

39 byte i; //used to keep track of which bit to write to

40 byte i2; //used to erase the RFID fob (key) number from the buffer


42 boolean DoorLocked; //true if door is locked

43 boolean RFID_Master_Correct; //true if it’s the right RFID fob (key), false if not

44 boolean RFID_Slave1_Correct, RFID_Slave2_Correct,

RFID_Slave3_Correct; //true if it’s the right RFID fob ( key), false if not

45 boolean RFID_SaveNextRead;


47 // Defines barcode scaner


49 class MyParser : public HIDReportParser {

50 private:

51 bool keyReady;

52 uint8_t scannedKey;

53 public:

54 MyParser();

55 void Parse(USBHID *hid, bool is_rpt_id, uint8_t len,

uint8_t *buf);

56 bool GetKey(uint8_t&);

57 protected:

58 uint8_t KeyToAscii(bool upper, uint8_t mod, uint8_t key) ;

59 virtual void OnKeyScanned(bool upper, uint8_t mod,

uint8_t key);

60 virtual void OnScanFinished();

61 };

62 // Function for the barcode scaning


63 MyParser::MyParser() {}


65 void MyParser::Parse(USBHID *hid, bool is_rpt_id, uint8_t

len, uint8_t *buf) {

66 // If error or empty, return

67 if (buf[2] == 1 || buf[2] == 0) return;


69 for (uint8_t i = 7; i >= 2; i--) {

70 if (buf[i] == 0) continue; // If empty, skip


72 if (buf[i] == UHS_HID_BOOT_KEY_ENTER) {

73 OnScanFinished(); // If enter signal emitted, scan finished

74 }

75 76

77 else { // If not, continue normally

78 OnKeyScanned(i > 2, buf, buf[i]); // If bit position not in 2, it’s uppercase words

79 }

80 return;

81 }

82 }


84 uint8_t MyParser::KeyToAscii(bool upper, uint8_t mod,

uint8_t key) { // Letters

85 if (VALUE_WITHIN(key, 0x04, 0x1d)) {

86 if (upper) return (key - 4 + ’A’);

87 else return (key - 4 + ’a’);

88 }


90 else if (VALUE_WITHIN(key, 0x1e, 0x27)) { // Numbers

91 return ((key == UHS_HID_BOOT_KEY_ZERO) ? ’0’ : key - 0 x1e + ’1’);

92 }




102 103

104 bool MyParser::GetKey(uint8_t &key)

105 { 106 if (keyReady) { 107 key = scannedKey; 108 keyReady = false; 109 return true; 110 } 111 return false; 112 } 113

114 // when barcode scaned

115 void MyParser::OnScanFinished() {

116 Serial.println(k); // prints number of scanned bites

117 Serial.println(scanned_code);// prints scanned code

118 Serial.println(" - Finished");


120 // begin I2C

121 Wire.beginTransmission(9); // transmit to device #9

122 Wire.write(scanned_code,k); // sends scanded_code

123 Wire.endTransmission(); // stop transmitting

124 k=0; // reset the count of used data slots

125 126 } 127 128 USB Usb; 129 USBHub Hub(&Usb); 130 HIDUniversal Hid(&Usb); 131 MyParser Parser; 132 133 // Setup 134 135 void setup() {

136 pinMode(13, OUTPUT); //enables the diode on the arduino

137 pinMode(RFID_Enabled_Pin, OUTPUT); //sets the RFID pin to output

138 pinMode(solenoidPin, OUTPUT); //Sets that pin as an output

139 RFID_Enable(false); //used to set the status of the RFID reader

140 EEPROM_Read_Slaves();



142 PreLock(); //locks the arduino on startup

143 RFID_Enable(true); //used to set the status of the RFID reader

144 Serial.begin(2400); //sets baudrate

145 i = 1; //sets the varible to 1, and thereby skip the start byte (0x0A)

146 Wire.begin();


148 // If faliur

149 if (Usb.Init() == -1) {

150 Serial.println("OSC did not start.");

151 } 152 153 delay( 200 ); // delay 200 ms 154 155 Hid.SetReportParser(0, &Parser); 156 } 157

158 void(* resetFunc) (void) = 0; //declare reset function @ address 0


160 //Loop

161 void loop() { //the main loop


163 Usb.Task(); // scans the usb host

164 165 uint8_t key; 166 if (Parser.GetKey(key)) { 167 scanned_code[k] = key; 168 k=++k; 169 } 170 171 // Serial data

172 if (Serial.available()) { //check if the RFID reader sends anything


APPENDIX B. THE CODE FOR THE ARDUINO UNO REV3 179 Serial.print("RFID Tag scanned: ");

180 RFID_Enable(false); 181 RFID_Master_Correct = true; 182 RFID_Slave1_Correct = true; 183 RFID_Slave2_Correct = true; 184 RFID_Slave3_Correct = true; 185 //RFID ID

186 // We have read all bytes - we are now going to check them

187 for (checkPosition = 0; checkPosition < 10; checkPosition++) { //Read bit fra 0-9

188 Serial.write(Serial.print(buffer[checkPosition+1]) );

189 if (buffer[checkPosition+1] == RFID_Slave1[

checkPosition] && RFID_Slave1_Correct == true) { // compares the written bits to "RFID1"

190 RFID_Slave1_Correct = true; //Slave1 RFID tag is detected

191 } else {

192 RFID_Slave1_Correct = false; //Slave1 RFID tag is not detected

193 }

194 if (buffer[checkPosition+1] == RFID_Slave2[

checkPosition] && RFID_Slave2_Correct == true) { // compares the written bits to "RFID1"

195 RFID_Slave2_Correct = true; //Slave2 RFID tag is detected

196 } else {

197 RFID_Slave2_Correct = false; //Slave2 RFID tag is not detected

198 }

199 if (buffer[checkPosition+1] == RFID_Slave3[

checkPosition] && RFID_Slave3_Correct == true) { // compares the written bits to "RFID1"

200 RFID_Slave3_Correct = true; //Slave3 RFID tag is detected

201 } else {

202 RFID_Slave3_Correct = false; //Slave3 RFID tag is detected

203 }

204 if (buffer[checkPosition+1] == RFID_Master[

checkPosition] && RFID_Master_Correct == true) { // compares the written bits to "RFID1"

205 RFID_Master_Correct = true; //Master RFID tag is



206 } else {

207 RFID_Master_Correct = false; //Master RFID tag is detected

208 }

209 }


211 Serial.println("");

212 if (RFID_SaveNextRead == false && ( RFID_Slave1_Correct == true || RFID_Slave2_Correct == true || RFID_Slave3_Correct == true) &&

RFID_Master_Correct == false) { //see if the right RFID fob (key) is detected

213 if (RFID_Slave1_Correct == true) { Serial.println(

"Slave1 Card Scanned"); }

214 if (RFID_Slave2_Correct == true) { Serial.println(

"Slave2 Card Scanned"); }

215 if (RFID_Slave3_Correct == true) { Serial.println(

"Slave3 Card Scanned"); }

216 //Door

217 if (DoorLocked == true) { //see if door is locked or not

218 //Unlock

219 Serial.print("Unlocking..."); //if the door is locked then unlocked it

220 Unlock(5); //unlock with 5ms delay

221 Serial.println(" Unlocked!");

222 DoorLocked = false; //the door is unlocked

223 } else {

224 //Lock

225 Serial.print("Locking..."); //if the door is unlocked then lock it

226 Lock(5); //lock with 5ms delay

227 Serial.println(" Locked!");

228 DoorLocked = true; //the door is unlocked


APPENDIX B. THE CODE FOR THE ARDUINO UNO REV3 234 Serial.println("Master Card Scanned - Programming

mode Enabled");

235 delay(1000);

236 RFID_SaveNextRead = true; // Enable programming mode

237 } else if (RFID_Master_Correct == false &&

RFID_SaveNextRead == true) { // If another card is scanned when in programming mode

238 // Save the Card

239 if (RFID_Slave1[0] == 0) { // Is the Slave1 Card slot empty?

240 for (checkPosition = 0; checkPosition < 10; checkPosition++) { //Read bit fra 0-9

241 RFID_Slave1[checkPosition] = buffer[

checkPosition+1]; // Save the scanned card as Slave1

242 }

243 Serial.println("RFID Card saved in: Slave1");

244 delay(1000);

245 } else if (RFID_Slave2[0] == 0) { // Is the Slave2 Card slot empty?

246 for (checkPosition = 0; checkPosition < 10; checkPosition++) { //Read bit fra 0-9

247 RFID_Slave2[checkPosition] = buffer[

checkPosition+1]; // Save the scanned card as Slave2

248 }

249 Serial.println("RFID Card saved in: Slave2");

250 delay(1000);

251 } else if (RFID_Slave3[0] == 0) { // Is the Slave3 Card slot empty?

252 for (checkPosition = 0; checkPosition < 10; checkPosition++) { //Read bit fra 0-9

253 RFID_Slave3[checkPosition] = buffer[

checkPosition+1]; // Save the scanned card as Slave3

254 }

255 Serial.println("RFID Card saved in: Slave3");

256 delay(1000);

257 } else {

258 Serial.println("No free Card slots");

259 RFID_Enable(true); //turns on the RFID reader

260 delay(1000);

261 RFID_Enable(false); //turns off the RFID reader


262 delay(1000);

263 }

264 EEPROM_Save_Slaves();

265 RFID_SaveNextRead = false;

266 } else if (RFID_Master_Correct == true &&

RFID_SaveNextRead == true) { // If the Master Card is scanned when in programming mode

267 Serial.println("Master Card Scanned again -Removing all saved Cards");

268 delay(1000);

269 // Remove all Slave Cards

270 for (checkPosition = 0; checkPosition < 10; checkPosition++) { //Read bit fra 0-9

271 RFID_Slave1[checkPosition] = 0;

272 }

273 for (checkPosition = 0; checkPosition < 10; checkPosition++) { //Read bit fra 0-9

274 RFID_Slave2[checkPosition] = 0;

275 }

276 for (checkPosition = 0; checkPosition < 10; checkPosition++) { //Read bit fra 0-9

277 RFID_Slave3[checkPosition] = 0; 278 } 279 EEPROM_Save_Slaves(); 280 RFID_SaveNextRead = false; 281 } 282

283 RFID_Enable(true); //turns on the RFID reader

284 EmptySerialBuffer(); //erase the buffer

285 Serial.println("");

286 }

287 i++; //used in the beginning to write to each bit in the buffer

288 }

289 }

290 //Go to


APPENDIX B. THE CODE FOR THE ARDUINO UNO REV3 298 } 299 i = 0; 300 } 301 // prelock 302 void PreLock() {

303 digitalWrite(solenoidPin, HIGH); // unlocks the solenoid

304 servoLock.attach(servoPin); // attaches the servo on pin 3 to the servo object

305 servoLock.write(LockedPos); // tell servo to go to position in variable ’LockedPos’

306 delay(250);// waits 250ms for the servo to reach the position

307 digitalWrite(solenoidPin, LOW); // locks the solenoid

308 servoLock.detach(); //detaches the servo, so it’s not using power

309 DoorLocked = true; //the door is locked

310 }

311 // unlocking

312 void Unlock(byte speedDelay) {

313 int pos;

314 digitalWrite(solenoidPin, HIGH); // unlocks the solenoid

315 delay(250); //waits 250ms for the soleoid to pull back

316 servoLock.attach(servoPin); // attaches the servo on pin 3 to the servo object

317 servoLock.write(UnlockedPos); // tell servo to go to position in variable ’pos’

318 delay(500); // waits 500ms for the servo to reach the position

319 digitalWrite(solenoidPin, LOW); // locks the solenoid

320 servoLock.detach(); //detaches the servo, so it’s not using power

321 DoorLocked = false; //the door is unlocked

322 }

323 // locking

324 void Lock(byte speedDelay) {

325 int pos;

326 digitalWrite(solenoidPin, HIGH); // unlocks the solenoid

327 servoLock.attach(servoPin); // attaches the servo on pin 3 to the servo object

328 servoLock.write(LockedPos); // tell servo to go to position in variable ’pos’

329 delay(500); // waits 500ms for the servo to reach the position

330 digitalWrite(solenoidPin, LOW); // locks the solenoid


331 servoLock.detach(); //detaches the servo, so it’s not using power

332 DoorLocked = true; //the door is locked

333 resetFunc(); // resets the function

334 }

335 void RFID_Enable(boolean enabled) {

336 if (enabled == true) {

337 digitalWrite(RFID_Enabled_Pin, LOW); //enables the RDIF reader and turns on the diode on the arduino

338 digitalWrite(13, HIGH);

339 } else { //disables the RDIF

reader and turns off the diode on the arduino

340 digitalWrite(RFID_Enabled_Pin, HIGH);

341 digitalWrite(13, LOW); 342 } 343 } 344 345 346 void EEPROM_Read_Slaves() { 347 byte EPROMaddr;

348 for (EPROMaddr = 0; EPROMaddr < 10; EPROMaddr++) { //Read bit fra 0-9

349 RFID_Slave1[EPROMaddr] = EEPROM.read(EPROMaddr);

350 }

351 for (EPROMaddr = 10; EPROMaddr < 20; EPROMaddr++) { //Read bit fra 0-9

352 RFID_Slave2[EPROMaddr-10] = EEPROM.read(EPROMaddr);

353 }

354 for (EPROMaddr = 20; EPROMaddr < 30; EPROMaddr++) { //Read bit fra 0-9

355 RFID_Slave3[EPROMaddr-20] = EEPROM.read(EPROMaddr);

356 }

357 }


359 void EEPROM_Save_Slaves() {

360 byte EPROMaddr;


APPENDIX B. THE CODE FOR THE ARDUINO UNO REV3 367 for (EPROMaddr = 20; EPROMaddr < 30; EPROMaddr++) { //Read

bit fra 0-9

368 EEPROM.write(EPROMaddr, RFID_Slave3[EPROMaddr-20]);

369 }

370 }


Appendix C

The code for the Arduino Uno Wifi rev2

1 /*This code is made to send an email when information is received. The code is meant to be used in collaboration with code smart_mailbox.ide and emailScript.php


3 Developed for:

4 Board: Arduino uno rev 3

5 Made by Jonatan Barriel and Jacob Tunberg

6 Last edited: 12-04-2020*/ 7 8 9 // start 10 #include <WiFiNINA.h> 11 #include <Wire.h> 12 #include <string.h> 13 14 //Initialise

15 char ssid[] = "*********"; //sets wifi ssid

16 char pass[] = "*********"; // sets wifi password

17 char a[0]={}; //used to store incoming data

18 char server[] = "www.thesmartmailbox.eu"; // sets server domain

19 char Key[6] = {’a’, ’b’, ’c’, ’1’, ’2’, ’3’}; // sets right recipient


APPENDIX C. THE CODE FOR THE ARDUINO UNO WIFI REV2 27 WiFiClient client; //Creates a client that can connect to to

a specified internet IP address and port as defined


29 // setup

30 void setup() {


32 Wire.begin(9); // Start the I2C Bus as Slave on address 9

33 Wire.onReceive(receiveEvent);// Attach a function to trigger when something is received.

34 Serial.begin(2400); //sets baudrate


36 // conect to local wifi

37 while (status != WL_CONNECTED) {

38 Serial.print("Attempting to connect to Network named: ") ;

39 Serial.println(ssid);

40 status = WiFi.begin(ssid, pass);

41 delay(10000); // delay 10 s

42 }


44 Serial.print("SSID: ");

45 Serial.println(WiFi.SSID());

46 IPAddress ip = WiFi.localIP();

47 Serial.print("IP Address: ");

48 Serial.println(ip);

49 }


51 // when reciwed data

52 void receiveEvent(int howMany) {


54 for (int i = 0; i < howMany; i++) // copies data given to char a

55 {

56 a[i] = Wire.read();

57 }


59 // decide if the correct recipient received data

60 for(int i=0;i< howMany; i++){

61 if(a[i]==Key[i]){

62 c++;

63 if(c==howMany){ // if correct recipient

64 c=0; // clear count

65 String temperatureF = a; // create a string with recived data


66 postData = postVariable + temperatureF;

67 // sends email

68 if (client.connect(server, 80)) {

69 client.println("POST /test/emailScript.php HTTP /1.1");

70 client.println("Host: www.thesmartmailbox.eu");

71 client.println("Content-Type: application/x-www-form-urlencoded");

72 client.print("Content-Length: ");

73 client.println(postData.length());

74 client.println();

75 client.print(postData);

76 Serial.println("Email Sent");

77 Serial.println(postData);

78 } 79 if (client.connected()) { 80 client.stop(); 81 } 82 break; 83 } 84 }

85 else{ // not correct recipient

86 c=0; // clears count

87 String temperatureF = "Someone else."; // inform the recipient thst someone elses mail have been recived

88 postData = postVariable + temperatureF;

89 // send email

90 if (client.connect(server, 80)) {

91 client.println("POST /test/emailScript.php HTTP/1.1");

92 client.println("Host: www.thesmartmailbox.eu");

93 client.println("Content-Type: application/x-www-form-urlencoded");

94 client.print("Content-Length: ");

95 client.println(postData.length());

96 client.println();

97 client.print(postData);



107 }


Appendix D

The php script uploaded to



$time = time ( ) ;

$ r ec i p i en t A = $ POST [ ” temp ” ] ; $to = ” name@adress . com ” ; $ s u b j e c t = ” Mail r e c e i v e d ! ” ;

$message = ”You r e c e i v e d mail adressed to : ” . $ r e ci p i en t A ; $headers = ”From : Thesmartmailbox@notification . eu ” ;

mail ( $to , $subject , $message , $headers ) ; p r i n t ” S c r i p t Ran $time ” ;


TRITA ITM-EX 2020:45



Related subjects :