• Dhanush kumar S

Interfacing Fingerprint Sensor with Raspberry Pi

Updated: Sep 6, 2020


Do you know how the Biometric attendance system in your schools or colleges works? Nowadays, Just by placing a finger on the board one can access all the basic information about you. All these processes happen only because of the #fingerprint sensor. while going through this article, you can gain some knowledge about these sensors and the controlling unit which is nothing but #raspberrypi.


This interfacing is pretty simple and can be used as a reference for various projects in the future. We are going to learn about the entire process involved in this interfacing, starting from the list of required components.


List:

The following list provides the hardware and software components required to perform this interfacing.

Hardware components:


1.Fingerprint Sensor - R307:

The number of fingerprints that can be stored is about 1000. The operating voltage of the R307 module is 3.3 V and there is a possibility of USB operation in it. The fingerprint detection output option is also available in the R307 sensor module. Here, we are using the #fingerprint sensor to capture our fingerprint and display the output with the help of #Raspberrypi.


· Normal working current: 50 mA

· Peak current: 80 mA

· Supply voltage: DC 4.2- 6.0 V

· Window area: 14x18 mm

· Matching method: Comparison method(1:1)


2.Raspberry Pi 3:

We are using Raspberrypi to connect with the fingerprint module and display the output. It contains several I/O pins using which we can connect the module and then by coding the Raspberrypi, we will receive the commands/signals that are sent from the fingerprint sensor.



3.CP2102 USB to TTL converter:

This module creates a virtual port on your computer using USB which can support various Baud rates for serial communication.


4.Jumper wires:

These are simple connecting wires, that are used to connect the ends without any soldering. The male wires have the ends that can be connected to other ends and the female wires are the ones that have the receiving end. In this interfacing, female to female wires is used.


5.USB Cable:

This cable is used to connect the RaspberryPi to the power supply. It also helps in the transmission of data.


Software components:


6.SSH Terminal:

The SHH Terminal is used in this project to connect the Raspberry Pi module to the terminal of another computer.


7.Python IDE:

#Python Programming is done in an IDE (Integrated Development Environment) is a platform where we can write the code, run, and test the working.

Circuit:

The fingerprint sensor #R307 module is first interfaced with CP2 102 USB converter and then it is connected to the respective port of the raspberry pi device.


What goes where?

  • · RED wire connects the VCC pin of the fingerprint sensor to either 3.3 V pin or 5 V pin of the USB converter depending on the usage of either R305 or #R307 module.

  • · BLACK wire connects the ground pin of the sensor to the ground of the USB converter.

  • · BLUE wire connects the transmission pin[TX] of the sensor to the reception pin[RX] of the USB converter.

  • · YELLOW wire connects the reception pin[RX] of the sensor to the transmitting pin[TX] of the USB converter

Here, the DTR port of the CP2 102 USB converter is not involved in this interfacing.


After connecting the ports of the sensor and USB converter, the power supply is given. The raspberry pi device gets boot up.


Code:


1. Enroll Fingerprint

At first, Import the fingerprint package from the python library. Then the sensor is tested for initialization with the appropriate baud rate and it is checked for its password. The template count where the fingerprint can be stored is acquired. The memory space required for storing the fingerprint is also mentioned.

import time
from pyfingerprint.pyfingerprint import PyFingerprint


## Enrolls new finger
##

## Tries to initialize the sensor
try:
    f = PyFingerprint('/dev/ttyUSB0', 9600, 0xFFFFFFFF, 0x00000000)

    if ( f.verifyPassword() == False ):
        raise ValueError('The given fingerprint sensor password is wrong!')

except Exception as e:
    print('The fingerprint sensor could not be initialized!')
    print('Exception message: ' + str(e))
    exit(1)

## Gets some sensor information
print('Currently used templates: ' + str(f.getTemplateCount()) +'/'+ str(f.getStorageCapacity()))
 

The fingerprint is now detected and converted into machine-readable characters by employing image processing and stored in char buffer 1. With the help, if-else loop condition the acquired fingerprint is checked for a match with the existing print. If there is any match, the template count of that particular fingerprint should be shown and then the print is removed.

## Tries to enroll new finger
try:
    print('Waiting for finger...')

    ## Wait that finger is read
    while ( f.readImage() == False ):
        pass

    ## Converts read image to characteristics and stores it in charbuffer 1
    f.convertImage(0x01)

    ## Checks if finger is already enrolled
    result = f.searchTemplate()
    positionNumber = result[0]

    if ( positionNumber >= 0 ):
        print('Template already exists at position #' + str(positionNumber))
        exit(0)

    print('Remove finger...')
    time.sleep(2)

    print('Waiting for same finger again...')

    ## Wait that finger is read again
    while ( f.readImage() == False ):
        pass

