Senin, 13 Maret 2017

Fingerprint + Arduino + Raspberry PI + Camera Raspi

Sebagai berikut adalah contoh dari kode untuk
mendaftarakn data fingerprint via Arduino yang kemudian di arsupkan ke Raspberry PI.

Juga kode untuk memastikan bahwa sidik jari ybs adalah finger yang mana....


Arduino.ino


#include <Adafruit_Fingerprint.h>
#include <SoftwareSerial.h>

char kon;
uint8_t id;
uint8_t getFingerprintEnroll();
String inputString = "";         // a string to hold incoming data
boolean stringComplete = false;  // whether the string is complete

int getFingerprintIDez();
SoftwareSerial mySerial(2, 3);
Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerial);

void setup()  {
  while (!Serial);  // For Yun/Leo/Micro/Zero/...
  delay(500);
 
  Serial.begin(9600);
 // Serial.println("Adafruit Fingerprint sensor enrollment");
  finger.begin(9600);
 
  if (finger.verifyPassword()) {
   // Serial.println("Found fingerprint sensor!");
  } else {
    Serial.println("!Did not find fingerprint sensor :(");
    while (1);
  }
  inputString.reserve(200);
}

uint8_t readnumber(void) {
  uint8_t num = 0;
  boolean validnum = false;
  while (1) {
    while (! Serial.available());
    char c = Serial.read();
    if (isdigit(c)) {
       num *= 10;
       num += c - '0';
       validnum = true;
    } else if (validnum) {
      return num;
    }
  }
}

void loop(){
   if (stringComplete) {
    Serial.println(inputString);
    inputString = "";
    stringComplete = false;
  }
}


void serialEvent() {
  while (Serial.available()) {
    char inChar = (char)Serial.read();
    kon=inChar;
    inputString += inChar;
    if(inChar=='S'){
       Serial.println("#Please Tap");
      while (kon=='S'){
        int hrs=getFingerprintIDez();
        if(hrs==214){kon='Y';Serial.println(kon);}
        delay(50);
       }
    }
    else if(inChar=='Z'){
          kon='Z';
     int hrs=0;  
       while (hrs<=0){
        hrs=getFingerprintEnroll();
        if(hrs==101){
        kon='E';
        //Serial.println(kon);
        delay(1000);
      }
        delay(50);
       }
       
        delay(50);
    }
   else if(inChar=='D'){
     kon='D';
     int hrs=0;  
   
       while(hrs <=0 ){
       
         ////
        hrs=hapus();
        if(hrs==112){kon='R';Serial.println(kon);delay(1000);}
        delay(50);
       }
        delay(50);
    }

    else if (inChar == '@') {
      stringComplete = true;
    }
  }
}

//===================================XXXX

