Code Monkey home page Code Monkey logo

adafruit_circuitpython_fingerprint's Introduction

Introduction

Documentation Status Discord Build Status Code Style: Black

This library will let you use an Adafruit Fingerprint sensor on any UART to get, store, retreive and query fingerprints! Great for adding bio-sensing security to your next build.

Dependencies

This driver depends on:

Please ensure all dependencies are available on the CircuitPython filesystem. This is easily achieved by downloading the Adafruit library and driver bundle.

Installing from PyPI

On supported GNU/Linux systems like the Raspberry Pi, you can install the driver locally from PyPI. To install for current user:

pip3 install adafruit-circuitpython-fingerprint

To install system-wide (this may be required in some cases):

sudo pip3 install adafruit-circuitpython-fingerprint

To install in a virtual environment in your current project:

mkdir project-name && cd project-name
python3 -m venv .venv
source .venv/bin/activate
pip3 install adafruit-circuitpython-fingerprint

Usage Example

See 'examples' folder for full usage demo!

Documentation

API documentation for this library can be found on Read the Docs.

For information on building library documentation, please check out this guide.

Contributing

Contributions are welcome! Please read our Code of Conduct before contributing to help this project stay welcoming.

adafruit_circuitpython_fingerprint's People

Contributors

ajiekurniawansaputra avatar brennen avatar dhalbert avatar evaherrada avatar foamyguy avatar jepler avatar jerryneedell avatar jim-mckeown avatar kattni avatar ladyada avatar prcutler avatar siddacious avatar sommersoft avatar stitchesnburns avatar tannewt avatar tekktrik avatar thekitty avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

adafruit_circuitpython_fingerprint's Issues

Aura LED control not functioning

I am using the Ultra-Slim Round Fingerprint Sensor and having an issue controlling the aura LED. The scanner is working perfectly in all other respects (scanning, enrolling, etc) and the aura LED is working fine it automatic mode. But I need to turn off the blue breathing LED when my device is not ready to scan a fingerprint and I am so-far unable to do so.

The LED control function (set_led) sends and receives ok.

SENT: 0xEF 0x01 0xFF 0xFF 0xFF 0xFF 0x01 0x00 0x07 0x35 0x04 0x80 0x01 0x00 0x00 0xC2 
RCVD: 0x00 

If it adds any useful information the FINGERPRINT_LEDOFF (0x51) command fails. I am not sure if it is supposed to work on this device because it is not in all versions of the code.

I started a thread in the Adafruit forum but we were unable to resolve it there.

Getting incorrect packet data when uploading image

Hi,
I've tested the PR and I'm receiving this error when downloading template. The last debug lines are:
Downloading template...
*** DEBUG ==> _send_packet length: 13
*** DEBUG ==> _send_packet data: ['ef', '01', 'ff', 'ff', 'ff', 'ff', '01', '00', '04', '08', '01', '00', '0e']
*** DEBUG ==> _get_packet received data: ['ef', '01', 'ff', 'ff', 'ff', 'ff', '07', '00', '03', '00', '00', '0a']
*** DEBUG ==> _get_packet reply: ['00']
*** DEBUG ==> _get_data received data: ['ef', '01', 'ff', 'ff', 'ff', 'ff', '02', '00', '82']
*** DEBUG ==> _get_data received start pos: 0xef01
*** DEBUG ==> _get_data received address: [255, 255, 255, 255]
*** DEBUG ==> _get_data received packet_type: 0x2
*** DEBUG ==> _get_data received length: 0x82
*** DEBUG ==> _get_data received checksum: (20956,)
*** DEBUG ==> _get_data received data: ['36', 'ab', '14', '65', '0f', 'a7', '05', '1f', '2e']
*** DEBUG ==> _get_data received start pos: 0x36ab
Traceback (most recent call last):
File "adafruit_template_file_compare.py", line 196, in
enroll_save_to_file()
File "adafruit_template_file_compare.py", line 147, in enroll_save_to_file
data = finger.get_fpdata("char", 1)
File "/home/pi/huellas/adafruit.py", line 222, in get_fpdata
res = self._get_data(9)
File "/home/pi/huellas/adafruit.py", line 405, in _get_data
reply += self._get_data(9)
File "/home/pi/huellas/adafruit.py", line 382, in _get_data
raise RuntimeError("Incorrect packet data")
RuntimeError: Incorrect packet data

