Download as pdf or txt
Download as pdf or txt
You are on page 1of 60

DA NANG UNIVERSITY

OF TECHNOLOGY AND SCIENCE


ENGINEERING FACULTY

PBL3: DESIGN OF
MICROCONTROLLERS AND
SENSORS

TOPIC: DIGITAL LOCK


Mentor : DR. ĐẶNG PHƯỚC VINH

Students : TRẦN ANH QUÂN 20CDTCLC2

PHAN VĂN KHẢI 20CDTCLC2

Da Nang, June/2023
MENTOR: DR. Dang Phuoc Vinh Topic: Digital lock

Contents
PREFACE ........................................................................................................................... 4
CHAPTER 1: INTRODUCTION OVERVIEW.................................................................. 5
1. What is Digital lock? .................................................................................................... 5
2. Benefits of digital lock ................................................................................................. 6
3. Analyze the project and choosing option ..................................................................... 6
3.1. Analyze .................................................................................................................. 6
3.2. Choosing option ..................................................................................................... 6
CHAPTER 2: HARDWARE DESIGN ............................................................................... 7
1. Overview of system...................................................................................................... 7
2. Component of system ................................................................................................... 7
2.1. PIC16F877A .......................................................................................................... 7
2.2. 4x4 keypad matrix ............................................................................................... 11
2.3. LCD16X2............................................................................................................. 13
2.4. Servo motor SG90 ............................................................................................... 15
2.5. RC522 .................................................................................................................. 17
2.6 LM393 .................................................................................................................. 18
3. Component in proteus ................................................................................................ 19
3.1. Source circuit ....................................................................................................... 19
3.2. Processing block .................................................................................................. 20
3.3. Source and clock pulse block .............................................................................. 21
3.4. Reset and charging block ..................................................................................... 21
3.5. Button and led block ............................................................................................ 22
3.6. LCD block............................................................................................................ 22
3.7. RS232................................................................................................................... 23
3.8. Sensor, servo & buzzer ........................................................................................ 23
3.9. Keypad 4x4 .......................................................................................................... 24
3.10. RC522 ................................................................................................................ 24
3.11. PCB layout & 3D Visualizer .............................................................................. 25
CHAPTER 3: SOFTWARE DESIGN ............................................................................... 27

2
MENTOR: DR. Dang Phuoc Vinh Topic: Digital lock

1. Compilers and loader for PIC Microcontrollers ........................................................ 27


1.1. CCS ...................................................................................................................... 27
1.2. Using CCS compiler ............................................................................................ 27
2. Program to load PIC microcontroller ......................................................................... 29
3. Visual studio ............................................................................................................... 32
4. Code ........................................................................................................................... 34
4.1. CCS ...................................................................................................................... 34
4.2. Visual ................................................................................................................... 48
CHAPTER 4: CONCLUSION .......................................................................................... 59
1. Conclusion.................................................................................................................. 59
2. Drawback ................................................................................................................... 59
REFERENCES .................................................................................................................. 60

3
MENTOR: DR. Dang Phuoc Vinh Topic: Digital lock

PREFACE

The project design of microcontroller and sensor application equipment is an


indispensable content for students of engineering in general and especially with the
mechatronics engineer training program in particular to provide students with Basic
knowledge of industrial sensors and microcontrollers. In the process of studying these two
subjects, we have become familiar with sensors, programmed to control sensors, peripheral
devices, etc. This design project helps us to re-systemize the knowledge learned and delve
into it. Through the completion of the project, we can link the learned knowledge of
subjects such as industrial sensors, industrial electronics, microcontroller programming to
be applied into a product. practice and through that gain more teamwork skills, circuit
design skills, printing skills to form a complete product.
The topic we choose is DIGITAL LOCK that is very popular application in our life.
During the process of making the project, we consulted many relevant documents as well
as textbooks, plus the dedicated guidance of the teachers, but because it was the first time
we were exposed to and perfected a product, we made mistakes. is inevitable. We hope to
receive more guidance from the teachers and will use it as an experience to gradually
improve ourselves on the way to becoming a Mechatronics engineer.
Above all, we would like to sincerely thank the teachers and especially send a deep
thanks to Dr. Dang Phuoc Vinh for enthusiastically guiding us in the process of completing
the project.

4
MENTOR: DR. Dang Phuoc Vinh Topic: Digital lock

Da Nang, June/2023

CHAPTER 1: INTRODUCTION OVERVIEW


1. What is Digital lock?

Figure 1. Digital lock

Digital locks are electronic or battery-operated locks that do NOT require the use
of physical keys for access. They’re used as an alternative to the conventional mechanical
locks, with the automated features giving a more creative security solution depending on
its intended use.
Like any other door lock, digital locks also use a latch or a bolt that can run across
the door and the doorframe to prevent access. What differs is how the latch or bolt is
controlled. Digital locks work by the use of any of the following: RFIDs, Pin codes,
fingerprints, smartphones, and more.
Digital locks are commonly found on cars and doors, but they can also be used
for lockers, furniture and cabinets. Reviews of these locks for cars and doors are sometimes

5
MENTOR: DR. Dang Phuoc Vinh Topic: Digital lock

