Elaine WuDmitry Maslov
Published

Fingerprints authentication and collect attendance

Build a Raspberry Pi-powered system to identify attendance and use pandas to collect data that can help attendace management.

IntermediateFull instructions provided2,543
Fingerprints authentication and collect attendance

Things used in this project

Story

Read more

Schematics

Grove PIR Motion Sensor and Grove LED to Grove Base HAT and Raspberry Pi

Code

fingerprint_sensor.py

Python
import time
import serial
import adafruit_fingerprint
import time
import pandas as pd 
from datetime import datetime

uart = serial.Serial("/dev/ttyUSB0", baudrate=57600, timeout=1)
finger = adafruit_fingerprint.Adafruit_Fingerprint(uart)
dates = []

def get_fingerprint():
    """Get a finger print image, template it, and see if it matches!"""
    print("Waiting for image...")
    while finger.get_image() != adafruit_fingerprint.OK:
        pass
    print("Templating...")
    if finger.image_2_tz(1) != adafruit_fingerprint.OK:
        return False
    print("Searching...")
    if finger.finger_search() != adafruit_fingerprint.OK:
        return False
    return True

def get_num(max_number):
    """Use input() to get a valid number from 0 to the maximum size
    of the library. Retry till success!"""
    i = -1
    while (i > max_number - 1) or (i < 0):
        try:
            i = int(input("Enter ID # from 0-{}: ".format(max_number - 1)))
        except ValueError:
            pass
    return i

dates = []
ids = []

try:
    while get_fingerprint():
        time.sleep(.05)

    dates.append(time.asctime(time.localtime(time.time())))
    ids.append(finger.finger_id)
    print(dates, ids)
    dict = {'id': ids, 'datetime': dates}
    df = pd.DataFrame(dict)
    df.to_csv('file1.csv')
except KeyboardInterrupt:        
    
    df.to_csv('file1.csv')

led_motion_sensor.py

Python
import RPi.GPIO as GPIO
import time
import threading

class MotionSensor:

    def __init__(self, pin = 12):

        self.pin = pin
        GPIO.setup(self.pin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

    def is_activated(self):

        res = False
        if GPIO.input(self.pin) == GPIO.HIGH:
            res = True
        return res

class Blinker:

    def __init__(self, pin = 16):
        self.is_active = False
        self.pin = pin
        GPIO.setmode(GPIO.BCM)
        GPIO.setup(self.pin, GPIO.OUT)

    def blink(self, speed = 0.25, duration = 5):

        if not self.is_active:
            self.is_active = True
            print("LED active")
            thread = threading.Thread(target=self.control_led, args=(speed, duration,))
            thread.start()
         
    def control_led(self, speed = 0.25, duration = 5):

        start_time = time.time()

        while (time.time() - start_time) < duration:
            GPIO.output(self.pin, True)
            time.sleep(speed)
            GPIO.output(self.pin, False)
            time.sleep(speed)
        self.is_active = False    

if __name__ == '__main__':

    blinker = Blinker()
    motion_sensor = MotionSensor()

    while True:
        try:
            if motion_sensor.is_activated():
                blinker.blink(1, 5)
        except KeyboardInterrupt:
            GPIO.cleanup()
            break

gpio_helper.py

Python
import RPi.GPIO as GPIO
import time
import threading

class MotionSensor:

    def __init__(self, pin = 27):

        self.pin = pin
        GPIO.setup(self.pin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

    def is_activated(self):

        res = False
        if GPIO.input(self.pin) == GPIO.HIGH:
            res = True
        return res

class Blinker:

    def __init__(self, pin = 17):
        self.is_active = False
        self.pin = pin
        GPIO.setmode(GPIO.BCM)
        GPIO.setup(self.pin, GPIO.OUT)

    def blink(self, speed = 0.25, duration = 5):

        if not self.is_active:
            self.is_active = True
            print("LED active")
            thread = threading.Thread(target=self.control_led, args=(speed, duration,))
            thread.start()
         
    def control_led(self, speed = 0.25, duration = 5):

        start_time = time.time()

        while (time.time() - start_time) < duration:
            GPIO.output(self.pin, True)
            time.sleep(speed)
            GPIO.output(self.pin, False)
            time.sleep(speed)
        self.is_active = False    

if __name__ == '__main__':

    blinker = Blinker()
    motion_sensor = MotionSensor()

    while True:
        try:
            if motion_sensor.is_activated():
                blinker.blink(1, 5)
        except KeyboardInterrupt:
            GPIO.cleanup()
            break

attendance.py

Python
import time
import serial
import adafruit_fingerprint
import pandas as pd 
import sys

from datetime import datetime
from gpio_helper import Blinker, MotionSensor

def get_fingerprint():
    """Get a finger print image, template it, and see if it matches!"""

    print("Waiting for image...")
    start_time = time.time()
    while finger.get_image() != adafruit_fingerprint.OK:
        if time.time() - start_time > 2:
            return False            
    
    print("Templating...")
    if finger.image_2_tz(1) != adafruit_fingerprint.OK:
        return False
    
    print("Searching...")
    if finger.finger_search() != adafruit_fingerprint.OK:
        return False
    return True

def main():
 
    while True:

        while not motion_sensor.is_activated():
            time.sleep(0.05)

        print('Motion detected.')
        tries = 0
        user_input = False
        finger_found = True

        while not get_fingerprint():
            time.sleep(.05)
            tries += 1
            print("Num of tries: ", tries)
            if tries >= 5:
                print("No finger detected")
                blinker.blink(0.1, 3)
                finger_found = False
                break

        if finger_found:      
            date = time.asctime(time.localtime(time.time()))
            id = finger.finger_id            

            dict = {'id': [id], 'datetime': [date]}
            print("Saving data: ", dict)
            blinker.blink(1, 3)    
            df = pd.DataFrame(dict)
            df.to_csv('attendance.csv', mode = 'a', header = False, index=False)
 
if __name__ == '__main__':

    if len(sys.argv) < 3:
        print('Usage: {} led_pin sensor_pin, e.g. python3 attendance.py 17 27'.format(sys.argv[0]))
        sys.exit(1)    

    blinker = Blinker(int(sys.argv[1]))
    motion_sensor = MotionSensor(int(sys.argv[2]))
    uart = serial.Serial("/dev/ttyUSB0", baudrate=57600, timeout=1)
    finger = adafruit_fingerprint.Adafruit_Fingerprint(uart)   

    main()

Credits

Elaine Wu

Elaine Wu

1 project • 0 followers
Dmitry Maslov

Dmitry Maslov

31 projects • 180 followers

Comments