The data received length is 130 (I showed it in hex). For some reason there's no next complete parcel, don't know why. Any clue?
Thx

Fingerprint Image

Hey, thanks for the project. I grabbed the finger image from the sensor, using @stitchesnburns work (in pull requests), and it looks misplaced.

can you explain why the finger seems to be repeated 3 times with different details?

Rename template upload/download to R503 specific

@jerryneedell I finally got a chance to test the optical sensors. I got two different models:

https://www.adafruit.com/product/4690
and
https://www.adafruit.com/product/751

image

As you suspected, the LED method is causing issues with these two units. The good thing is the template upload/download does work but there is a wierd extra packet being sent by these two modules when asked to compare two template (instruction 03x):

*** DEBUG ==> _send_packet data: ['ef', '01', 'ff', 'ff', 'ff', 'ff', '01', '00', '03', '03', '00', '07']   
*** DEBUG ==> _get_packet received data: ['ef', '01', 'ff', 'ff', 'ff', 'ff', '07', '00', '03', '01', '00', '0b']  <<=== Failure packet
*** DEBUG ==> _get_packet reply: ['01']  
*** DEBUG ==> _get_packet received data: ['ef', '01', 'ff', 'ff', 'ff', 'ff', '07', '00', '05', '00', '00', 'ff', '01', '0b']  <<=== Followed by proper expected packet
*** DEBUG ==> _get_packet reply: ['00', '00', 'ff']  
*** DEBUG ==> compare_templates confidence: (255,)  
Fingerprint match template in file.   

It sends error when receiving package (01x) followed by a proper/expected packet. It does not appear to affect the functionality.

I guess The easiest thing to do is to create PR and rename the template upload/down example to R503 specific. We can just document what needs to be done to make the example work with non R503 sensors.

AS608 Optical Fingerprint Sensor With Raspberry PI is not waiting for finger input

I'm trying to connect Fingerprint (AS608) sensor with Raspberry PI 3 B+.

finger.get_image() function is not waiting to put finger on sensor. returning 0x0 automatically.

used ttyUSB0 port.

I'm referring source code here https://github.com/adafruit/Adafruit_CircuitPython_Fingerprint/blob/main/examples/fingerprint_simpletest.py

Version's

  • adafruit-circuitpython-fingerprint==2.2.10
  • Raspberry PI 3 B+
  • AS608 Optical Fingerprint Sensor

Hitting memory issues on M0 boards

Re this thread:
https://forums.adafruit.com/viewtopic.php?f=58&t=180064

Guide shows using with a Trinket M0:
https://learn.adafruit.com/adafruit-optical-fingerprint-sensor/circuitpython#circuitpython-microcontroller-wiring-3044423-6

But doing so runs into memory issue:

Adafruit CircuitPython 6.3.0 on 2021-06-01; Adafruit Trinket M0 with samd21e18
>>> import fingerprint_simpletest
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "fingerprint_simpletest.py", line 8, in <module>
  File "adafruit_fingerprint.py", line 94, in <module>
MemoryError: memory allocation failed, allocating 296 bytes
>>> 

the template_file_compare.py always show same error of Incorrect packet data when run,why?and the other examples run brilliant.

INFO: Sensor les not support LED. Error: Incorrect packet data
Place finger on sensor...Traceback (most recent call last):
File "/home/pi/Desktop/adafruit_finger_compared.py", line 192, in
enroll_save_to_file()
File "/home/pi/Desktop/adafruit_finger_compared.py", line 91, in enroll_save_to_file
i = finger.get_image()
File "/usr/local/lib/python3.9/dist-packages/adafruit_fingerprint.py", line 179, in get_image
return self._get_packet(12)[0]
File "/usr/local/lib/python3.9/dist-packages/adafruit_fingerprint.py", line 354, in _get_packet
raise RuntimeError("Incorrect packet data")
RuntimeError: Incorrect packet data