mixed, but for businesses who use lockers and cabinets, the benefits of digital locks are
greater compared to the traditional key locks.
2. Benefits of digital lock
• You can authorize multiple people simultaneously
• No more broken keys in locks
• Don't be afraid to lose the key
• Easy to change the code
• High security
• Easy out of hours access for approved persons, no calling a keyholder out
• There is no need to carry keys
• There is no need for spare keys
3. Analyze the project and choosing option
3.1. Analyze
Through the actual survey, the digital key needs to have the components of a
normal set of keys
• Easy to use
• Easy to use database
• Can warn when wrong login
• The power use is not dangerous to the user
• The price is suitable for students
3.2. Choosing option
Based on the above analysis, we make the following choices:
• Using microcontroller 16F877A
• Using 16x2 LCD screen to display information and communicate with users
• Using the 4x4 keyboard to sign in
• Using RC522 to scan the magnetic card to open the door
• Using servo motor to close and open the door
• Using sensor to open the door when someone comes out

6
MENTOR: DR. Dang Phuoc Vinh Topic: Digital lock

CHAPTER 2: HARDWARE DESIGN


1. Overview of system

Keyboard RDM6300 Sensor

Power PIC 16F877A C# Database

LCD 16x2
Servo

- Keyboard: Communication and entering password to open a door


- RDM6300: Using scan the magnetic card to open the door
- Power: Supply power to all devices
- LCD 16x2: Show the necessary information
- Servo: Controlling a door
- Database: Using store information about the person who is granted the password
2. Component of system
2.1. PIC16F877A
• Overview

7
MENTOR: DR. Dang Phuoc Vinh Topic: Digital lock

The Pic16F877A is a microcontroller produced by Microchip with 35 instructions


of 14-bit length. It is an 8-bit microcontroller based on RISC architecture with 8KB ISP
flash program memory that can be erased and rewritten thousands of times, 256B
EEPROM, and a very large RAM in the world of 8-bit processors (368B SRAM).
It has 33 pins that can be used for input or output (I/O) connections, 32 registers, 3
programmable timer/counters, internal and external interrupts (2 interrupts per vector),
USART, SPI, and I2C serial communication protocols. Additionally, it can utilize a 10-bit
analog-to-digital converter/digital-to-analog converter (ADC/DAC) that can be expanded
up to 11 channels, programming capabilities for a watchdog timer, operation with 5 power
modes, and the ability to use up to 2 channels of pulse-width modulation (PWM) control…

Figure 2: PIC16F877A

• Specifications
CPU PIC 8 bit

Program memory size (Kbyte) 14

RAM (bytes) 368

EEPROM/HEF 256/HEF

Number of pins 40

Maximum CPU speed (MHz) 20

Select peripheral pin select (PPS) No

Internal oscillator No

8
MENTOR: DR. Dang Phuoc Vinh Topic: Digital lock

Number of comparators 2

Number of ADC channels 14

Maximum ADC resolution (bits) 10

ADC with computation No

Number of DAC converters 0

Maximum DAC resolution 0

Internal voltage reference Yes

Number of 8-bit timers 2

Number of 16-bit timers 1

Signal measurement timer No

Hardware limit timer No

Number of PWM outputs 0

Maximum PWM resolution 10

Angle measurement timer No

Mathematical acceleration unit No

Number of UART modules 1

Number of SPI modules 1

Number of I2C modules 1

Number of USB modules 0

Numerically controlled oscillator No

9
MENTOR: DR. Dang Phuoc Vinh Topic: Digital lock

Minimum operating temperature (*C) -40

Maximum operating temperature (*C) 125

Minimum operating voltage (V) 2

Maximum operating voltage (V) 5.5

• Pinout diagram

Figure 3: Pinout diagram PIC16F877A

Pin Pin name Description


number
01 𝑀𝐶𝐿𝑅 / Vpp MCLR is used in the programming process,
mainly connected to a programmer like PicKit
02 RA0 / AN0 Analog pin 0 or pin 0 of PORTA
03 RA1 / AN1 Analog pin 1 or pin 1 of PORTA
04 RA2 / AN2 / Vref- Analog pin 2 or pin 2 of PORTA
05 RA3 / AN3 / Vref + Analog pin 3 or pin 3 of PORTA
06 RA4 / T0CKI / C1out Pin 4 of PORTA
07 RA5/AN4/𝑆𝑆/C2OUT Analog pin 4 or pin 5 of PORTA
08 RE0/𝑅𝐷/AN5 Analog pin 5 or pin 0 of PORTE
09 RE1 / WR / AN6 Analog pin 6 or pin 1 of PORTE
10 RE2/𝐶𝑆/AN7 Pin 7 of PORTE
11 Vdd Ground pin of MCU

10
MENTOR: DR. Dang Phuoc Vinh Topic: Digital lock

12 Vss Positive pin of MCU (+5V)


