Fingerprints are one of the many unique biometric signatures which we can use to identify people very accurately. But just by holding someone's hand and staring at their fingers can't be practical [grins]; we're not good at it. But computers are good at recognizing and matching patterns very fast and accurately. Before we can process a fingerprint pattern with a computer, we must "capture" it.
There exists many methods to digitize fingerprints; from forensic methods to ultrasound scanning. In this tutorial, we will learn how an Optical Fingerprint Scanner works and how we can interface the R307 fingerprint scanner module to Arduino. R307 is an optical fingerprint scanner module from R30X series produced by a Chinese vendor called Hangzhou Grow Technology Co., Ltd. Other sensors in the series are R300, R301T, R302, R303, R303T, R305, R306, R308, and R311, some of which are capacitive sensors. Despite having different sensing techniques and form-factors, they all share the same interface and command set. Therefore it is easy to adapt the library that you find here for other models as well.
The skin on the palms of our hands have a special pattern called friction ridges that help us grab things effectively without slipping. These patterns consist of ridges and valleys arranged in certain configurations and is unique for each individual. Our finger tips also have them as you can see from the above image. When a finger comes in contact with a surface, the ridges make strong contact with the surface. When we strongly grab something, the moisture, oil, dirt and dead skin cells on our finger can attach to the surface of the material, leaving an impression we call a fingerprint. Various forensic methods involving the use chemicals are used to extract such fingerprints from crime scenes and are called latent fingerprints. But an optical fingerprint scanner works a bit differently.
An optical fingerprint scanner works based on the principle of Total Internal Reflection (TIR). In an optical fingerprint scanner, a glass prism is used to facilitate TIR. Light from an LED (usually blue color) is allowed to enter through one face of the prism at a certain angle for the TIR to occur. The reflected light exits the prism through the other face where a lens and an image sensor (essentially camera) are placed.
When there's no finger on the prism, the light will be completely reflected off from the surface, producing a plain image in the image sensor. When TIR occurs, a small amount of light leaked to the external medium and it is called the Evanescent Wave. Materials with different refractive indexes (RI) interact with the evanescent wave differently. When we touch a glass surface, only the ridges make good contact with it. The valleys remain separated from the surface by air packets. Our skin and air have different RIs and thus affect the evanescent field differently. This effect is called Frustrated Total Internal Reflection (FTIR). This effect alters the intensities of the internally reflected light and is detected by the image sensor (see this image). The image sensor data is processed to produce a high contrast image which will be the digital version of the fingerprint.
In capacitive sensors, which are more accurate and less bulky, there's no light involved. Instead, an array of capacitive sensors are arranged on the surface of the sensor and allowed to come in contact with the finger. The ridges and air packets affect the capacitive sensors differently. The data from the sensor array can be used to generate a digital image of the fingerprint.
Above is a cross-sectional diagram that I made to better understand the construction (illustrative only, not a physically exact one). Opening the module was easy; there are four Philips screws on the back. Unscrew them and you can remove the PCB. There are two PCBs; one arranged horizontally and one vertically (shown in washed green). These PCBs are connected by solder. The four blue LEDs and the touch sense pad are on the horizontal PCB. The vertical PCB has the image sensor, the processor and connector. When inserted, the touch sense pad comes in contact with the glass block above. The image sensor is soldered and glued. Strangely, I couldn't find any lens on it. May be it doesn't need one. The enclosure has an internal barrier to separate the light from the LEDs and the light coming out of the prism. On the bottom side of the prism a black epoxy is coated which gives a high-contrast background for the fingerprint image. To access the prism, just remove the cap on the front.
Pin Number | Name | Type | Description |
1 | +5V | IN | Positive Supply (DC 4.2V-6V) |
2 | GND | GND | Supply Ground |
3 | TXD | OUT | Data output (TTL) |
4 | RXD | IN | Data input (TTL) |
5 | Touch | OUT | Finger detection signal (max output current: 50mA) |
6 | 3.3V | IN | Finger detection power (DC 3.3V-5V ~5uA) |
The scanner can be interfaced and powered from both 3.3V and 5V supplies. The working voltage of the scanner controller is always 3.3V. There's a 3.3V regulator on the PCB. The 5V supply you provide goes to the input of that regulator, and the 3.3V you supply bypasses the regulator and goes directly to the fingerprint scanner controller.
When you want to power the scanner from 5V and interface with a 5V microcontroller, supply the power to the pins 1 and 6, and disconnect the 3.3V jumper shown in the picture. If you want to supply 3.3V and interface the scanner with a 3.3V microcontroller such as Arduino Due, supply the power to pins 1 and 6 and short the 3.3V jumper. Improper voltages and configurations might damage the controller. So be careful with it.
The pin 6 (Touch Sense Power) is the supply voltage for the finger detection circuit. When a finger is present on the scanner, the output of pin 5 (Touch Sense) will be high. This signal can be used to initiate the scanning of the finger manually. Otherwise the scanner will wait for some time to detect the finger.
The R307 has both USB and UART interfaces. With the USB, you can directly connect the scanner to a computer and communicate with it. A virtual COM port will be created when you connect the scanner to a Windows PC. If you want to interface the scanner with a microcontroller, you can use the UART interface which supports baud rates up to 115200 bps.
The main controller on the PCB is AS606 from a company called Synochip. I don't know how Synochip is related to the company Hangzhou Grow. Whatever that is, the AS606 is a microcontroller with Cordis 5+ RISC cores and has everything needed for a performance controller including a DSP. If you want to know more about the controller check out the datasheet and good luck.
The R307 Manual is the only document to our rescue, and it is ambiguous at many places. The R30X Series Manual has some more information. The below schematic is included in the manual.
The schematic is incomplete and full of errors. For example, in the schematic you can see the TOUCH output pin is directly connected to the ground. And there are many such inconsistencies. If you look at the manuals of other modules in the series, the same schematic can be seen included in them. So whomever made the manual was not thinking straight!
When I disassembled the module, I could see there an IC TTP233D from Tontek, which is a touch sense detector. The TOUCH pin is actually connected to the output pin (pin 1) of the IC, which I verified using a multimeter. The resistor R9 is possibly a pull-up. The input pin of the IC is connected to the copper pad on the horizontal PCB. There is some kind of black glue on the side of the glass block between the copper pad. I don't know if that opaque coating has any other functions other than providing a high-contrast background for the fingerprint image. But I assume, when we touch the glass, the change in capacitance detected by the touch sense IC via the copper pad, and a digital output driven at the TOUCH pin. This is in contrast to the schematic the company provided. Somebody skipped their job!
1. Notepad - This is a 512 bytes of the non-volatile flash memory. It is logically divided into 16 pages with 32 bytes each. Instructions GR_WriteNotepad
and GR_ReadNotepad
can be used to access this memory. When writing a page, it is taken as a whole and the contents are replaced.
2. Image Buffer - Image buffer is used to store a BMP image of size 256 x 288, each pixel occupying a byte. This buffer is part of the RAM and the contents are lost when power is lost.
3. Character File Buffer - A character file is a processed high contrast image of a fingerprint. Two character files from two consecutive scans are combined to form a template file which is the final version of the fingerprint that is stored in the fingerprint library (not to be confused with the Arduino library. Fingerprint library is the memory used to store up to 1000 fingerprints). The two character file buffers are CharBuffer1
and CharBuffer2
each with size of 512 bytes.
4. Fingerprint Library - This is a section of the flash memory where 1000 fingerprint templates can be stored. Templates are arranged sequentially with numbering from 0 to N-1 (The manual says 0-N) where N is the capacity of the library determined by the size of the flash memory. There are instructions to store, process and delete templates from this memory. They will be explained later.
5. System Configuration Register - This is a 16-bytes long register bank containing operating parameters and status. Except the device address which takes up 4 bytes, rest of the parameters are 2 bytes (a word
) in length. The command ReadSysPara
can be used to read, and command SetSysPara
can be used to write this register bank.
Name | Description | Offset (word) | Size (word) |
Status Register | Contents of system status register | 0 | 1 |
System Identifier Code | Fixed value: 0x0009 | 1 | 1 |
Library Size | Fingerprint library size | 2 | 1 |
Security Level | Security level (1, 2, 3, 4, 5) | 3 | 1 |
Device Address | 32-bit device address | 4 | 2 |
Data Packet Size | Size code (0, 1, 2, 3) | 6 | 1 |
Baud Multiplier | N (baud = 9600*N bps) | 7 | 1 |
Bit Number | 15-4 | 3 | 2 | 1 | 0 |
Description | Reserved | ImgBufStat | PWD | Pass | Busy |
1
: system is executing commands; 0
: system is free, Pass = 1
: found a matching fingerprint; 0
: fingerprint not found, PWD = 1
: handshaking password verified; 0
: password not verified, ImgBufStatus = 1
: image buffer contains valid image; 0
: image buffer does not have a valid image.
0x0009
for R307.
SetAddr
. The factory programmed address is 0xFFFFFFFF
. There's no methods specified in the manual to reset the address to default, so keep the address safe if you ever change it.
Both UART and USB interfaces use a common serial communication protocol based on a packet format (the manual refers packets as "packages"). All data and commands are to be sent as data packets and all responses from the module will also be packets. So we need to frame data and commands as packets before sending out, and must extract data from response packets. The UART frame format is 10 bit with 1 start bit, 1 stop bit and 8 data bits.
Header (2) | Address (4) | Packet Identifier (1) | Packet Length (2) | Packet Content (Instruction/Data/Parameter) | Checksum (2) |
0xEF01
. It is 2 bytes long and the high byte is always transferred first.0xFFFFFFFF
and can be modified with SetAddr
instruction.0x01
: The packet contains a command.0x02
: Data packet. A data packet must be followed by a command packet or acknowledge packet.0x07
: Acknowledge packet. It is sent by the module in response to a command.0x08
: End of data transfer packet. When we send large volume data such as an image, the data transfer will be terminated by this packet.
In order make the fingerprint scanner work, we must send instructions or commands in the form of packets. Each instruction is simply a 1-byte code that we must include in the packet. The module responds to each instruction with an acknowledgment packet that describes the result and status of command execution. Each instruction has a set of expected response codes found in the ACK packet that are called confirmation codes. Instructions and their byte codes are grouped according to their functions as shown below,
Following is the list of confirmation codes.
0x00
- Command execution complete0x01
- Error when receiving data package0x02
- No finger on the sensor0x03
- Failed to enroll the finger0x04
- Failed to generate character file due to the over-disorderly fingerprint image0x05
- Failed to generate character file due to the over-wet fingerprint image0x06
- Failed to generate character file due to the over-disorderly fingerprint image0x07
- Failed to generate character file due to lack of character point or over-smallness of fingerprint image0x08
- Finger doesn’t match0x09
- Failed to find a matching finger0x0A
- Failed to combine the character files0x0B
- Addressing PageID is beyond the finger library0x0C
- Error when reading template from library or the template is invalid0x0D
- Error when uploading template0x0E
- Module can’t receive the following data packages0x0F
- Error when uploading image0x10
- Failed to delete the template0x11
- Failed to clear finger library0x13
- Wrong password0x15
- Failed to generate the image0x18
- Error when writing flash0x19
- No definition error0x21
- Password not verified0x1A
- Invalid register number0x1B
- Incorrect configuration of register0x1C
- Wrong notepad page number0x1D
- Failed to operate the communication port0x41
- No finger on sensor when add fingerprint on second time0x42
- Failed to enroll the finger for second fingerprint scan0x43
- Failed to generate character file due to lack of character point or over-smallness of fingerprint image for second fingerprint scan
0x44
- Failed to generate character file due to the over-disorderly fingerprint image for second fingerprint scan0x45
- Duplicate fingerprint0x21
is not listed in the manual but I found when working with the module. It will be sent when we try to execute commands without verifying the password first.
VfyPwd
instruction and its corresponding packet for an example.
2 bytes | 4 bytes | 1 byte | 2 bytes | 1 byte | 4 bytes | 2 bytes |
Header | Address | Packet Identifier | Packet Length | Instruction Code | Data (Password) | Checksum |
0xEF01 |
0xFFFFFFFF |
0x01 |
0x07 |
0x13 |
0x6F6F6F6F |
0x01D7 |
Above is the packet format for verifying password. Address is assumed to be default. We're sending out a command, and so the Packet Identifier has to be 0x07
. The Packet Length will be always 7 for this instruction. The Packet Content is split into Instruction Code and Password. Password is 0x6F6F6F6F
for our example. If we calculate the Checksum of the bytes, it will be 0x01D7
which is two bytes long.
If the address and password are correct and the packet is correctly formatted, the module will respond with the following acknowledgment packet,
2 bytes | 4 bytes | 1 byte | 2 bytes | 1 byte | 2 bytes |
Header | Address | Packet Identifier | Packet Length | Confirmation Code | Checksum |
0xEF01 |
0xFFFFFFFF |
0x01 |
0x03 |
0x00 |
0x04 |
The confirmation code will be 0x00
if our password was correct and 0x13
if it was not.
A Windows application is available to test products in the R30X series. You would find two versions of it if you search online. One is called SFG Demo and the other is SYNO Demo. The latter one found to be better, so I will be demoing that here. You can download both versions in the downloads section.
You can either connect the module directly to the computer via USB or through a USB-UART converter module. In both cases, a virtual COM port will be established in Windows. Then open the SYNO Demo software and use the Open Device button to choose the COM port. You could encounter an issue here. Instead of fetching the list of active COM ports from the OS, the application has a set of predefined COM port numbers. This is from 1-16 in the SYNO Demo software. So if the COM port assigned to your fingerprint module or the USB-UART module is greater than 16, you won't be able to connect. In that case, go to Device Manager and change the COM port number for your module. If an active device was found, its details will be shown in the hardware information window with a success message.
You will come across many inconsistencies and typos while using the software. But that is to be expected when the Chinese make English versions of their applications and manuals. Other features of the application are straightforward. A more detailed tutorial on the application can be found here, though for a different version of the module.
The most widely used library for the R30X series modules is the Adafruit Fingerprint Sensor library. It was released 7 years ago, it is hard to understand due to lack of documentation and has limited features. That's when I decided to write one myself. Writing libraries is like an exercise for me.
Since the instruction set and confirmation codes are compatible with many versions of the fingerprint scanner, you could easily modify my library to interface a different type. The code is easy to understand and is shared as an open source project. The library is not complete yet. Many functions are still need to be implemented. But the basic enrolling, searching and matching functions work. All that is working are demonstrated in the example Arduino sketch.
The library consists of a header file R30X_Fingerprint.h and a CPP file R30X_Fingerprint.cpp. The header file will give an overview of the library and it includes all instructions codes, default values, class declarations, parameters and functions declarations.
Since the module uses UART to communicate, you have the choice of choosing serial port you want. With boards like Arduino Uno with single UART, you can use the SoftwareSerial for interfacing the fingerprint module and hardware serial for debugging. Debugging is optional. Currently SoftwareSerial is used for AVR and ESP8266 boards. So when initializing, you must create a SoftwareSerial object and send it to the constructor function. I tested the module with Arduino Due and used the hardware serial.
1. Arduino.h
2. SoftwareSerial.h
FPS_DEBUG
is a macro to enable or disable the display of debug information. Comment out the line if you do not want debug information to be printed. The serial port to which the debug info is sent is set by the debugPort
macro. The default one is Serial
, the first serial port on the board.
//-------------------------------------------------------------------------//
//Confirmation codes fingerprint scanner
#define FPS_RESP_OK 0x00U //command executed successfully
#define FPS_RESP_RECIEVEERR 0x01U //packet receive error
#define FPS_RESP_NOFINGER 0x02U //no finger detected
#define FPS_RESP_ENROLLFAIL 0x03U //failed to enroll the finger
#define FPS_RESP_OVERDISORDERFAIL 0x04U //failed to generate character file due to over-disorderly fingerprint image
#define FPS_RESP_OVERWETFAIL 0x05U //failed to generate character file due to over-wet fingerprint image
#define FPS_RESP_OVERDISORDERFAIL2 0x06U //failed to generate character file due to over-disorderly fingerprint image
#define FPS_RESP_FEATUREFAIL 0x07U //failed to generate character file due to over-wet fingerprint image
#define FPS_RESP_DONOTMATCH 0x08U //fingers do not match
#define FPS_RESP_NOTFOUND 0x09U //no valid match found
#define FPS_RESP_ENROLLMISMATCH 0x0AU //failed to combine character files (two character files (images) are used to create a template)
#define FPS_RESP_BADLOCATION 0x0BU //addressing PageID is beyond the finger library
#define FPS_RESP_INVALIDTEMPLATE 0x0CU //error when reading template from library or the template is invalid
#define FPS_RESP_TEMPLATEUPLOADFAIL 0x0DU //error when uploading template
#define FPS_RESP_PACKETACCEPTFAIL 0x0EU //module can not accept more packets
#define FPS_RESP_IMAGEUPLOADFAIL 0x0FU //error when uploading image
#define FPS_RESP_TEMPLATEDELETEFAIL 0x10U //error when deleting template
#define FPS_RESP_DBCLEARFAIL 0x11U //failed to clear fingerprint library
#define FPS_RESP_WRONGPASSOWRD 0x13U //wrong password
#define FPS_RESP_IMAGEGENERATEFAIL 0x15U //fail to generate the image due to lackness of valid primary image
#define FPS_RESP_FLASHWRITEERR 0x18U //error when writing flash
#define FPS_RESP_NODEFINITIONERR 0x19U //no definition error
#define FPS_RESP_INVALIDREG 0x1AU //invalid register number
#define FPS_RESP_INCORRECTCONFIG 0x1BU //incorrect configuration of register
#define FPS_RESP_WRONGNOTEPADPAGE 0x1CU //wrong notepad page number
#define FPS_RESP_COMPORTERR 0x1DU //failed to operate the communication port
#define FPS_RESP_INVALIDREG 0x1AU //invalid register number
#define FPS_RESP_SECONDSCANNOFINGER 0x41U //secondary fingerprint scan failed due to no finger
#define FPS_RESP_SECONDENROLLFAIL 0x42U //failed to enroll second fingerprint
#define FPS_RESP_SECONDFEATUREFAIL 0x43U //failed to generate character file due to lack of enough features
#define FPS_RESP_SECONDOVERDISORDERFAIL 0x44U //failed to generate character file due to over-disorderliness
#define FPS_RESP_DUPLICATEFINGERPRINT 0x45U //duplicate fingerprint
//-------------------------------------------------------------------------//
//Received packet verification status codes from host device
#define FPS_RX_OK 0x00U //when the response is correct
#define FPS_RX_BADPACKET 0x01U //if the packet received from FPS is badly formatted
#define FPS_RX_WRONG_RESPONSE 0x02U //unexpected response
#define FPS_RX_TIMEOUT 0x03U //when no response was received
//-------------------------------------------------------------------------//
//Packet IDs
#define FPS_ID_STARTCODE 0xEF01U
#define FPS_ID_STARTCODEHIGH 0xEFU
#define FPS_ID_STARTCODELOW 0x01U
#define FPS_ID_COMMANDPACKET 0x01U
#define FPS_ID_DATAPACKET 0x02U
#define FPS_ID_ACKPACKET 0x07U
#define FPS_ID_ENDDATAPACKET 0x08U
//-------------------------------------------------------------------------//
//Command codes
#define FPS_CMD_GENIMAGE 0x01U //collect finger image
#define FPS_CMD_IMAGE2TZ 0x02U //generate char file from image
#define FPS_CMD_MATCHTEMPLATES 0x03U //match two fingerprints precisely
#define FPS_CMD_SEARCHLIBRARY 0x04U //search the fingerprint library
#define FPS_CMD_REGMODEL 0x05U //combine character files and generate template
#define FPS_CMD_STORETEMPLATE 0x06U //store template
#define FPS_CMD_LOADTEMPLATE 0x07U //read/load template
#define FPS_CMD_UPLOADTEMPLATE 0x08U //upload template
#define FPS_CMD_DOWNLOADTEMPLATE 0x09U //download template
#define FPS_CMD_DOWNLOADIMAGE 0x0AU //upload image
#define FPS_CMD_UPLOADIMAGE 0x0BU //upload image to the sensor
#define FPS_CMD_DELETETEMPLATE 0x0CU //delete template
#define FPS_CMD_CLEARLIBRARY 0x0DU //clear fingerprint library
#define FPS_CMD_SETSYSPARA 0x0EU //set system configuration register
#define FPS_CMD_READSYSPARA 0x0FU //read system configuration register
#define FPS_CMD_SETPASSWORD 0x12U //set device password
#define FPS_CMD_VERIFYPASSWORD 0x13U //verify device password
#define FPS_CMD_GETRANDOMCODE 0x14U //get random code from device
#define FPS_CMD_SETDEVICEADDRESS 0x15U //set 4 byte device address
#define FPS_CMD_PORTCONTROL 0x17U //enable or disable comm port
#define FPS_CMD_WRITENOTEPAD 0x18U //write to device notepad
#define FPS_CMD_READNOTEPAD 0x19U //read from device notepad
#define FPS_CMD_HISPEEDSEARCH 0x1BU //highspeed search of fingerprint
#define FPS_CMD_TEMPLATECOUNT 0x1DU //read total template count
#define FPS_CMD_GETANDRANGESEARCH 0x32U //read total template count
#define FPS_CMD_GETANDFULLSEARCH 0x34U //read total template count
#define FPS_DEFAULT_TIMEOUT 2000 //UART reading timeout in milliseconds
#define FPS_DEFAULT_BAUDRATE 57600 //9600*6
#define FPS_DEFAULT_RX_DATA_LENGTH 64 //the max length of data in a received packet
#define FPS_DEFAULT_SECURITY_LEVEL 3 //the threshold at which the fingerprints will be matched
#define FPS_DEFAULT_SERIAL_BUFFER_LENGTH 300 //length of the buffer used to read the serial data
#define FPS_DEFAULT_PASSWORD 0xFFFFFFFF
#define FPS_DEFAULT_ADDRESS 0xFFFFFFFF
#define FPS_BAD_VALUE 0x1FU //some bad value or parameter was delivered
#define FPS_DEBUG //uncomment this line to enable debug info to be printed
#define debugPort Serial //select the hardware serial port for debugging
1. R30X_Fingerprint
devicePasswordL
which is a 32-bit value, and devicePassword[4]
which is an array of four 8-bit values. This is just done for convenience, and must not confuse you. When a packet is created and extracted, different set of variables are used, prefixed by rx
and tx
. Some values are variable in length and therefore pointers are used, example *txDataBuffer
. mySerial
is a pointer to a Stream
object which is used to communicate with different interfaces. swSerial
is a pointer only used for SoftwareSerial
interface and hwSerial
is only used for HardwareSerial
interface. They will be conditionally included by the compiler depending on the platform you're compiling for.
private:
//common parameters
uint32_t devicePasswordL; //32-bit single value version of password (L = long)
uint32_t deviceAddressL; //module's address
uint16_t startCodeL; //packet start marker
uint8_t devicePassword[4]; //array version of password
uint8_t deviceAddress[4]; //device address as an array
uint8_t startCode[2]; //packet start marker
uint32_t deviceBaudrate; //UART speed
uint8_t securityLevel; //threshold level for fingerprint matching
uint16_t dataPacketLength; //the max length of data in packet. can be 32, 64, 128 or 256
//transmit packet parameters
uint8_t txPacketType; //type of packet
uint16_t txPacketLengthL; //length of packet (Data + Checksum)
uint8_t txInstructionCode; //instruction to be sent to FPS
uint16_t txPacketChecksumL; //checksum long value
uint8_t txPacketLength[2]; //packet length as an array
uint8_t *txDataBuffer; //packet data buffer
uint16_t txDataBufferLength; //length of actual data in a packet
uint8_t txPacketChecksum[2]; //packet checksum as an array
//receive packet parameters
uint8_t rxPacketType; //type of packet
uint16_t rxPacketLengthL; //packet length long
uint8_t rxConfirmationCode; //the return codes from the FPS
uint16_t rxPacketChecksumL; //packet checksum long
uint8_t rxPacketLength[2]; //packet length as an array
uint8_t *rxDataBuffer; //packet data buffer
uint32_t rxDataBufferLength; //the length of the data only. this doesn't include instruction or confirmation code
uint8_t rxPacketChecksum[2]; //packet checksum as array
uint16_t fingerId; //location of fingerprint in the library
uint16_t matchScore; //the match score of comparison of two fingerprints
uint16_t templateCount; //total number of fingerprint templates in the library
uint16_t statusRegister; //contents of the FPS status register
private:
Stream *mySerial; //stream class is used to facilitate communication
SoftwareSerial *swSerial; //for those devices with only one hardware UART
HardwareSerial *hwSerial; //for those devices with multiple hardware UARTs
Not all of these functions are fully implemented. All that working are demonstrated in the example Arduino sketch.
R30X_Fingerprint (HardwareSerial *hs, uint32_t password = FPS_DEFAULT_PASSWORD, uint32_t address = FPS_DEFAULT_ADDRESS); //constructor for hardware serial
R30X_Fingerprint (SoftwareSerial *ss, uint32_t password = FPS_DEFAULT_PASSWORD, uint32_t address = FPS_DEFAULT_ADDRESS); //constructor for software serial
void begin (uint32_t baud); //initializes the communication port
void resetParameters (void); //initialize and reset and all parameters
uint8_t verifyPassword (uint32_t password = FPS_DEFAULT_PASSWORD); //verify the user supplied password
uint8_t setPassword (uint32_t password); //set FPS password
uint8_t setAddress (uint32_t address = FPS_DEFAULT_ADDRESS); //set FPS address
uint8_t setBaudrate (uint32_t baud); //set UART baudrate, default is 57000
uint8_t setSecurityLevel (uint8_t level); //set the threshold for fingerprint matching
uint8_t setDataLength (uint16_t length); //set the max length of data in a packet
uint8_t portControl (uint8_t value); //turn the comm port on or off
uint8_t sendPacket (uint8_t type, uint8_t command, uint8_t* data = NULL, uint16_t dataLength = 0); //assemble and send packets to FPS
uint8_t receivePacket (uint32_t timeout=FPS_DEFAULT_TIMEOUT); //receive packet from FPS
uint8_t readSysPara (void); //read FPS system configuration
uint8_t captureAndRangeSearch (uint16_t captureTimeout, uint16_t startId, uint16_t count); //scan a finger and search a range of locations
uint8_t captureAndFullSearch (void); //scan a finger and search the entire library
uint8_t generateImage (void); //scan a finger, generate an image and store it in the buffer
uint8_t downloadImage (void); //download image from sensor
uint8_t uploadImage (uint8_t* dataBuffer); //upload image to sensor
uint8_t generateCharacter (uint8_t bufferId); //generate character file from image
uint8_t generateTemplate (void); //combine the two character files and generate a single template
uint8_t downloadCharacter (uint8_t bufferId); //download character file stored in one of the two buffers
uint8_t uploadCharacter (uint8_t bufferId, uint8_t* dataBuffer); //upload character files to one of the two buffers
uint8_t saveTemplate (uint8_t bufferId, uint16_t location); //store the template in the buffer to a location in the library
uint8_t loadTemplate (uint8_t bufferId, uint16_t location); //load a template from library to one of the buffers
uint8_t deleteTemplate (uint16_t startLocation, uint16_t count); //delete a set of templates from library
uint8_t clearLibrary (void); //delete all templates from library
uint8_t matchTemplates (void); //match the templates stored in the two character buffers
uint8_t searchLibrary (uint8_t bufferId, uint16_t startLocation, uint16_t count); //search the library for a template stored in the buffer
uint8_t getTemplateCount (void); //get the total no. of templates in the library
1. R30X_Fingerprint (HardwareSerial *hs, uint32_t password = FPS_DEFAULT_PASSWORD, uint32_t address = FPS_DEFAULT_ADDRESS);
2. R30X_Fingerprint (SoftwareSerial *ss, uint32_t password = FPS_DEFAULT_PASSWORD, uint32_t address = FPS_DEFAULT_ADDRESS);
3. void begin (uint32_t baud);
4. void resetParameters (void);
5. uint8_t verifyPassword (uint32_t password = FPS_DEFAULT_PASSWORD);
0x21
error code. If you want to test for the default password, pass nothing. Otherwise send your custom password. Returns the confirmation code.
6. uint8_t setPassword (uint32_t password);
7. uint8_t setAddress (uint32_t address = FPS_DEFAULT_ADDRESS);
8. uint8_t setBaudrate (uint32_t baud);
9. uint8_t setSecurityLevel (uint8_t level);
10. uint8_t setDataLength (uint16_t length);
11. uint8_t portControl (uint8_t value);
12. uint8_t sendPacket (uint8_t type, uint8_t command, uint8_t* data = NULL, uint16_t dataLength = 0);
data
and dataLength
parameters empty. If you enable debugging, the packet will be printed to the debug port. Returns the confirmation code.
13. uint8_t receivePacket (uint32_t timeout=FPS_DEFAULT_TIMEOUT);
FPS_DEFAULT_TIMEOUT
will be used which is 2 seconds. Returns the confirmation code.
14. uint8_t readSysPara (void);
15. uint8_t captureAndRangeSearch (uint16_t captureTimeout, uint16_t startId, uint16_t count);
fingerId
and matchScore
. Returns the confirmation code.
16. uint8_t captureAndFullSearch (void);
captureAndRangeSearch()
and use the entire range for searching. If the operation was successful, the results are stored in fingerId
and matchScore
. Returns the confirmation code.
17. uint8_t generateImage (void);
18. uint8_t downloadImage (void);
19. uint8_t generateCharacter (uint8_t bufferId);
20. uint8_t generateTemplate (void);
CharBuffer1
. Returns the confirmation code.
21. uint8_t downloadCharacter (uint8_t bufferId);
22. uint8_t uploadCharacter (uint8_t bufferId, uint8_t* dataBuffer);
23. uint8_t saveTemplate (uint8_t bufferId, uint16_t location);
24. uint8_t loadTemplate (uint8_t bufferId, uint16_t location);
25. uint8_t deleteTemplate (uint16_t startLocation, uint16_t count);
26. uint8_t clearLibrary (void);
27. uint8_t matchTemplates (void);
matchScore
variable. Returns the confirmation code.
28. uint8_t searchLibrary (uint8_t bufferId, uint16_t startLocation, uint16_t count);
fingerId
and matchScore
. Returns the confirmation code.
29. uint8_t getTemplateCount (void);
templateCount
. Returns the confirmation code.
I wrote this code for Arduino Due which has 4 hardware serial ports. I'm using first serial port Serial
for debugging and Serial1
for fingerprint scanner interface. I'm using the default password and address of 0xFFFFFFFF
. Three of these parameters are passed to the constructor. You must use the password and address of your module if it was ever changed.
In the setup()
function, we first initialize the debugging port and the fingerprint module. fps
is the object we're using. Then we have to verify the password before doing anything else. Otherwise the scanner will refuse to execute our commands. Optionally you may set a new address, or verify the existing address.
In the loop()
function, we periodically check the serial port for incoming data. When data is available, it is read as a string and it is checked for valid commands and parameters. If it's a valid command, rest of the parameters are extracted from the string in order as firstParam
, secondParam
and thirdParam
. Then the parameters are sent to corresponding function to execute. Once the command is executed, the results are stored in the variables and we wait for new instructions. Following is the list of the available commands.
clrlib
- clear librarytmpcnt
- get templates countreadsys
- read system parameterssetdatlen <data length>
- set data lengthcapranser <timeout> <start location> <quantity>
- capture and range search library for fingerprintcapfulser
- capture and full search the library for fingerprintenroll <location>
- enroll new fingerprintverpwd <password>
- verify 4 byte device passwordsetpwd <password>
- set new 4 byte device passwordsetaddr <address>
- set new 4 byte device addresssetbaud <baudrate>
- set the baudratesetseclvl <level>
- set security levelgenimg
- generate imagegenchar <buffer id>
- generate character file from imagegentmp
- generate template from character bufferssavtmp <buffer id> <location>
- save template to library from bufferlodtmp <buffer id> <location>
- load template from library to bufferdeltmp <start location> <quantity>
- delete one or more templates from librarymattmp
- precisely match two templates available on buffersserlib <buffer id> <start location> <quantity>
- search library for content on the bufferenrollFinger()
function implements the fingerprint enrolling process.
//=========================================================================// | |
// // | |
// ## R30X Fingerprint Sensor Library Example 1 ## // | |
// // | |
// Filename : R30X_Fingerprint_Test.ino // | |
// Description : Arduino compatible test program for Fingerprint_VMA // | |
// library for R30X series fingerprint sensors. // | |
// Library version : 1.0.1 // | |
// Author : Vishnu M Aiea // | |
// Src : https://github.com/vishnumaiea/R30X-Fingerprint-Sensor-Library // | |
// Author's website : https://www.vishnumaiea.in // | |
// Initial release : IST 07:35 PM, 08-04-2019, Monday // | |
// License : MIT // | |
// // | |
// Last modified : IST 11:44 PM, 08-04-2019, Monday // | |
// // | |
//=========================================================================// | |
#include "R30X_Fingerprint.h" | |
//=========================================================================// | |
//initialize the object with the correct password and address | |
//if you want to use the deafault values, pass nothing | |
//Serial1 is availabel only for Due and Mega. Pass SoftwareSerial object for Uno etc | |
R30X_Fingerprint fps = R30X_Fingerprint (&Serial1, 0xFFFFFFFF, 0xFFFFFFFF); //custom password and address | |
// R30X_Fingerprint fps = R30X_Fingerprint (&Serial1); //use deafault password and address | |
//========================================================================// | |
//this implements the fingerprint enrolling process | |
//simply send the location of where you want to save the new fingerprint. | |
//the location can be from #1 to #1000 | |
//the library location actually starts at 0, but I have made it to 1 to avoid confusion | |
//therefore a 1 will be substracted from your location automatically | |
//The finger needs to be scanend twice at steps #1 and #2 | |
uint8_t enrollFinger(uint16_t location) { | |
//enroll new fingerprint | |
debugPort.println("========================="); | |
debugPort.println("Enrolling New Fingerprint"); | |
debugPort.println("========================="); | |
if((location > 1000) || (location < 1)) { //if not in range (1-1000) | |
debugPort.println(); | |
debugPort.println("Enrolling failed."); | |
debugPort.println("Bad location."); | |
debugPort.print("location = #"); | |
debugPort.println(location); | |
debugPort.println("Please try again."); | |
return 1; | |
} | |
delay(4000); | |
debugPort.println(); | |
debugPort.println("Scan #1: Please put your finger on the sensor."); | |
debugPort.println(); | |
delay(5000); | |
uint8_t response = fps.generateImage(); //scan the finger | |
if(response != 0) { | |
debugPort.println("Scan #1: ERROR - Scanning failed. Please try again."); | |
} | |
else { | |
debugPort.println("Scan #1: Scanning success."); | |
debugPort.println(); | |
delay(2000); | |
response = fps.generateCharacter(1); //generate the character file from image and save to buffer 1 | |
if(response != 0) { | |
debugPort.println("Scan #1: ERROR - Template generation failed. Please try again."); | |
} | |
else { | |
debugPort.println(); | |
debugPort.println("Scan #1: Template generation success."); | |
delay(2000); | |
debugPort.println("Scan #2: Please put your finger on the sensor."); | |
delay(5000); | |
debugPort.println(); | |
response = fps.generateImage(); //scan the finger for second time | |
if(response != 0) { | |
debugPort.println("Scan #2: ERROR - Scanning failed. Please try again."); | |
} | |
else { | |
debugPort.println(); | |
debugPort.println("Scan #2: Scanning success."); | |
delay(2000); | |
response = fps.generateCharacter(2); //generate the character file from image and save to buffer 2 | |
if(response != 0) { | |
debugPort.println("Scan #2: Template generation failed. Please try again."); | |
} | |
else { | |
debugPort.println(); | |
response = fps.generateTemplate(); //combine the two buffers and generate a template | |
if(response == 0) { | |
debugPort.println(); | |
response = fps.saveTemplate(1, location); //save the template to the specified location in library | |
if(response == 0) { | |
debugPort.print("-- Fingerprint enrolled at ID #"); | |
debugPort.print(location); | |
debugPort.println(" successfully --"); | |
} | |
} | |
else if(response == FPS_RESP_ENROLLMISMATCH) { | |
debugPort.println("ERROR : Fingerprints do not belong to same finger. Please try again."); | |
} | |
} | |
} | |
} | |
} | |
debugPort.println(); | |
} | |
//=========================================================================// | |
//Arduino setup function | |
void setup() { | |
Serial.begin(115200); | |
fps.begin(115200); | |
Serial.println(); | |
Serial.println("R307 Fingerprint Test"); | |
Serial.println("======================"); | |
Serial.println(); | |
//you need to verify the password before you can do anything else | |
Serial.println("Verifying password.."); | |
uint8_t response = fps.verifyPassword(0xFFFFFFFF); | |
Serial.println(); | |
//this is optional | |
Serial.println("Setting new address.."); | |
response = fps.setAddress(0xFFFFFFFF); | |
Serial.println(); | |
} | |
//=========================================================================// | |
//infinite loop | |
void loop() { | |
uint8_t response = 0; | |
String inputString = ""; | |
String commandString = ""; | |
String firstParam = ""; | |
String secondParam = ""; | |
String thirdParam = ""; | |
//send commands and parameters for each operation | |
//items are separated by single whitespace | |
//you can send up to 3 parameters | |
if(Serial.available()) { //monitor the serial interface | |
inputString = Serial.readString(); //read the contents of serial buffer as string | |
Serial.print("Command : "); | |
Serial.println(inputString); | |
Serial.println(); | |
//-------------------------------------------------------------------------// | |
uint8_t posCount = 0; | |
int indexOfSpace = 0; | |
while(inputString.indexOf(" ") != -1) { //loop until all whitespace chars are found | |
indexOfSpace = inputString.indexOf(" "); //get the position of first whitespace | |
if(indexOfSpace != -1) { //if a whitespace is found | |
if(posCount == 0) //the first one will be command string | |
commandString = inputString.substring(0, indexOfSpace); //end char is exclusive | |
if(posCount == 1) //second will be second param | |
firstParam = inputString.substring(0, indexOfSpace); | |
if(posCount == 2) //and so on | |
secondParam = inputString.substring(0, indexOfSpace); | |
else if(posCount == 3) | |
thirdParam = inputString.substring(0, indexOfSpace); | |
inputString = inputString.substring(indexOfSpace+1); //trim the input string | |
posCount++; | |
} | |
} | |
//saves the last part of the string is no more whitespace is found | |
if(posCount == 0) //if there's just the command | |
commandString = inputString; | |
if(posCount == 1) | |
firstParam = inputString; | |
if(posCount == 2) | |
secondParam = inputString; | |
if(posCount == 3) | |
thirdParam = inputString; | |
//-------------------------------------------------------------------------// | |
//separate and print the received command and parameters | |
Serial.print("Command string = "); | |
Serial.println(commandString); | |
if(firstParam != "") { | |
Serial.print("First param = "); | |
Serial.println(firstParam); | |
} | |
if(secondParam != "") { | |
Serial.print("Second param = "); | |
Serial.println(secondParam); | |
} | |
if(thirdParam != "") { | |
Serial.print("Third param = "); | |
Serial.println(thirdParam); | |
} | |
Serial.println(); | |
//-------------------------------------------------------------------------// | |
//deletes all the templates in the library | |
//this command has no parameters | |
//eg. clrlib | |
if(commandString == "clrlib") { | |
response = fps.clearLibrary(); | |
} | |
//-------------------------------------------------------------------------// | |
//get templates count | |
//eg. tmpcnt | |
else if(commandString == "tmpcnt") { | |
Serial.println("Reading templates count.."); | |
response = fps.getTemplateCount(); | |
} | |
//-------------------------------------------------------------------------// | |
//read system parameters | |
//eg. readsys | |
else if(commandString == "readsys") { | |
response = fps.readSysPara(); | |
} | |
//-------------------------------------------------------------------------// | |
//set data length | |
//this command has a single parameter | |
//value should be 32, 64, 128 or 256 | |
//eg. setdatlen 256 | |
else if(commandString == "setdatlen") { | |
uint16_t length = firstParam.toInt(); | |
response = fps.setDataLength(length); | |
} | |
//-------------------------------------------------------------------------// | |
//capture and range search library | |
//this command has three parameters | |
//eg. capranser 3000 1 10 | |
else if(commandString == "capranser") { | |
uint16_t timeOut = firstParam.toInt(); //first parameter in milliseconds | |
uint16_t startLocation = secondParam.toInt(); //second parameter | |
uint16_t count = thirdParam.toInt(); //third parameter | |
Serial.println("Capture and range search fingerprint.."); | |
delay(1000); | |
Serial.println("Put your finger on the sensor.."); | |
delay(3000); | |
response = fps.captureAndRangeSearch(timeOut, startLocation, count); | |
} | |
//-------------------------------------------------------------------------// | |
//capture and full search library | |
//eg. capfulser | |
else if(commandString == "capfulser") { | |
Serial.println("Capture and full search fingerprint.."); | |
delay(1000); | |
Serial.println("Put your finger on the sensor.."); | |
delay(3000); | |
response = fps.captureAndFullSearch(); | |
} | |
//-------------------------------------------------------------------------// | |
//enroll a new fingerprint | |
//you need to scan the finger twice | |
//follow the on-screen instructions | |
//eg. enroll | |
else if(commandString == "enroll") { | |
uint16_t location = firstParam.toInt(); //converts String object to int | |
enrollFinger(location); | |
} | |
//-------------------------------------------------------------------------// | |
//verify 4 byte password | |
//password should be sent as hex string | |
//eg. verpwd FF16FF16 | |
else if(commandString == "verpwd") { | |
const char* hexString = firstParam.c_str(); //convert String object to C-style string | |
uint32_t password = strtol(hexString, NULL, 16); //convert hex formatted C-style string to int value | |
response = fps.verifyPassword(password); | |
} | |
//-------------------------------------------------------------------------// | |
//set 4 byte password sent in hex format | |
//password should be sent as hex string | |
//eg. setpwd FF16FF16 | |
else if(commandString == "setpwd") { | |
const char* hexString = firstParam.c_str(); //convert String object to C-style string | |
uint32_t password = strtol(hexString, NULL, 16); //convert hex formatted C-style string to int value | |
response = fps.setPassword(password); | |
} | |
//-------------------------------------------------------------------------// | |
//set 4 byte address sent in hex format | |
//address should be sent as hex string | |
//eg. setaddr FF16FF16 | |
else if(commandString == "setaddr") { | |
const char *hexString = firstParam.c_str(); //convert String object to C-style string | |
uint32_t address = strtol(hexString, NULL, 16); //convert hex formatted C-style string to int value | |
response = fps.setAddress(address); | |
} | |
//-------------------------------------------------------------------------// | |
//set baudrate | |
//baudrate must be integer multiple of 96000. max is 115200 | |
//eg. setbaud 115200 | |
else if(commandString == "setbaud") { | |
uint32_t baudrate = firstParam.toInt(); | |
response = fps.setBaudrate(baudrate); | |
} | |
//-------------------------------------------------------------------------// | |
//set security level | |
//security level value must be 1-5 | |
//deafault is usually 2 | |
//eg. setseclvl 4 | |
else if(commandString == "setseclvl") { | |
uint8_t level = firstParam.toInt(); | |
response = fps.setSecurityLevel(level); | |
} | |
//-------------------------------------------------------------------------// | |
//scan finger image and save to image buffer | |
//eg. genimg | |
else if(commandString == "genimg") { | |
response = fps.generateImage(); | |
} | |
//-------------------------------------------------------------------------// | |
//generate character file from image | |
//buffer Id should be 1 or 2 | |
//eg. genchar 1 | |
else if(commandString == "genchar") { | |
uint8_t bufferId = firstParam.toInt(); | |
response = fps.generateCharacter(bufferId); | |
} | |
//-------------------------------------------------------------------------// | |
//generate template from char buffers | |
//template is the digital format of a fingerprint | |
//generated template will be available on both buffers 1 and 2 | |
//eg. gentmp | |
else if(commandString == "gentmp") { | |
response = fps.generateTemplate(); | |
} | |
//-------------------------------------------------------------------------// | |
//save template on buffer to library | |
//buffer ID should be 1 or 2 | |
//location should be #1 - #10000 (don't send the "#" with command) | |
//eg. savtmp 1 32 | |
else if(commandString == "savtmp") { | |
uint8_t bufferId = firstParam.toInt(); | |
uint16_t location = secondParam.toInt(); | |
response = fps.saveTemplate(bufferId, location); | |
} | |
//-------------------------------------------------------------------------// | |
//load template from library to buffer 1 or 2 | |
//buffer ID should be 1 or 2 | |
//location should be #1 - #10000 (don't send the "#" with command) | |
//eg. lodtmp 1 32 | |
else if(commandString == "lodtmp") { | |
uint8_t bufferId = firstParam.toInt(); | |
uint16_t location = secondParam.toInt(); | |
response = fps.loadTemplate(bufferId, location); | |
} | |
//-------------------------------------------------------------------------// | |
//delete one or more templates from library | |
//to delete a single template, simply send 1 as quantity or count | |
//eg. deltmp 5 1 | |
else if(commandString == "deltmp") { | |
uint16_t startLocation = firstParam.toInt(); //start location in library | |
uint16_t count = secondParam.toInt(); //quantity to delete | |
response = fps.deleteTemplate(startLocation, count); | |
} | |
//-------------------------------------------------------------------------// | |
//precisely match templates on the buffers 1 and 2 | |
//returns match score (matchScore) | |
//eg. mattmp | |
else if(commandString == "mattmp") { | |
response = fps.matchTemplates(); | |
} | |
//-------------------------------------------------------------------------// | |
//search the library for content on the buffer | |
//buffer ID should be 1 or 2 | |
//start location cane be #1 to #1000 (don't send the "#" with command) | |
//eg. serlib 1 10 50 | |
else if(commandString == "serlib") { | |
uint8_t bufferId = firstParam.toInt(); | |
uint16_t startLocation = secondParam.toInt(); | |
uint16_t count = thirdParam.toInt(); | |
response = fps.searchLibrary(bufferId, startLocation, count); | |
} | |
//-------------------------------------------------------------------------// | |
//unknown command | |
else { | |
Serial.print("Invalid command : "); | |
Serial.println(commandString); | |
} | |
Serial.println("..........................."); | |
Serial.println(); | |
delay(2000); | |
} | |
} | |
//=========================================================================// | |
It took me a very long time to develop the library for this fingerprint scanner module and a good amount of time to write this documentation. I hope you will my tutorial useful. If you found any error with documentation or code, however small it is, feel free to tell me about it. Your questions are welcome.