import error

after running the fingerprint_simpletest.py code i received this error.
I'm running the code in my esp8266 board with the Micropython firmware.

Traceback (most recent call last):
File "", line 5, in
ImportError: no module named 'board'

Error in _send_data

Hello,
I think this statement for j in range(len(data[start:end])): needs to be revised to for j in range(start, end): otherwise it is sending the same chunk of data over and over again. Just checking...

packet.append(length & 0xFF)
checksum = _DATAPACKET + (length >> 8) + (length & 0xFF)
for j in range(len(data[start:end])):
packet.append(data[j])
checksum += data[j]
packet.append(checksum >> 8)
packet.append(checksum & 0xFF)
# print("Sending: ", [hex(i) for i in packet])
self._uart.write(packet)
# print(i)
i += 1
start = i * (data_length - 2)
end = (i + 1) * (data_length - 2)
# print(start)
# print(end)
# print(i)
packet = [_STARTCODE >> 8, _STARTCODE & 0xFF]
packet = packet + self.address
packet.append(_ENDDATAPACKET)
length = len(data[start:end]) + 2
# print(length)
packet.append(length >> 8)
packet.append(length & 0xFF)
checksum = _ENDDATAPACKET + (length >> 8) + (length & 0xFF)
for j in range(len(data[start:end])):
packet.append(data[j])
checksum += data[j]

import typing / import ustruct

I'm using a Metro M0 express with Circuitpython 7.0.0 and when I try to run a simple code with import adafruit_fingerprint I get a ImportError: no module named 'ustruct'. While checking the code I saw that the fingerrprint lib try to import ustruct only if typing, busio or struct isn't present. By checking the default module of Circuitpython 7.0.0 I can confirm the absence of typing and ustruct.
Am I missing something?

Missing Type Annotations

There are missing type annotations for some functions in this library.

The typing module does not exist on CircuitPython devices so the import needs to be wrapped in try/except to catch the error for missing import. There is an example of how that is done here:

try:
    from typing import List, Tuple
except ImportError:
    pass

Once imported the typing annotations for the argument type(s), and return type(s) can be added to the function signature. Here is an example of a function that has had this done already:

def wrap_text_to_pixels(
    string: str, max_width: int, font=None, indent0: str = "", indent1: str = ""
) -> List[str]:

If you are new to Git or Github we have a guide about contributing to our projects here: https://learn.adafruit.com/contribute-to-circuitpython-with-git-and-github

There is also a guide that covers our CI utilities and how to run them locally to ensure they will pass in Github Actions here: https://learn.adafruit.com/creating-and-sharing-a-circuitpython-library/check-your-code In particular the pages: Sharing docs on ReadTheDocs and Check your code with pre-commit contain the tools to install and commands to run locally to run the checks.

If you are attempting to resolve this issue and need help, you can post a comment on this issue and tag both @FoamyGuy and @kattni or reach out to us on Discord: https://adafru.it/discord in the #circuitpython-dev channel.

The following locations are reported by mypy to be missing type annotations:

  • adafruit_fingerprint.py:114
  • adafruit_fingerprint.py:159
  • adafruit_fingerprint.py:179
  • adafruit_fingerprint.py:191
  • adafruit_fingerprint.py:197
  • adafruit_fingerprint.py:203
  • adafruit_fingerprint.py:209
  • adafruit_fingerprint.py:227
  • adafruit_fingerprint.py:323
  • adafruit_fingerprint.py:336
  • adafruit_fingerprint.py:369
  • adafruit_fingerprint.py:418
  • adafruit_fingerprint.py:437
  • adafruit_fingerprint.py:492

Cannot find print

Just started playing with the R503 fingerprint sensor on a grandcentral_m4_express.
It seems to enroll fingerprints OK so it is communicating but it repeatedly fails when trying to find a match.
I'm just using the fingerprint_simpletest.py from the examples.
Any suggestions?

Adafruit CircuitPython 6.0.0-alpha.1-45-g37e77b21c on 2020-07-14; Adafruit Grand Central M4 Express with samd51p20
>>> import finger
----------------
Fingerprint templates: [1]
e) enroll print
f) find print
d) delete print
----------------
> e
Enter ID # from 1-127: 2
Place finger on sensor........................................................................................................................................Image taken
Templating...Templated
Remove finger
Place same finger again................................................................Image taken
Templating...Templated
Creating model...Created
Storing model #2...Stored
----------------
Fingerprint templates: [1, 2]
e) enroll print
f) find print
d) delete print
----------------
> f
Waiting for image...
Templating...
Searching...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "finger.py", line 185, in <module>
  File "finger.py", line 34, in get_fingerprint
  File "adafruit_fingerprint.py", line 279, in finger_fast_search
  File "adafruit_fingerprint.py", line 292, in _get_packet
RuntimeError: Failed to read data from sensor
>>> 

Compare print to file Error

I'm trying to use this example but i get this error when I try to compare print to file.

Waiting for finger print... Templating... Loading file template...Traceback (most recent call last): File "/home/pi/Adafruit_CircuitPython_Fingerprint/examples/fingerprint_template_file_compare.py", line 199, in <module> fingerprint_check_file() File "/home/pi/Adafruit_CircuitPython_Fingerprint/examples/fingerprint_template_file_compare.py", line 72, in fingerprint_check_file i = finger.compare_templates() ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/pi/.local/lib/python3.11/site-packages/adafruit_fingerprint.py", line 323, in compare_templates r = self._get_packet(14) ^^^^^^^^^^^^^^^^^^^^ File "/home/pi/.local/lib/python3.11/site-packages/adafruit_fingerprint.py", line 349, in _get_packet raise RuntimeError("Failed to read data from sensor") RuntimeError: Failed to read data from sensor

I'm on raspberry pi 4 with this sensor

All the other examples works fine.

How can I save finger print image as jpg ?

It is more of a question than an issue. Please help.

finger = adafruit_fingerprint.Adafruit_Fingerprint(uart)

def enroll_finger(location):
    """Take a 2 finger images and template it, then store in 'location'"""
    for fingerimg in range(1, 3):
        if fingerimg == 1:
            print("Place finger on sensor...", end="", flush=True)
        else:
            print("Place same finger again...", end="", flush=True)

        while True:
            i = finger.get_image()
            if i == adafruit_fingerprint.OK:
                print("Image taken")
                break
            if i == adafruit_fingerprint.NOFINGER:
                print(".", end="", flush=True)
            elif i == adafruit_fingerprint.IMAGEFAIL:
                print("Imaging error")
                return False
            else:
                print("Other error")
                return False

        print("Templating...", end="", flush=True)
        i = finger.image_2_tz(fingerimg)
        if i == adafruit_fingerprint.OK:
            print("Templated")
        else:
            if i == adafruit_fingerprint.IMAGEMESS:
                print("Image too messy")
            elif i == adafruit_fingerprint.FEATUREFAIL:
                print("Could not identify features")
            elif i == adafruit_fingerprint.INVALIDIMAGE:
                print("Image invalid")
            else:
                print("Other error")
            return False

        if fingerimg == 1:
            print("Remove finger")
            time.sleep(1)
            while i != adafruit_fingerprint.NOFINGER:
                i = finger.get_image()

    print("Creating model...", end="", flush=True)
    i = finger.create_model()
    if i == adafruit_fingerprint.OK:
        print("Created")
    else:
        if i == adafruit_fingerprint.ENROLLMISMATCH:
            print("Prints did not match")
        else:
            print("Other error")
        return False

    print("Storing model #%d..." % location, end="", flush=True)
    i = finger.store_model(location)
    if i == adafruit_fingerprint.OK:
        print("Stored")
    else:
        if i == adafruit_fingerprint.BADLOCATION:
            print("Bad storage location")
        elif i == adafruit_fingerprint.FLASHERR:
            print("Flash storage error")
        else:
            print("Other error")
        return False

    return True

In this code, finger print is being stored in RAM I guess, how can we save the fingerprint image as jpg in some location ? For example like this:

def save_image_as_jpg(image_bytes):
    with open('image.jpg', 'wb') as f:
          f.write(image_bytes)

# How can I get the value of image_bytes to save it like this ?
save_image_as_jpg(image_bytes)

struct.error: unpack requires a buffer of 2 bytes

Hi, I am using r307 fingerprint sensor. I'm trying to compare fingerprint template by uploading it to the fingerprint sensor flash storage.

I'm trying to run this example code.

Here is the piece of code from the example which I failed to run. I've already saved the fingerprint template('template0.dat') file before executing this code.


# pylint: disable=too-many-branches
def fingerprint_check_file():
    """Compares a new fingerprint template to an existing template stored in a file
    This is useful when templates are stored centrally (i.e. in a database)"""
    print("Waiting for finger print...")
    set_led_local(color=3, mode=1)
    while finger.get_image() != adafruit_fingerprint.OK:
        pass
    print("Templating...")
    if finger.image_2_tz(1) != adafruit_fingerprint.OK:
        return False

    print("Loading file template...", end="", flush=True)
    with open("template0.dat", "rb") as file:
        data = file.read()
    finger.send_fpdata(list(data), "char", 2)

    i = finger.compare_templates()
    if i == adafruit_fingerprint.OK:
        set_led_local(color=2, speed=150, mode=6)
        print("Fingerprint match template in file.")
        return True
    if i == adafruit_fingerprint.NOMATCH:
        set_led_local(color=1, mode=2, speed=20, cycles=10)
        print("Templates do not match!")
    else:
        print("Other error!")
    return False

I got following error:

Waiting for finger print...
Templating...
Loading file template...Traceback (most recent call last):
File "/home/mockupsystem/Adafruit_CircuitPython_Fingerprint/examples/fingerprint_template_file_compare.py", line 203, in
fingerprint_check_file()
File "/home/mockupsystem/Adafruit_CircuitPython_Fingerprint/examples/fingerprint_template_file_compare.py", line 73, in fingerprint_check_file
i = finger.compare_templates()
File "/home/mockupsystem/python-env/some/lib/python3.10/site-packages/adafruit_fingerprint.py", line 323, in compare_templates
self.confidence = struct.unpack(">H", bytes(r[1:3]))
struct.error: unpack requires a buffer of 2 bytes

MemoryError

Thanks for helping me out with the Import Error I had yesterday i have come through it now with your steps.
But I had another error trying to to run the "fingerprint_simplest.py" example code. Below is the error I got while trying to run the code on my esp. 8266 micro controller device. I would be glad if you can reply as prompt as you had always done.

Traceback (most recent call last):
File "", line 5, in
File "/lib/board.py", line 39, in
File "/lib/adafruit_platformdetect/init.py", line 10, in
MemoryError:

Can't template file compare with SEN0188

I want to store a fingerprint template in a file, and then compare it with one newly obtained with the sensor. For that I'm using the code in the example you provided (examples/fingerprint_tempalte_file_compare.py).

Im getting the following error:

Traceback (most recent call last):
  File "/home/pi/biometrics/tests/fingerprint_compare_files.py", line 200, in <module>
    fingerprint_check_file()
  File "/home/pi/biometrics/tests/fingerprint_compare_files.py", line 72, in fingerprint_check_file
    i = finger.compare_templates()
  File "/usr/local/lib/python3.9/dist-packages/adafruit_fingerprint.py", line 324, in compare_templates
    self.confidence = struct.unpack(">H", bytes(r[1:3]))
struct.error: unpack requires a buffer of 2 bytes

Which is relted to this function:

def compare_templates(self) -> int:
    self._send_packet([_COMPARE])
    r = self._get_packet(14)
    self.confidence = struct.unpack(">H", bytes(r[1:3]))
    self._print_debug("compare_templates confidence:", self.confidence)
    return r[0]

The value of r after r = self._get_packet(14) is [1], which is the code for PACKETRECIEVEERR.
So what is happening? The sensor is unable to make the comparison? The problem is the _COMPARE instruction or it may be the data that was sended before?
Note that everything works for the flash memory option (examples/fingerprint_simpletest_rpi.py).

Thank you.

template_compare fails on PID4750

I tried the fingerprint_template_file compare on one of the new fingerprint sensors https://www.adafruit.com/product/4750 and it fails with this result. I have not looked into it yet and don't have a datasheet for this sensor :-(

The "simpletest" works ok.

INFO: Sensor les not support LED. Error: Failed to read data from sensor
----------------
Fingerprint templates:  [1, 2]
Number of templates found:  2
Traceback (most recent call last):
  File "fingerprint_test.py", line 179, in <module>
    if finger.read_sysparam() != adafruit_fingerprint.OK:
  File "/home/pi/projects/fingerprint/adafruit_fingerprint.py", line 147, in read_sysparam
    r = self._get_packet(28)
  File "/home/pi/projects/fingerprint/adafruit_fingerprint.py", line 342, in _get_packet
    raise RuntimeError("Failed to read data from sensor")
RuntimeError: Failed to read data from sensor
# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
# SPDX-License-Identifier: MIT

"""
`fingerprint_template_file_compare.py`
====================================================

This is an example program to demo storing fingerprint templates in a file. It also allows
comparing a newly obtained print with one stored in the file in previous step. This is helpful
when fingerprint templates are stored centrally (not on sensor's flash memory) and shared
between multiple sensors.

* Author(s): admiralmaggie

Implementation Notes
--------------------

**Hardware:**

* `Fingerprint sensor <https://www.adafruit.com/product/751>`_ (Product ID: 751)
* `Panel Mount Fingerprint sensor <https://www.adafruit.com/product/4651>`_ (Product ID: 4651)
"""


import serial
import adafruit_fingerprint


# import board (if you are using a micropython board)
# uart = busio.UART(board.TX, board.RX, baudrate=57600)

# If using with a computer such as Linux/RaspberryPi, Mac, Windows with USB/serial converter:
uart = serial.Serial("/dev/ttyUSB0", baudrate=115200, timeout=1)

# If using with Linux/Raspberry Pi and hardware UART:
# uart = serial.Serial("/dev/ttyS0", baudrate=57600, timeout=1)

# If using with Linux/Raspberry Pi 3 with pi3-disable-bte
# uart = serial.Serial("/dev/ttyAMA0", baudrate=57600, timeout=1)

finger = adafruit_fingerprint.Adafruit_Fingerprint(uart)

##################################################


def sensor_reset():
    """Reset sensor"""
    print("Resetting sensor...")
    if finger.soft_reset() != adafruit_fingerprint.OK:
        print("Unable to reset sensor!")
    print("Sensor is reset.")


# pylint: disable=too-many-branches
def fingerprint_check_file():
    """Compares a new fingerprint template to an existing template stored in a file
    This is useful when templates are stored centrally (i.e. in a database)"""
    print("Waiting for finger print...")
    set_led_local(color=3, mode=1)
    while finger.get_image() != adafruit_fingerprint.OK:
        pass
    print("Templating...")
    if finger.image_2_tz(1) != adafruit_fingerprint.OK:
        return False

    print("Loading file template...", end="", flush=True)
    with open("template0.dat", "rb") as file:
        data = file.read()
    finger.send_fpdata(list(data), "char", 2)

    i = finger.compare_templates()
    if i == adafruit_fingerprint.OK:
        set_led_local(color=2, speed=150, mode=6)
        print("Fingerprint match template in file.")
        return True
    if i == adafruit_fingerprint.NOMATCH:
        set_led_local(color=1, mode=2, speed=20, cycles=10)
        print("Templates do not match!")
    else:
        print("Other error!")
    return False