13 OSC1 / CLKI External oscillator / clock input pin
14 OSC2 / CLKO External oscillator / Clock input pin
15 RC0 / T1OSO / T1CKI Pin 0 of PORT C
16 RC1 / T1OSI / CCP2 Pin 1 of POCTC or Timer/PWM pin
17 RC2 / CCP1 Pin 2 of POCTC or Timer/PWM pin
18 RC3 / SCK / SCL Pin 3 of POCTC
19 RD0 / PSP0 Pin 0 of POCTD
20 RD1 / PSPI Pin 1 of POCTD
21 RD2 / PSP2 Pin 2 of POCTD
22 RD3 / PSP3 Pin 3 of POCTD
23 RC4 / SDI / SDA Pin 4 of POCTC or Serial Data Input Pin
24 RC5 / SDO Pin 5 of POCTC or Serial Data Output Pin
25 RC6 / Tx / CK Pin 6 of POCTC or Microcontroller Clock
Output Pin
26 RC7 / Rx / DT Pin 7 of POCTC or Microcontroller Clock
Input Pin
27 RD4 / PSP4 Pin 4 of POCTD
28 RD5/PSP5 Pin 5 of POCTD
29 RD6/PSP6 Pin 6 of POCTD
30 RD7/PSP7 Pin 7 of POCTD
31 Vss Positive power supply pin of MCU (+5V)
32 Vdd Ground pin of MCU
33 RB0/INT Pin 0 of POCTB or External Interrupt Pin
34 RB1 Pin 1 of POCTB
35 RB2 Pin 2 of POCTB
36 RB3/PGM Pin 3 of POCTB or Programming Pin
37 RB4 Pin 4 of POCTB
38 RB5 Pin 5 of POCTB
39 RB6/PGC Pin 6 of POCTB or Programming Pin
40 RB7/PGD Pin 7 of POCTB or Programming Pin

2.2. 4x4 keypad matrix


• Overview
A 4x4 matrix is a combination of individual buttons, connected to each other
through rows and columns. There are 16 buttons in total, but only 8 pins are used for
connections.

11
MENTOR: DR. Dang Phuoc Vinh Topic: Digital lock

Figure 4: 4x4 keypad matrix

• Scanning method for keypad

Figure 5: Structure of 4x4 Keypad

There are two scanning methods for a 4x4 keypad:


- Row scanning
- Column scanning
For row scanning:
- The columns are set as outputs
- The rows are set as inputs

12
MENTOR: DR. Dang Phuoc Vinh Topic: Digital lock

• Set logic level 0 for C1: Set column 1 to 0 and the other columns to 1. The
programmer checks each pin from R1 to R4 to determine which button is being
pressed. For example, if pin R3 is at level 0, then button 7 is being pressed.
• Set logic level 0 for C2: Similar to the above step, set column 2 to 0 and the other
columns to 1. The programmer checks each pin from R1 to R4 to determine which
button is being pressed (2, 5, 8, or 0).
• Repeat the above steps for the remaining columns.
• Go back to step 1.
For column scanning: In contrast to scanning by row (we switch row and column)
2.3. LCD16X2
• Overview
• The LCD (Liquid Crystal Display) display device is widely used in
microcontroller applications because it has the ability to display various
characters, symbols, and graphics in a user-friendly manner, and can be easily
integrated into different application circuits using various communication
protocols (such as 4-bit mode, 8-bit mode, …).
• Pinout diagram

Figure 6: Pinout diagram LCD16x2

Pin Pin name Description


number
1 Vss Ground connection for LCD, when designing the circuit we
connect this pin to the GND of the control circuit
2 Vdd Power supply pin for LCD, when designing the circuit we
connect this pin to the VCC=5V of the control circuit
3 Vee LCD contrast adjustment pin

13
MENTOR: DR. Dang Phuoc Vinh Topic: Digital lock

Register select pin. Connect RS pin to logic "0" (GND) or


4 RS logic "1" (VCC) to select the register.
+ Logic "0": Bus DB0-DB7 will be connected to the LCD
command instruction register (in "write" mode) or to the
LCD address counter (in "read" mode)
+ Logic "1": Bus DB0-DB7 will be connected to the data
register DR inside the LCD
5 R/W Read/Write mode select pin. Connect R/W pin to logic "0"
for writing mode, or logic "1" for reading mode.
6 E Enable pin. After the signals are placed on the bus DB0-
DB7, the commands are only accepted when there is a pulse
on the E pin.
+ In writing mode: The data on the bus will be transferred
(accepted) into the internal register of the LCD when a high-
to-low transition of the E signal is detected.
+ In reading mode: The data will be outputted by the LCD
onto DB0-DB7 when a rising edge (low-to-high transition)
is detected on the E pin, and the LCD will hold the data on
the bus until the E pin goes low.
7-14 DB0- The eight data bus lines are used to exchange information
DB7 with the MPU. There are two modes of using these 8 data
bus lines :
+ 8-bit mode: Data is transmitted on all 8 lines, with MSB
being bit DB7.
+ 4-bit mode: Data is transmitted on 4 lines from DB4 to
DB7.

14
MENTOR: DR. Dang Phuoc Vinh Topic: Digital lock

2.4. Servo motor SG90

Figure 7: SERVO MOTOR SG90

Overview
The SG90 servo motor is small in size and is the most commonly used type for
small models or mechanisms that do not require heavy force.
The SG90 180-degree servo motor has a fast response speed, but its plastic gears
need to be handled with care when lifting heavy loads to avoid damaging them. The RC
Servo 9G motor has a built-in driver for motor control, making it easy to control the
rotation angle using the PWM pulse width modulation method.
- Pulse width range of 0.5ms to 2.5ms corresponds to a rotation angle
of 0-180 degrees
- Frequency of 50Hz, with a cycle of 20ms
Technical specifications
• Operating voltage: 4.8-5VDC
• Speed: 0.12 sec/60 deg (4.8VDC)
• Torque: 1.6 Kg.cm
• Dimensions: 21x12x22mm
• Weight: 9g

Wiring diagram
- Red: Power positive
- Brown: Power negative

15
MENTOR: DR. Dang Phuoc Vinh Topic: Digital lock

- Orange: Signal

Figure 8. Servo motor wire

16
MENTOR: DR. Dang Phuoc Vinh Topic: Digital lock

2.5. RC522

Figure 9. RC522

RC522 RFID module uses Phillip's MFRC522 IC used to read and write data
for 13.56mhz NFC tags, with a low price and compact design, this module is the
first choice for card reading and writing applications. RFID.
Specifications
• Power: 3.3VDC, 13 - 26mA
• Wave frequency: 13.56MHz
• Operating distance: 0~60mm(mifare1 card)
• Communicate: SPI
• Data transfer rate: 10Mbit/s
• Supported RFID cards: mifare1 S50, mifare1 S70, mifare UltraLight, mifare
Pro, mifare Desfire
• Size: 40mm × 60mm

17
MENTOR: DR. Dang Phuoc Vinh Topic: Digital lock

Figure 10. Pinout diagram

2.6 LM393

Figure 11. LM393 sensor

The sensor is capable of recognizing obstacles in the environment with a pair of


infrared transceiver LEDs to transmit and receive infrared data. Infrared rays emitted with
a certain frequency, when there is an obstacle on the transmission path of the LED
transmitter, it will reflect on the infrared receiver LED, then the obstacle LED on the
module will light up, when there is no obstacle, the LED will turn off.
Specification:
- Comparator IC: LM393
- Voltage: 3.3V - 6V
- Detection distance: 2 ~ 30 cm
- Power LED and output signal LED

18
MENTOR: DR. Dang Phuoc Vinh Topic: Digital lock

- Output logic level:


+ Low level - 0V: when there is an obstacle
+ High level - 5V: when there is no obstacle
- Dimensions: 3.2cm x 1.4cm

Figure 12. Pinout diagram

3. Component in proteus
3.1. Source circuit

Figure 12. Power circuit

19
MENTOR: DR. Dang Phuoc Vinh Topic: Digital lock

3.2. Processing block

Figure 13. Main circuit

20
MENTOR: DR. Dang Phuoc Vinh Topic: Digital lock

3.3. Source and clock pulse block

Figure 13. Source and clock pulse

3.4. Reset and charging block

21
MENTOR: DR. Dang Phuoc Vinh Topic: Digital lock

Figure 14. Reset and charging

3.5. Button and led block

Figure 14. Button and led

3.6. LCD block

Figure 14. LCD 16X2

22
MENTOR: DR. Dang Phuoc Vinh Topic: Digital lock

3.7. RS232

Figure 15. RS232 circuit

3.8. Sensor, servo & buzzer

Figure 15. Sensor, servo and buzzer

23
MENTOR: DR. Dang Phuoc Vinh Topic: Digital lock

3.9. Keypad 4x4

Figure 16. Keypad 4x4

3.10. RC522

24
MENTOR: DR. Dang Phuoc Vinh Topic: Digital lock

Figure 17. RC522

3.11. PCB layout & 3D Visualizer

Figure 18. Main circuit PCB layout

Figure 19. LCD circuit PCB layout

25
MENTOR: DR. Dang Phuoc Vinh Topic: Digital lock

Figure 20. Power circuit PCB layout

Figure 21. Power circuit 3D

26
MENTOR: DR. Dang Phuoc Vinh Topic: Digital lock

22

Figure 22. Main & LCD circuit 3D

CHAPTER 3: SOFTWARE DESIGN


1. Compilers and loader for PIC Microcontrollers
1.1. CCS
CCS compiler program for microcontrollers is one of the high-level C programming
languages that is easy to get used to and suitable for students' projects. In addition, CCS is
very easy to use and has an easy-to-see interface.
1.2. Using CCS compiler
For this topic, we use CCS compiler with C languages to program for PIC16F877A
microcontroller. To create a new file we need to do the following steps: File → New →
Project Wizard

27
MENTOR: DR. Dang Phuoc Vinh Topic: Digital lock

Figure 23. Creating a new file

Then we choose Save As window will appear, enter the name of the project in the
File name box and click the Save button to save the project to be done (note: Names cannot
start with a number, no sign, don't use space button).

Figure 24. Saving a file

28
MENTOR: DR. Dang Phuoc Vinh Topic: Digital lock

After successfully saving the newly created project file, the CCS compiler will
ask the programmer to select the microcontroller line and the quartz frequency to use. For
this project, the team used PIC16 in the Family section, PIC16F877A in the Device section
and 4MHz in the Crystal Clock Speed section. Click Create Project to finish creating a new
project

Figure 25. Choosing options

2. Program to load PIC microcontroller


Pickit 3 software is a program used to load code from computer to microcontroller.
This is a software with a fairly simple interface, easy to access and very simple to use.
Firstly we need to plug the Pickit into the computer and turn on the Pickit 3 software

29
MENTOR: DR. Dang Phuoc Vinh Topic: Digital lock

Figure 26. PICKIT 3 interface

To check the connection to the microcontroller, we do the following steps: Tool →


Check communication.

Figure 27. Checking status

30
MENTOR: DR. Dang Phuoc Vinh Topic: Digital lock

To load the code into the microcontroller we do the following steps: File → Import
Hex → Choose file you want to add

Figure 28. Loading a file code

PICKit 3 has the following outstanding features:


• Communicating with computer via USB port without driver installation
• High stability, less error
• Outstanding interface, support on many different operating systems
• Fully support all basic PIC families
• Allow firmware update when new version is available

31
MENTOR: DR. Dang Phuoc Vinh Topic: Digital lock

• New chips can be added to the software by updating the software, which is freely
downloaded from the Mircochip website.

Figure 29. Pickit circuit

3. Visual studio
Microsoft Visual Studio is integrated software from Microsoft. Visual Studio uses
Microsoft's software development platform Visual Studio includes other built-in tools
including a form designer for building application interfaces, web designer, class designer,
and database schema designer.
Visual Studio supports many different programming languages and allows the code
editor and debugger to support almost any programming language. Integrated languages
include C, C++, C++/CLI…

32
MENTOR: DR. Dang Phuoc Vinh Topic: Digital lock

Figure 30. Example of a generated Windows Form

Figure 41. User interface

33
MENTOR: DR. Dang Phuoc Vinh Topic: Digital lock

Figure 52. Some funtions

4. Code
4.1. CCS
Main program:

Figure 53. Main program

34
MENTOR: DR. Dang Phuoc Vinh Topic: Digital lock

Keypad program:

Figure 54. Keypad program

35
MENTOR: DR. Dang Phuoc Vinh Topic: Digital lock

Servo program:

Figure 55. Servo program

Code:
#include <main.h>
#FUSES NOWDT,PUT,HS,NOPROTECT,NOBROWNOUT,NOLVP
#use delay(crystal = 4mhz)
#use rs232(baud=9600,parity=N,xmit=pin_c6,rcv=pin_c7,bits=8)

#define LCD_RS_PIN PIN_D1


#define LCD_RW_PIN PIN_D2
#define LCD_ENABLE_PIN PIN_D3
#define LCD_DATA4 PIN_D4
#define LCD_DATA5 PIN_D5

36
MENTOR: DR. Dang Phuoc Vinh Topic: Digital lock

#define LCD_DATA6 PIN_D6


#define LCD_DATA7 PIN_D7
#include <lcd.c>

#define C1 PIN_B4
#define C2 PIN_B5
#define C3 PIN_A0
#define C4 PIN_A1
#define H1 PIN_B0
#define H2 PIN_B1
#define H3 PIN_B2
#define H4 PIN_B3

#define MFRC522_SS PIN_C2


#define MFRC522_SCK PIN_C3
#define MFRC522_MOSI PIN_D0
#define MFRC522_MISO PIN_C4
#define MFRC522_RST PIN_C5
#include<Built_in.h>

#define LOA PIN_E0


#define LED1 PIN_A2
#define LED2 PIN_A3
#define SAVE PIN_A1
#define CLEAR PIN_A0

char DATA_KHAI[5] ={0XE3, 0XBB, 0X51, 0XA6, 0XAF};

37
MENTOR: DR. Dang Phuoc Vinh Topic: Digital lock

char DATA_QUAN[5] ={0XA3, 0XB9, 0X0D, 0XAA, 0XBD};


int1 THE_1=0, i;
char tt_1, tt_2;

int a=0;
int8 k, kp=0,index = 0,b=1,h=0;
int password[4]={1,2,3,4};
int pw_nhap[4];
int tt=0;
char c;

void coi_bao(int8 so_lan_keu,int time)


{
for (int i = 0; i < so_lan_keu;i++)
{
output_high(LOA); delay_ms(time); output_low(LOA);
}
}

void enter_pass(){
lcd_init();
lcd_putc("\f");
lcd_gotoxy(3,2);
lcd_putc("PASSWORD OR ID CARD");
}

int1 QUET_THE(char DATA[],char UID[])

38
MENTOR: DR. Dang Phuoc Vinh Topic: Digital lock

{
FOR (int i = 0; i < 5; i++)
{
if(UID[i]== DATA[i] )
{
THE_1=1;
}
else
{
THE_1=0;
break;
}
}
return THE_1;
}

void keyarray()
{
pw_nhap[index]= kp;
index++;
if(index==4) index=0;
}

void quet(int8 k){


port_b_pullups(1);
switch (k){

39
MENTOR: DR. Dang Phuoc Vinh Topic: Digital lock

case 1:{ output_low(C1); output_high(C2); output_high(C3);output_high(C4);


break;}
case 2:{ output_high(C1); output_low(C2); output_high(C3);output_high(C4);
break;}
case 3:{ output_high(C1); output_high(C2); output_low(C3);output_high(C4);
break;}
case 4:{ output_high(C1); output_high(C2); output_high(C3);output_low(C4);
break;}
}
}

void nhap_phim(){
int8 x,a=0;
for (int i=0; i < 5; i++){
port_b_pullups(1);
switch (i){
case 1:{
quet (1);
if (input (H1) ==
0){LCD_gotoxy(b,1);printf(LCD_putc,"1");b++;a=1;kp=1;keyarray(); coi_bao(1,100);
}
else if (input (H2) ==
0){LCD_gotoxy(b,1);printf(LCD_putc,"4");;b++;a=1;kp=4;keyarray();coi_bao(1,100); }
else if (input (H3) ==
0){LCD_gotoxy(b,1);printf(LCD_putc,"7");b++;a=1;kp=7;keyarray(); coi_bao(1,100); }
else if (input (H4) ==
0){LCD_gotoxy(b,1);printf(LCD_putc,"*");b++;a=1;kp=10;keyarray();coi_bao(1,100); }
break;
}
case 2:{

40
MENTOR: DR. Dang Phuoc Vinh Topic: Digital lock

quet (2);
if (input (H1) ==
0){LCD_gotoxy(b,1);printf(LCD_putc,"2");b++;a=1;kp=2;keyarray(); coi_bao(1,100); }
else if (input (H2) ==
0){LCD_gotoxy(b,1);printf(LCD_putc,"5");b++;a=1;kp=5;keyarray(); coi_bao(1,100); }
else if (input (H3) ==
0){LCD_gotoxy(b,1);printf(LCD_putc,"8");b++;a=1;kp=8;keyarray(); coi_bao(1,100); }
else if (input (H4) ==
0){LCD_gotoxy(b,1);printf(LCD_putc,"0");b++;a=1;kp=0;keyarray(); coi_bao(1,100); }
break;
}

case 3:{
quet (3);
if (input (H1) ==
0){LCD_gotoxy(b,1);printf(LCD_putc,"3");b++;a=1;kp=3;keyarray(); coi_bao(1,100); }
else if (input (H2) ==
0){LCD_gotoxy(b,1);printf(LCD_putc,"6");b++;a=1;kp=6;keyarray(); coi_bao(1,100); }
else if (input (H3) ==
0){LCD_gotoxy(b,1);printf(LCD_putc,"9");b++;a=1;kp=9;keyarray(); coi_bao(1,100); }
else if (input (H4) ==
0){LCD_gotoxy(b,1);printf(LCD_putc,"=");b++;a=1;kp=11;keyarray();coi_bao(1,100);
}
break;
}
case 4:{
quet (4);
if (input (H1) ==
0){LCD_gotoxy(b,1);printf(LCD_putc,"*");b++;a=1;kp=12;keyarray(); coi_bao(1,100);
}

41
MENTOR: DR. Dang Phuoc Vinh Topic: Digital lock

else if (input (H2) ==


0){LCD_gotoxy(b,1);printf(LCD_putc,"*");b++;a=1;kp=13;keyarray(); coi_bao(1,100);}
else if (input (H3) ==
0){LCD_gotoxy(b,1);printf(LCD_putc,"*");b++;a=1;kp=14;keyarray(); coi_bao(1,100);}
else if (input (H4) ==
0){LCD_gotoxy(b,1);printf(LCD_putc,"*");b++;a=1;kp=15;keyarray(); coi_bao(1,100);}
break;
}
}
do {x = input (H1) & input (H2) & input (H3) & input (H4);
}
while (x == 0);

}
}

void mocua()
{ set_tris_c(0);

output_high(PIN_c0);
delay_us(1000);
output_low(PIN_c0);
delay_us(19000);

void dongcua()

42
MENTOR: DR. Dang Phuoc Vinh Topic: Digital lock

{ set_tris_c(0);

output_high(PIN_c0);
delay_us(2000);
output_low(PIN_c0);
delay_us(18000);

void check_pass()
{
for(int j=0;j<4;j++){
if(password[j] == pw_nhap[j])
{
tt++;
delay_ms(200);
}
else
{
lcd_putc("\fERROR");
coi_bao(5,100);
delay_ms(500);
break;

}
if (tt>=4)

43
MENTOR: DR. Dang Phuoc Vinh Topic: Digital lock

lcd_putc("\fWELCOME");
delay_ms(500);
mocua();
delay_ms(1000);
dongcua();
}
}
}

void visual()
{
c = getch ();
if(c=='1') mocua();
if(c=='2') dongcua();
}

void main()
{
CHAR UID[6];
UNSIGNED int TagType;
lcd_init ();
output_low(PIN_A5);
set_tris_c(0x00);
set_tris_d(0x00);
set_tris_b(0x0F);

44
MENTOR: DR. Dang Phuoc Vinh Topic: Digital lock

set_tris_a(0x03);
set_tris_e(0xFF);
port_b_pullups(1);
enter_pass();
while(TRUE)
{

visual();
nhap_phim();
if(b==5)
{check_pass();
enter_pass();
h=0;
tt=0;
b=1;
}
if(input(PIN_E2)==0)
{
mocua();
delay_ms(1000);
dongcua();}

IF (MFRC522_isCard (&TagType))
{

45
MENTOR: DR. Dang Phuoc Vinh Topic: Digital lock

IF (MFRC522_ReadCardSerial (&UID))
{
tt_1 = QUET_THE(DATA_KHAI,UID);
tt_2 = QUET_THE(DATA_QUAN,UID);

if( tt_1 == 1)
{

printf(LCD_PUTC, "\f Phan Van Khai ");


lcd_gotoxy(1,2);
printf(LCD_PUTC, "xin moi ban vao");
output_high(PIN_C0);
mocua();

delay_ms(5000);
lcd_putc("\f");
lcd_gotoxy(1,2);
printf(LCD_PUTC, "Cua da duoc dong");
output_low(PIN_C0);
dongcua();
delay_ms(500);
}

else if(tt_2 == 1)
{
printf(LCD_PUTC, "\fTran Anh Quan");

46
MENTOR: DR. Dang Phuoc Vinh Topic: Digital lock

lcd_gotoxy(1,2);
printf(LCD_PUTC, "WELCOME");
output_high(PIN_C0);
mocua();

delay_ms(5000);
lcd_putc("\f");
lcd_gotoxy(1,2);
printf(LCD_PUTC, "CLOSED");
output_high(PIN_C0);
dongcua();
delay_ms(500);
}
else if (tt_1==0 & tt_2==0)
{
lcd_gotoxy(1, 1);
lcd_putc ("WRONG");
lcd_gotoxy(4, 2);
lcd_putc ("WARNING!!!");
coi_bao(5,100) ;
}
}
MFRC522_Halt () ;
}
}
}

47
MENTOR: DR. Dang Phuoc Vinh Topic: Digital lock

4.2. Visual

Figure 56. Visual studio

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;

48
MENTOR: DR. Dang Phuoc Vinh Topic: Digital lock

using System.IO.Ports;
using AForge.Video;
using AForge.Video.DirectShow;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private FilterInfoCollection cameras;
private VideoCaptureDevice cam;

public Form1()
{

InitializeComponent();
cameras = new FilterInfoCollection(FilterCategory.VideoInputDevice);
foreach(FilterInfo info in cameras)
{ comboBox2.Items.Add(info.Name); }
comboBox2.SelectedIndex = 0;
khoi_tao_bang(); //2. Khởi tạo bảng dữ liệu: datagridview1
loadData(); // 3. Lấy dữ liệu ở access đưa lên bảng datagrdiview
}

private void btnConnect_Click(object sender, EventArgs e)


{
if (serialPort1.IsOpen) serialPort1.Close();
try

49
MENTOR: DR. Dang Phuoc Vinh Topic: Digital lock

{
serialPort1.PortName = comboBox1.Text;
serialPort1.Open();
btnConnect.Enabled = false;
btnDisconnect.Enabled = true;
groupBox2.Enabled = true;
groupBox3.Enabled = true;
timer1.Start();
}
catch(Exception ex)
{
MessageBox.Show("Error!"+ex.Message);
}

private void btnDisconnect_Click(object sender, EventArgs e)


{
if (serialPort1.IsOpen) serialPort1.Close();
btnConnect.Enabled = true;
btnDisconnect.Enabled = false;
groupBox2.Enabled = false;
groupBox3.Enabled = false;
}

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)


{

50
MENTOR: DR. Dang Phuoc Vinh Topic: Digital lock

private void label1_Click(object sender, EventArgs e)


{

private void label3_Click(object sender, EventArgs e)


{

private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)


{

private void comboBox5_SelectedIndexChanged(object sender, EventArgs e)


{

private void label4_Click(object sender, EventArgs e)


{

private void label6_Click(object sender, EventArgs e)


{

51
MENTOR: DR. Dang Phuoc Vinh Topic: Digital lock

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)


{

private void khoi_tao_bang()


{
dataGridView1.AutoGenerateColumns = false;
const int NumberColumn = 5;
dataGridView1.ColumnCount = NumberColumn;
string[] list = new string[NumberColumn] { "STT", "MSSV", "Ten", "NamSinh", "Khoa"};
string[] header_name = new string[NumberColumn] { "STT", "MSSV", "Tên", "Năm sinh",
"Khoa" };
int[] width_col = new int[NumberColumn] { 50, 150, 150, 120, 100 };

for (int i = 0; i < NumberColumn; i++)


{
dataGridView1.Columns[i].Name = list[i];
dataGridView1.Columns[i].DataPropertyName = list[i];
dataGridView1.Columns[i].HeaderText = header_name[i];
dataGridView1.Columns[i].Width = width_col[i];
dataGridView1.Columns[i].ValueType = typeof(String);
dataGridView1.Columns[i].Visible = true;
}
}

private void loadData()


{

52
MENTOR: DR. Dang Phuoc Vinh Topic: Digital lock

DataTable my_data = new DataTable();


my_data.Load(Program.Database.SelectSQL("SELECT * FROM danhsach"));
dataGridView1.DataSource = my_data;
}

private void groupBox1_Enter(object sender, EventArgs e)


{

private void Form1_Load(object sender, EventArgs e)


{
btnConnect.Enabled = true;
btnDisconnect.Enabled = false;
groupBox2.Enabled = false;
groupBox3.Enabled = false;

string[] ports = SerialPort.GetPortNames();


foreach (string port in ports)
comboBox1.Items.Add(port);

private void button1_Click_1(object sender, EventArgs e)


{
serialPort1.Write("2");
pictureBox1.Image = Properties.Resources.door;
}

53
MENTOR: DR. Dang Phuoc Vinh Topic: Digital lock

private void pictureBox1_Click(object sender, EventArgs e)


{

private void pictureBox1_Click_1(object sender, EventArgs e)


{

private void btnmo_Click_1(object sender, EventArgs e)


{
serialPort1.Write("1");
pictureBox1.Image = Properties.Resources.doormo;
}

private void btnLuu_Click_1(object sender, EventArgs e)


{
try
{
// lệnh đúng
String sql = "insert into danhsach (MSSV, Ten, NamSinh, Khoa) values ('"
+ cMSSV.Text + "','"
+ cTen.Text + "','"
+ cNamSinh.Text + "','"
+ cKhoa.Text + "')";

OleDbDataReader reader = Program.Database.SelectSQL(sql);

54
MENTOR: DR. Dang Phuoc Vinh Topic: Digital lock

loadData();
}
catch
{
MessageBox.Show("Có lỗi");
}
}

private void comboBox1_SelectedIndexChanged_1(object sender, EventArgs e)


{

private void label7_Click(object sender, EventArgs e)


{
String ma_the = "";
String tam = serialPort1.ReadExisting().ToString();

if (!String.IsNullOrEmpty(tam))
{
char[] tam2 = tam.ToCharArray();
if (tam2[0] == 0x02)
{
for (int j = 1; j < 13; j++)
{
ma_the = ma_the + tam2[j].ToString();
}
}
if (ma_the != "") label7.Text = ma_the;
}

55
MENTOR: DR. Dang Phuoc Vinh Topic: Digital lock

private void timer1_Tick(object sender, EventArgs e)


{
string ma_the = serialPort1.ReadExisting();
if (ma_the != "") label7.Text = ma_the;
}

private void dataGridView1_CellContentClick_1(object sender, DataGridViewCellEventArgs e)


{

private void pictureBox5_Click(object sender, EventArgs e)


{

private void pictureBox6_Click(object sender, EventArgs e)


{

private void pictureBox9_Click(object sender, EventArgs e)


{

private void pictureBox10_Click(object sender, EventArgs e)


{

56
MENTOR: DR. Dang Phuoc Vinh Topic: Digital lock

private void pictureBox11_Click(object sender, EventArgs e)


{

private void textBox1_TextChanged(object sender, EventArgs e)


{

private void pictureBox8_Click(object sender, EventArgs e)


{

private void textBox2_TextChanged(object sender, EventArgs e)


{

private void pictureBox3_Click(object sender, EventArgs e)


{

private void textBox3_TextChanged(object sender, EventArgs e)


{

57
MENTOR: DR. Dang Phuoc Vinh Topic: Digital lock

}
private void textBox4_TextChanged(object sender, EventArgs e)
{
}
private void button3_Click(object sender, EventArgs e)
{
if(cam != null && cam.IsRunning)
{
cam.Stop();
}
cam = new VideoCaptureDevice(cameras[comboBox2.SelectedIndex].MonikerString);
cam.NewFrame += cam_NewFrame;
cam.Start();
}
void cam_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
Bitmap bitmap = (Bitmap)eventArgs.Frame.Clone();
pictureBox3.Image = bitmap;
}
private void button2_Click(object sender, EventArgs e)
{
saveFileDialog1.InitialDirectory = "C:\\Users\\VICTUS\\pictures";
if(saveFileDialog1.ShowDialog() == DialogResult.OK)
{
pictureBox3.Image.Save(saveFileDialog1.FileName);
}
}
}
}

58
MENTOR: DR. Dang Phuoc Vinh Topic: Digital lock

CHAPTER 4: CONCLUSION
1. Conclusion

The circuit has worked with concise, easy-to-understand functions, from which it
can be relied on to develop applications in current life.
2. Drawback
- With this database comparison model, we still have to bring a computer when we need
to use it.
- We have not been able to scan the magnetic card to return data to the computer.
- No password change function.

59
MENTOR: DR. Dang Phuoc Vinh Topic: Digital lock

REFERENCES
[1] Đặng Phước Vinh, Trần Quang Khải, Đoàn Lê Anh, Võ Như Thành, Phạm Anh Đức,
“Lập trình Vi Điều khiển PIC và Thiết Bị Ngoại Vi”, NSB KH và KT.
[2] https://www.youtube.com/watch?v=htoHSMjgVSE&list=LL&index=14&t=97s
[3] https://www.youtube.com/watch?v=zkOL2jri3DE&list=LL&index=3

60

You might also like