Again the fingerprint is detected and stored in char buffer 2. The same process is repeated. If a new fingerprint is detected it is stored in another variable called PositionNumber. An exception is thrown in case of any discrepancy.

import time
from pyfingerprint.pyfingerprint import PyFingerprint


## Enrolls new finger
##

## Tries to initialize the sensor
try:
    f = PyFingerprint('/dev/ttyUSB0', 9600, 0xFFFFFFFF, 0x00000000)

    if ( f.verifyPassword() == False ):
        raise ValueError('The given fingerprint sensor password is wrong!')

except Exception as e:
    print('The fingerprint sensor could not be initialized!')
    print('Exception message: ' + str(e))
    exit(1)

## Gets some sensor information
print('Currently used templates: ' + str(f.getTemplateCount()) +'/'+ str(f.getStorageCapacity()))

## Tries to enroll new finger
try:
    print('Waiting for finger...')

    ## Wait that finger is read
    while ( f.readImage() == False ):
        pass

    ## Converts read image to characteristics and stores it in charbuffer 1
    f.convertImage(0x01)

    ## Checks if finger is already enrolled
    result = f.searchTemplate()
    positionNumber = result[0]

    if ( positionNumber >= 0 ):
        print('Template already exists at position #' + str(positionNumber))
        exit(0)

    print('Remove finger...')
    time.sleep(2)

    print('Waiting for same finger again...')

    ## Wait that finger is read again
    while ( f.readImage() == False ):
        pass

    ## Converts read image to characteristics and stores it in charbuffer 2
    f.convertImage(0x02)

    ## Compares the charbuffers
    if ( f.compareCharacteristics() == 0 ):
        raise Exception('Fingers do not match')

    ## Creates a template
    f.createTemplate()

    ## Saves template at new position number
    positionNumber = f.storeTemplate()
    print('Finger enrolled successfully!')
    print('New template position #' + str(positionNumber))

except Exception as e:
    print('Operation failed!')
    print('Exception message: ' + str(e))
    exit(1)

Download the code here,

example_enroll code
.txt
TXT • 2KB




Note: This file is in the text format and should be converted to python-format (.py) before downloading.


Similarly, there are codes available for operations such as downloading the image of the fingerprint, searching the existing fingerprint, and deleting a fingerprint.


2. Deleting a fingerprint:


This code is used to delete a registered fingerprint from the fingerprint data stored previously.


from pyfingerprint.pyfingerprint import PyFingerprint


## Deletes a finger from sensor
##


## Tries to initialize the sensor
try:
    f = PyFingerprint('/dev/ttyUSB0', 9600, 0xFFFFFFFF, 0x00000000)

    if ( f.verifyPassword() == False ):
        raise ValueError('The given fingerprint sensor password is wrong!')

except Exception as e:
    print('The fingerprint sensor could not be initialized!')
    print('Exception message: ' + str(e))
    exit(1)

## Gets some sensor information
print('Currently used templates: ' + str(f.getTemplateCount()) +'/'+ str(f.getStorageCapacity()))

## Tries to delete the template of the finger
try:
    positionNumber = input('Please enter the template position you want to delete: ')
    positionNumber = int(positionNumber)

    if ( f.deleteTemplate(positionNumber) == True ):
        print('Template deleted!')

except Exception as e:
    print('Operation failed!')
    print('Exception message: ' + str(e))
    exit(1)


Download the code here.

example_delete code
.txt
TXT • 1KB




Note: This file is in the text format and should be converted to python-format (.py) before downloading.


3. Search Fingerprint:

This code is used to search our fingerprint from the data which has been stored.


import hashlib
from pyfingerprint.pyfingerprint import PyFingerprint


## Search for a finger
##

## Tries to initialize the sensor
try:
    f = PyFingerprint('/dev/ttyUSB0', 9600, 0xFFFFFFFF, 0x00000000)

    if ( f.verifyPassword() == False ):
        raise ValueError('The given fingerprint sensor password is wrong!')

except Exception as e:
    print('The fingerprint sensor could not be initialized!')
    print('Exception message: ' + str(e))
    exit(1)