# pylint: disable=too-many-statements
def enroll_save_to_file():
    """Take a 2 finger images and template it, then store it in a file"""
    set_led_local(color=3, mode=1)
    for fingerimg in range(1, 3):
        if fingerimg == 1:
            print("Place finger on sensor...", end="", flush=True)
        else:
            print("Place same finger again...", end="", flush=True)

        while True:
            i = finger.get_image()
            if i == adafruit_fingerprint.OK:
                print("Image taken")
                break
            if i == adafruit_fingerprint.NOFINGER:
                print(".", end="", flush=True)
            elif i == adafruit_fingerprint.IMAGEFAIL:
                set_led_local(color=1, mode=2, speed=20, cycles=10)
                print("Imaging error")
                return False
            else:
                set_led_local(color=1, mode=2, speed=20, cycles=10)
                print("Other error")
                return False

        print("Templating...", end="", flush=True)
        i = finger.image_2_tz(fingerimg)
        if i == adafruit_fingerprint.OK:
            print("Templated")
        else:
            if i == adafruit_fingerprint.IMAGEMESS:
                set_led_local(color=1, mode=2, speed=20, cycles=10)
                print("Image too messy")
            elif i == adafruit_fingerprint.FEATUREFAIL:
                set_led_local(color=1, mode=2, speed=20, cycles=10)
                print("Could not identify features")
            elif i == adafruit_fingerprint.INVALIDIMAGE:
                set_led_local(color=1, mode=2, speed=20, cycles=10)
                print("Image invalid")
            else:
                set_led_local(color=1, mode=2, speed=20, cycles=10)
                print("Other error")
            return False

        if fingerimg == 1:
            print("Remove finger")
            while i != adafruit_fingerprint.NOFINGER:
                i = finger.get_image()

    print("Creating model...", end="", flush=True)
    i = finger.create_model()
    if i == adafruit_fingerprint.OK:
        print("Created")
    else:
        if i == adafruit_fingerprint.ENROLLMISMATCH:
            set_led_local(color=1, mode=2, speed=20, cycles=10)
            print("Prints did not match")
        else:
            set_led_local(color=1, mode=2, speed=20, cycles=10)
            print("Other error")
        return False

    print("Downloading template...")
    data = finger.get_fpdata("char", 1)
    with open("template0.dat", "wb") as file:
        file.write(bytearray(data))
    set_led_local(color=2, speed=150, mode=6)
    print("Template is saved in template0.dat file.")

    return True


# pylint: disable=broad-except
def set_led_local(color=1, mode=3, speed=0x80, cycles=0):
    """this is to make sure LED doesn't interfer with example
    running on models without LED support - needs testing"""
    try:
        finger.set_led(color, mode, speed, cycles)
    except Exception as exc:
        print("INFO: Sensor les not support LED. Error:", str(exc))


set_led_local(color=3, mode=2, speed=10, cycles=10)

while True:
    print("----------------")
    if finger.read_templates() != adafruit_fingerprint.OK:
        raise RuntimeError("Failed to read templates")
    print("Fingerprint templates: ", finger.templates)
    if finger.count_templates() != adafruit_fingerprint.OK:
        raise RuntimeError("Failed to read templates")
    print("Number of templates found: ", finger.template_count)
    if finger.set_sysparam(6, 2) != adafruit_fingerprint.OK:
        raise RuntimeError("Unable to set package size to 128!")
    if finger.read_sysparam() != adafruit_fingerprint.OK:
        raise RuntimeError("Failed to get system parameters")
    print("Package size (x128):", finger.data_packet_size)
    print("Size of template library: ", finger.library_size)
    print("e) enroll print and save to file")
    print("c) compare print to file")
    print("r) soft reset")
    print("x) quit")
    print("----------------")
    c = input("> ")

    if c in ("x", "q"):
        print("Exiting fingerprint example program")
        # turn off LED
        set_led_local(mode=4)
        raise SystemExit
    if c == "e":
        enroll_save_to_file()
    elif c == "c":
        fingerprint_check_file()
    elif c == "r":
        sensor_reset()
    else:
        print("Invalid choice: Try again")

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.