uint8_t getFingerprintEnroll() {
    Serial.println("#Input Enroll:");
  //Serial.println("Ready to enroll a fingerprint! Please Type in the ID # you want to save this finger as...");
  id = readnumber();
  //Serial.println(id);
 
  int p = -1;
//  Serial.print("Waiting for valid finger to enroll as"); Serial.println(id);
  while (p != FINGERPRINT_OK) {
    p = finger.getImage();
    switch (p) {
    case FINGERPRINT_OK:
      Serial.println("@Image taken");
      break;
    case FINGERPRINT_NOFINGER:
      Serial.println("@wait");delay(1000);
      break;
    case FINGERPRINT_PACKETRECIEVEERR:
      Serial.println("!Communication error");
      break;
    case FINGERPRINT_IMAGEFAIL:
      Serial.println("!Imaging error");
      break;
    default:
      Serial.println("!Unknown error");
      break;
    }
  }

  // OK success!

  p = finger.image2Tz(1);
  switch (p) {
    case FINGERPRINT_OK:
      Serial.println("@Image converted");
      break;
    case FINGERPRINT_IMAGEMESS:
      Serial.println("!Image too messy");
      return p;
    case FINGERPRINT_PACKETRECIEVEERR:
      Serial.println("!Communication error");
      return p;
    case FINGERPRINT_FEATUREFAIL:
      Serial.println("!Could not find fingerprint features");
      return p;
    case FINGERPRINT_INVALIDIMAGE:
      Serial.println("!Could not find fingerprint features");
      return p;
    default:
      Serial.println("!Unknown error");
      return p;
  }
 
  //Serial.println("#Remove finger");
  delay(2000);
  p = 0;
  while (p != FINGERPRINT_NOFINGER) {
    p = finger.getImage();
  }
  //Serial.print("ID "); Serial.println(id);
  p = -1;
  Serial.println("#Place same finger again");
  while (p != FINGERPRINT_OK) {
    p = finger.getImage();
    switch (p) {
    case FINGERPRINT_OK:
      Serial.println("@Image taken");
      break;
    case FINGERPRINT_NOFINGER:
      Serial.println("@wait");delay(1000);
      break;
    case FINGERPRINT_PACKETRECIEVEERR:
      Serial.println("!Communication error");
      break;
    case FINGERPRINT_IMAGEFAIL:
      Serial.println("!Imaging error");
      break;
    default:
      Serial.println("!Unknown error");
      break;
    }
  }

  // OK success!

  p = finger.image2Tz(2);
  switch (p) {
    case FINGERPRINT_OK:
      Serial.println("@Image converted");
      break;
    case FINGERPRINT_IMAGEMESS:
      Serial.println("!Image too messy");
      return p;
    case FINGERPRINT_PACKETRECIEVEERR:
      Serial.println("!Communication error");
      return p;
    case FINGERPRINT_FEATUREFAIL:
      Serial.println("!Could not find fingerprint features");
      return p;
    case FINGERPRINT_INVALIDIMAGE:
      Serial.println("!Could not find fingerprint features");
      return p;
    default:
      Serial.println("!Unknown error");
      return p;
  }
 
  // OK converted!
//  Serial.print("Creating model for #");  Serial.println(id);
 
  p = finger.createModel();
  if (p == FINGERPRINT_OK) {
    Serial.println("#MATCH");
  } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
    Serial.println("!Communication error");
    return p;
  } else if (p == FINGERPRINT_ENROLLMISMATCH) {
    Serial.println("#Fingerprints did not match");
    return p;
  } else {
    Serial.println("!Unknown error");
    return p;
  }  
 
//  Serial.print("ID "); Serial.println(id);
  p = finger.storeModel(id);
  if (p == FINGERPRINT_OK) {
    Serial.println("#STORED");
    return 101;
  } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
    Serial.println("!Communication error");
    return p;
  } else if (p == FINGERPRINT_BADLOCATION) {
    Serial.println("!Could not store in that location");
    return p;
  } else if (p == FINGERPRINT_FLASHERR) {
    Serial.println("!Error writing to flash");
    return p;
  } else {
    Serial.println("!Unknown error");
    return p;
  }  
}
//XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

// returns -1 if failed, otherwise returns ID #
int getFingerprintIDez() {
 
  uint8_t p = finger.getImage();
  if (p != FINGERPRINT_OK)  return -1;

  p = finger.image2Tz();
  if (p != FINGERPRINT_OK)  return -1;

  p = finger.fingerFastSearch();
  if (p != FINGERPRINT_OK)  return 214;
 
  // found a match!
  Serial.print("#Found#"); Serial.print(finger.fingerID);
  Serial.print("#"); Serial.println(finger.confidence);
  kon='X';
  delay(3000);
  //return finger.fingerID;
  return 212;
}
//XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

int hapus(){
 
  Serial.println("#WHAT ID");

  uint8_t id = readnumber();
//  while (true) {
//    while (! Serial.available());
//    char c = Serial.read();
//    if (! isdigit(c)) break;
//    id *= 10;
//    id += c - '0';
//  }
 
  //Serial.print("#Deleting#");Serial.println(id);
 
 return deleteFingerprint(id);
}

uint8_t deleteFingerprint(uint8_t id) {
  uint8_t p = -1;
 
  p = finger.deleteModel(id);

  if (p == FINGERPRINT_OK) {
    //Serial.println("Deleted!");
    return 112;
  } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
    Serial.println("!Communication error");
    return p;
  } else if (p == FINGERPRINT_BADLOCATION) {
    Serial.println("!Could not delete in that location");
    return p;
  } else if (p == FINGERPRINT_FLASHERR) {
    Serial.println("!Error writing to flash");
    return p;
  } else {
    Serial.print("!Unknown error: 0x"); Serial.println(p, HEX);
    return p;
  }  
}