## Gets some sensor information
print('Currently used templates: ' + str(f.getTemplateCount()) +'/'+ str(f.getStorageCapacity()))

## Tries to search the finger and calculate hash
try:
    print('Waiting for finger...')

    ## Wait that finger is read
    while ( f.readImage() == False ):
        pass

    ## Converts read image to characteristics and stores it in charbuffer 1
    f.convertImage(0x01)

    ## Searchs template
    result = f.searchTemplate()

    positionNumber = result[0]
    accuracyScore = result[1]

    if ( positionNumber == -1 ):
        print('No match found!')
        exit(0)
    else:
        print('Found template at position #' + str(positionNumber))
        print('The accuracy score is: ' + str(accuracyScore))

    ## OPTIONAL stuff
    ##

    ## Loads the found template to charbuffer 1
    f.loadTemplate(positionNumber, 0x01)

    ## Downloads the characteristics of template loaded in charbuffer 1
    characterics = str(f.downloadCharacteristics(0x01)).encode('utf-8')

    ## Hashes characteristics of template
    print('SHA-2 hash of template: ' + hashlib.sha256(characterics).hexdigest())

except Exception as e:
    print('Operation failed!')
    print('Exception message: ' + str(e))
    exit(1)

Download the code here.

example_search code
.txt
TXT • 2KB




Note: This file is in the text format and should be converted to python-format (.py) before downloading.


4. Download Fingerprint Image:

This code is used to download the image of our fingerprint which has been captured by the sensor.

import tempfile
from pyfingerprint.pyfingerprint import PyFingerprint


## Reads image and download it
##

## Tries to initialize the sensor
try:
    f = PyFingerprint('/dev/ttyUSB0', 9600, 0xFFFFFFFF, 0x00000000)

    if ( f.verifyPassword() == False ):
        raise ValueError('The given fingerprint sensor password is wrong!')

except Exception as e:
    print('The fingerprint sensor could not be initialized!')
    print('Exception message: ' + str(e))
    exit(1)

## Gets some sensor information
print('Currently used templates: ' + str(f.getTemplateCount()) +'/'+ str(f.getStorageCapacity()))

## Tries to read image and download it
try:
    print('Waiting for finger...')

    ## Wait that finger is read
    while ( f.readImage() == False ):
        pass

    print('Downloading image (this take a while)...')

    imageDestination =  tempfile.gettempdir() + '/fingerprint.bmp'
    f.downloadImage(imageDestination)

    print('The image was saved to "' + imageDestination + '".')

except Exception as e:
    print('Operation failed!')
    print('Exception message: ' + str(e))
    exit(1)


Download the code here.

example_downloadimage code
.txt
TXT • 1KB




Note: The files above are in .txt format but should be converted into python file format (.py format) before uploading the code to Raspberry Pi.


Working:

Before executing the code, certain packages are needed to be installed to complete the interface.


Commands to install the required packages -


Open the SSH Terminal to install the packages and run the following commands:

Root privileges are required to run these commands. To enter the root use the command

sudo bash

Now, install the packages using the below command

wget –O – http://apt.pm-codeworks.de/pm-codeworks.de.gpg | apt-key add –
wget http://apt.pm-codeworks.de/pm-codeworks.list -P /etc/apt/sources.list.d/


To update your Raspberry Pi in the root itself use the with command

apt-get update

Install the fingerprint sensor library with

apt-get install python-fingerprint -yes

In case, you face any error while installing the package then type

apt-get -f install

Finally, after installing type "exit" to exit the root.


After executing any of the above-mentioned codes, the corresponding output is displayed in the raspberry pi terminal.

Output 1 - Enrolling Fingerprint

Output 2 - Searching Fingerprint

Output 3 - Deleting Fingerprint

Output 4 - Downloading Fingerprint Image

Fingerprint Image


To see the practical implementation of the above-explained tutorial, watch the video below:

Learn Electronics. (June 20, 2020). Interfacing fingerprint sensor with Raspberry Pi. https://www.youtube.com/watch?v=DVwt7r8w0zw.

The day-to-day applications of fingerprint sensors include mobile lock, security systems, and biometric attendance at schools and colleges and this interfacing is the base of all those. In this interfacing, Python language is used, so the beginners can also perform the interfacing operations quite easily.


See also:

  1. Interfacing a Buzzer with Arduino Board

  2. Smart lighting system- using LEDs, LDR, and raspberry pi

  3. Article on an interfacing LCD display with raspberry pi

1,320 views