Python.py

import serial

import MySQLdb
from time import gmtime, strftime
from random import randint
from picamera import PiCamera
from time import sleep

#camera = PiCamera()
#camera.rotation = 180

db = MySQLdb.connect("localhost","root","","db_project")
cursor = db.cursor()

db2 = MySQLdb.connect("localhost","root","","db_project")
cursor2 = db2.cursor()

id=""
ruang="A09"

read_serial0=""
#ser = serial.Serial('/dev/ttyACM0',9600)
ser = serial.Serial('COM8',9600)

def mtrim(s):
    if s.endswith(" "): s = s[:-1]
    if s.startswith(" "): s = s[1:]
    return s

def find_str(s, char):
    index = 0

    if char in s:
        c = char[0]
        for ch in s:
            if ch == c:
                if s[index:index+len(char)] == char:
                    return index

            index += 1

    return -1

def simpanEnroll():
    tgl=strftime("%Y-%m-%d", gmtime())
    jam=strftime("%H:%M:%S", gmtime())
    stgl=strftime("%Y%m%d", gmtime())
    sjam=strftime("%H%M%S", gmtime())
    img=   stgl+sjam+".jpg";

    #camera.framerate = 15
    #camera.start_preview()

    sleep(1)
    #camera.capture('/var/www/html/project/ypathfile/'+img)
    sleep(1)
    #camera.stop_preview()
    sql='INSERT INTO `tb_enroll` (`is`, `namaSiswa`) VALUES ("%s", "%s")' % (id, namaSiswa,'-')
    try:
        cursor.execute(sql)
        db.commit()
    except:
        db.rollback()
         
    try:
        cursor2.execute(sql)
        db2.commit()
    except:
        db2.rollback()
    print("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
            ###################

           
def enroll():
    print("Proses Enroll")

    ser.write("Z")
    ser.flush()
    #sleep(1)
    print("Start")
   
    lop=0
    while lop<1:
        msg = ser.readline()
        if find_str(msg,"#Input Enroll:")>=0:
            id=str(input("Masukan ID Anda!"))
            ser.write(id)
            ser.write('\n')
            ser.flush()
            ser.flush()
            sleep(1)

        elif find_str(msg,"@Image converted")>=0:
            print(msg)
            print("Silakan Lepas Finger Anda Untuk Persiapan Tap Lagi")
            #sleep(1)
       
        elif find_str(msg,"@")>=0:
            print(msg)
           
        elif find_str(msg,"!")>=0:
            print(msg)
            #sleep(1)
            lop=1

        elif find_str(msg,"E")>=0:
            print(msg)
            #sleep(1)
            lop=1
           
        elif find_str(msg,"#Place same finger again")>=0:
            print("Silakan Tap Finger Yang Sama......")
            #sleep(1)
           
        elif find_str(msg,"#MATCH")>=0:
            print("Sidik Jari Benar.. Sesuai......")
           
        elif find_str(msg,"#STORED")>=0:
            print("Sidik Jari Tersimpan.....")
            simpanEnroll()
            #sleep(1)
            lop=1
           
        elif find_str(msg,"#Fingerprints did not match")>=0:
            print("Sidik Jari Tidak Sama.....")
            #sleep(1)
           
        else:
            print(msg)
            #sleep(1)
            lop=1  
   
def search():
    print("Proses Searching")
    ser.flush()
    ser.write("S")
    sleep(1)
   
    lop=0
    while lop<1:
        msg = ser.readline()
        if find_str(msg,"#Please Tap")>=0:
            ser.flush()
            print("Silahkan Tap your Finger")
            sleep(1)
        elif find_str(msg,"Y")>=0:
            print("Maaf Data Tak Dikenal")
            sleep(1)
            lop=1
        elif find_str(msg,"#Found#")>=0:
            ar=msg.split("#")
            print("Dikenal :",ar[2],":Approx:",ar[3])
            sleep(1)
            lop=1
        else:
            print(msg)
            lop=1
           
def remove():
    print("Proses Remove")
    ser.write("D")
    ser.flush()
    sleep(1)

    lop=0
    while lop<1:
        msg = ser.readline()
        if find_str(msg,"#WHAT ID")>=0:
            id=str(input("Masukan ID Yang Akan Dihapus!"))
            ser.write(id)
            ser.write('\n')
            ser.flush()
            ser.flush()
            sleep(1)
           
        elif find_str(msg,"@")>=0:
            print(msg)
           
        elif find_str(msg,"R")>=0:
            print("Hapus Berhasil")
            sleep(1)
            lop=1
           
        elif find_str(msg,"!")>=0:
            print(msg)
            sleep(1)
            lop=1
           
        else:
            print(msg)
            lop=1

def mulai():
   

    print("Silakan Pilih Operasi?")
    print("    1) Enroll")
    print("    2) Stand By")
    print("    3) Remove")
   
 
    pil=int(input(" Pilihan= "))
 
    if pil==1:
       enroll()
    elif pil==2:
       search()
    elif pil==3:
       remove()
    else:
        print("Tidak Ada Dalam Pilihan")

    print("Apakah Anda Ingin Melanjutkan Operasi?")
    print("    1) Lanjut")
    print("    2) Keluar")
    pil=int(input("Pilihan"))
 
    if pil==1:
        mulai()
 
    else:
        print("Terimakasih")
        try:
            ser.close();
            print("Disconnect")
        except:
            print("Terputus.....")

           
       
print("*****************************************")
print("           Aplikasi Fingerprint          ")          
print("*****************************************")
ser.flush()
ser.write("A")
sleep(4)
mulai()


Database:


CREATE TABLE IF NOT EXISTS `tb_history` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `tanggal` date NOT NULL,
  `jam` time NOT NULL,
  `ruang` varchar(3) NOT NULL,
  `ksj` varchar(5) NOT NULL,
  `image` varchar(30) NOT NULL,
  `note` varchar(30) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=15 ;



INSERT INTO `tb_history` (`id`, `tanggal`, `jam`, `ruang`, `ksj`, `image`, `note`) VALUES
(1, '2017-01-12', '16:13:02', '7', '1', 'Chrysanthemum.jpg', '-'),
(2, '2017-01-25', '16:13:32', '', '', 'avatar.jpg', ''),
(3, '2017-01-26', '07:07:42', 'A', '49', '20170126070742.jpg', '-'),
(4, '2017-01-26', '07:08:38', 'A', '87', '20170126070838.jpg', '-'),
(5, '2017-01-26', '07:08:43', 'A', '97', '20170126070843.jpg', '-'),
(6, '2017-01-26', '07:09:56', 'A', '49', '20170126070956.jpg', '-'),
(7, '2017-01-26', '07:10:08', 'A', '87', '20170126071008.jpg', '-'),
(8, '2017-01-26', '07:10:21', 'A', '97', '20170126071021.jpg', '-'),
(9, '2017-01-26', '07:18:51', 'A', '49', '20170126071851.jpg', '1'),
(10, '2017-01-26', '07:19:03', 'A', '87', '20170126071903.jpg', '1'),
(11, '2017-01-26', '07:19:17', 'A', '97', '20170126071917.jpg', '1'),
(12, '2017-01-26', '07:19:26', 'A', '279', '20170126071926.jpg', '1'),
(13, '2017-01-26', '07:21:21', 'A', '49', '20170126072121.jpg', '1'),
(14, '2017-01-26', '08:12:16', 'A', '49', '20170126081216.jpg', '-');

-- --------------------------------------------------------

--
-- Table structure for table `tb_siswa`
--

CREATE TABLE IF NOT EXISTS `tb_siswa` (
  `nis` varchar(10) NOT NULL,
  `nama` varchar(25) NOT NULL,
  `jenis_kelamin` varchar(15) NOT NULL,
  `kelas` varchar(15) NOT NULL,
  `ksj` varchar(5) NOT NULL,
  `username` varchar(25) NOT NULL,
  `password` varchar(25) NOT NULL,
  `hp` varchar(15) NOT NULL,
  PRIMARY KEY (`nis`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;



INSERT INTO `tb_siswa` (`nis`, `nama`, `jenis_kelamin`, `kelas`, `ksj`, `username`, `password`, `hp`) VALUES
('SIS001', 'Ali', 'Laki-Laki', '1', '1', 'Ali', 'ali', '08568452535'),
('SIS002', 'Wati', 'Laki-Laki', '1', '2', 'Wati', 'wati', '08568619797');








1 komentar: