Interfacing R307 Optical Fingerprint Scanner with Arduino

Complete tutorial on interfacing R307 series optical fingerprint scanners from Hangzhou Grow, with Arduino compatible library.
R307 Optical Fingerprint Scanner

Fingerprints are one of the many unique biometric signatures 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 R300R301TR302R303R303TR305R306R308, 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.

R307 Specifications

  • Power Supply : DC 4.2V-6V
  • Current Consumption : ~50mA
  • Interface : UART and USB
  • Baudrate : (9600 * N) bps, N = 1-12, default is 6
  • Image Acquiring Time : <0.5s
  • Matching Modes : 1:1, 1:N
  • Character File Size : 256 Bytes
  • Template Size : 512 Bytes
  • Storage Capacity : 1000
  • Security Levels : 5
  • FAR (False Acceptance Rate) : <0.001%
  • FRR (False Recognition Rate) : <0.1%
  • Average Searching Time : <1s (1:1000)
  • Window Dimensions : 19 * 21 mm
  • Working Environment : Temp = -10°C – +40°C, RH = 20%-80%
  • Storage Environment : Temp = -40°C – +85°C, RH = <85%
  • Outline Dimensions : Split Type, 44.1 * 20 * 23.5 mm

How Does An Optical Fingerprint Scanner Work?

Fingerprint close-up image [Source : Wikipedia]

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.

Optical fingerprint scanner working principle

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.

R307 Construction & Disassembly

R307 Fingerprint Scanner cross-section (illustrative only)

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.

LEDs and touch sense pad
Image sensor
Remove the cap to see the prism
Prism assembly
Light barrier

R307 Physical Dimensions

R307 Fingerprint Scanner Physical Dimensions

R307 Pinout

R307 fingerprint scanner pinout
Pin NumberNameTypeDescription
1+5VINPositive Supply (DC 4.2V-6V)
2GNDGNDSupply Ground
3TXDOUTData output (TTL)
4RXDINData input (TTL)
5TouchOUTFinger detection signal (max output current: 50mA)
63.3VINFinger detection power (DC 3.3V-5V ~5uA)
R307 fingerprint scanner pinout

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.

R307 Schematic

R307 fingerprint scanner PCB side

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.

Error-ridden schematic of R307 fingerprint scanner provided 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!

R307 Memory and Registers

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.

NameDescriptionOffset (word)Size (word)
Status RegisterContents of system status register01
System Identifier CodeFixed value: 0x000911
Library SizeFingerprint library size21
Security LevelSecurity level (1, 2, 3, 4, 5)31
Device Address32-bit device address42
Data Packet SizeSize code (0, 1, 2, 3)61
Baud MultiplierN (baud = 9600*N bps)71

The Status Register indicates the current operation status of the module, and comprises of the following,

Bit Number15-43210

where 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.

System Identifier Code is a fixed value that determines the type of module. Its value is 0x0009 for R307.

Library Size is the number of templates that can be stored in the module. The maximum value for this parameter is 1000 for R307.

Security Value determines the threshold for fingerprint searching and matching. Its value can be from 1-5. When it is 1, the FAR (False Acceptance Rate) is the highest and FRR (False Recognition Rate) is the lowest. FAR is simply the number that determines how likely the module will identify a weakly matched fingerprint as positive. FRR is how likely the module will identify a wrong fingerprint as negative. At level 5, the FAR is the lowest and FFR is the highest. In this setting, it can be difficult to match your fingerprint.

Device Address is a 32-bit value that holds the address of the module. The correct address is needed to communicate with the module. If you don’t send the correct address, the module won’t execute any commands. Device address can be modified with the command 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.

Data Packet Size determines the maximum length of data content in a single packet. Its value can be 0-3 where 0 = 32 bytes, 1 = 64 bytes, 2 = 128 bytes and 3 = 256 bytes.

Baud Multiplier sets the UART communication speed of the module. The minimum speed is 9600bps and can be set to up to 12 times of that which is 115200bps. The multiplier value N can be from 1-12 and the effective speed will be (9600*N) bps. The default baudrate is 57600bps.

R307 Communication Protocol

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.

R307 UART frame format

The packet format is as follows (length in bytes is shown in brackets),

Header (2)Address (4)Packet Identifier (1)Packet Length (2)Packet Content (Instruction/Data/Parameter)Checksum (2)

If you feel confused, the UART frame is how a byte of data is transferred via the UART interface. A packet is a group of many such bytes (or frames). Let’s see the definitions of each part.

  1. Header : This indicates the start of a packet. It has to be the fixed value 0xEF01. It is 2 bytes long and the high byte is always transferred first.
  2. Address : This is the 32-bit address of the scanner module. The module will accept instructions only if the address we are sending matches the address stored in the module. The default address is 0xFFFFFFFF and can be modified with SetAddr instruction.
  3. Packet Identifier : This determines what type of packet we’re sending or receiving. It is 1 byte long and depending on the value the packet types can be,
    • 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.
  4. Packet Length : This is the total length of Packet Content and Checksum in bytes. Maximum length is 256 bytes and high byte is transferred first.
  5. Packet Content : This can be data/command/parameters etc. of varying length. The Packet Length is the value that specifies the length of the data here in bytes.
  6. Checksum : This is the arithmetic sum of all bytes in Packet IdentifierPacket Length and Packet Content. Overflowing bits are ignored. High byte is always transferred first.

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,

R307 commands and their byte codes

Following is the list of confirmation codes.

  • 0x00 – Command execution complete
  • 0x01 – Error when receiving data package
  • 0x02 – No finger on the sensor
  • 0x03 – Failed to enroll the finger
  • 0x04 – Failed to generate character file due to the over-disorderly fingerprint image
  • 0x05 – Failed to generate character file due to the over-wet fingerprint image
  • 0x06 – Failed to generate character file due to the over-disorderly fingerprint image
  • 0x07 – Failed to generate character file due to lack of character point or over-smallness of fingerprint image
  • 0x08 – Finger doesn’t match
  • 0x09 – Failed to find a matching finger
  • 0x0A – Failed to combine the character files
  • 0x0B – Addressing PageID is beyond the finger library
  • 0x0C – Error when reading template from library or the template is invalid
  • 0x0D – Error when uploading template
  • 0x0E – Module can’t receive the following data packages
  • 0x0F – Error when uploading image
  • 0x10 – Failed to delete the template
  • 0x11 – Failed to clear finger library
  • 0x13 – Wrong password
  • 0x15 – Failed to generate the image
  • 0x18 – Error when writing flash
  • 0x19 – No definition error
  • 0x21 – Password not verified
  • 0x1A – Invalid register number
  • 0x1B – Incorrect configuration of register
  • 0x1C – Wrong notepad page number
  • 0x1D – Failed to operate the communication port
  • 0x41 – No finger on sensor when add fingerprint on second time
  • 0x42 – Failed to enroll the finger for second fingerprint scan
  • 0x43 – 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 scan
  • 0x45 – Duplicate fingerprint
  • Others – System reserved

The confirmation code 0x21 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.

All the commands and their response codes are explained in detail in the manual. So it would be redundant to do it here. But let’s look at the VfyPwd instruction and its corresponding packet for an example.

2 bytes4 bytes1 byte2 bytes1 byte4 bytes2 bytes
HeaderAddressPacket IdentifierPacket LengthInstruction CodeData (Password)Checksum

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 bytes4 bytes1 byte2 bytes1 byte2 bytes
HeaderAddressPacket IdentifierPacket LengthConfirmation CodeChecksum

The confirmation code will be 0x00 if our password was correct and 0x13 if it was not.

Interfacing with PC Application

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.

SFG Demo software
SYNO Demo software – we’ll be using this

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.

SYNO Demo software – open device success.

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.

R30X Arduino Library

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 has become an exercise for me.

Since the instruction set and confirmation codes are compatible with many versions of the fingerprint scanner, you could easily modify this 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 yet 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 the 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.

Library Details

The library is now part of the official Arduino library set. To install it on your computer, open the Library Manager from the Arduino IDE and search for “R30X fingerprint scanner”. Then install the latest version from the list.


All the constants are defined inside the main header file. It includes all the commands, response codes and default values. 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.


#define FPS_DEBUG   //uncomment this line to enable debug info to be printed

#define debugPort Serial  //the serisl port to which debug info will be sent

//Response codes from FPS to the commands sent to it
//FPS = 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_SCANFINGER            0x01U    //scans the finger and collect finger image
#define FPS_CMD_IMAGETOCHARACTER      0x02U    //generate char file from a single image and store it to one of the buffers
#define FPS_CMD_MATCHTEMPLATES        0x03U    //match two fingerprints precisely
#define FPS_CMD_SEARCHLIBRARY         0x04U    //search the fingerprint library
#define FPS_CMD_GENERATETEMPLATE      0x05U    //combine both character buffers and generate a template
#define FPS_CMD_STORETEMPLATE         0x06U    //store the template on one of the buffers to flash memory
#define FPS_CMD_LOADTEMPLATE          0x07U    //load a template from flash memory to one of the buffers
#define FPS_CMD_EXPORTTEMPLATE        0x08U    //export a template file from buffer to computer
#define FPS_CMD_IMPORTTEMPLATE        0x09U    //import a template file from computer to sensor buffer
#define FPS_CMD_EXPORTIMAGE           0x0AU    //export fingerprint image from buffer to computer
#define FPS_CMD_IMPORTIMAGE           0x0BU    //import an image from computer to sensor buffer
#define FPS_CMD_DELETETEMPLATE        0x0CU    //delete a template from flash memory
#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_SCANANDRANGESEARCH    0x32U    //read total template count
#define FPS_CMD_SCANANDFULLSEARCH     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 paramter was delivered



The main class with variables and functions.

Member Variables

These are public and private member variables. Some parameters have both array and whole bit versions such as 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 *txDataBuffermySerial 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.

//common parameters

uint16_t startCodeL;  //packet start marker
uint8_t startCode[2]; //packet start marker

uint32_t devicePasswordL;  //32-bit single value version of password (L = long)
uint32_t deviceAddressL;   //module's address
uint8_t devicePassword[4]; //array version of password
uint8_t deviceAddress[4];  //device address as an array

uint16_t statusRegister; //contents of the FPS status register
uint16_t systemID;       //fixed value 0x0009
uint16_t librarySize;    //library memory size
uint16_t securityLevel;  //threshold level for fingerprint matching
uint16_t dataPacketLengthCode;
uint16_t dataPacketLength; //the max length of data in packet. can be 32, 64, 128 or 256
uint16_t baudMultiplier;   //value between 1-12
uint32_t deviceBaudrate;   //UART speed (9600 * baud multiplier)

//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


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
Member Functions

Not all of these functions are fully implemented. All that working are demonstrated in the example Arduino sketch.

R30X_FPS(HardwareSerial *hs, uint32_t password = FPS_DEFAULT_PASSWORD, uint32_t address = FPS_DEFAULT_ADDRESS);

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 reinitializePort(uint32_t baud);
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 exportImage(void);  //export a fingerprint image from the sensor to the computer
uint8_t importImage(uint8_t *dataBuffer); //import a fingerprint image from the computer 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 exportCharacter(uint8_t bufferId);  //export a character file from the sensor to computer
uint8_t importCharacter(uint8_t bufferId, uint8_t *dataBuffer); //import a character file to the sensor from computer
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

Functions are explained below.

R30X_Fingerprint (HardwareSerial *hs, uint32_t password = FPS_DEFAULT_PASSWORD, uint32_t address = FPS_DEFAULT_ADDRESS);
R30X_Fingerprint (SoftwareSerial *ss, uint32_t password = FPS_DEFAULT_PASSWORD, uint32_t address = FPS_DEFAULT_ADDRESS);

These are the constructors for hardware and software serial interfaces. These are not overloaded but conditionally selected. The usage is shown in the example sketch. First parameter is the serial port you want to use to communicate to the module, which is different from debug port. Next you have to send the 32-bit password and address. If you want to use the default ones, send nothing.

void begin (uint32_t baud);

This initializes the serial port with specified baud rate.

void resetParameters (void);

Resets all parameters to default values.

uint8_t verifyPassword (uint32_t password = FPS_DEFAULT_PASSWORD);

Verifies the given password. You need to verify the password before doing anything. Otherwise the module will always respond with a 0x21 error code. If you want to test for the default password, pass nothing. Otherwise send your custom password. Returns the confirmation code.

uint8_t setPassword (uint32_t password);

This updates the password on the module. The password is also saved to the parameter variables. Returns the confirmation code.

uint8_t setAddress (uint32_t address = FPS_DEFAULT_ADDRESS);

Updates the device address. Once you successfully change it, all further data packets must include the new address. Returns the confirmation code.

uint8_t setBaudrate (uint32_t baud);

This modifies the baudrate at which your module is communicating. It first changes the baudrate multiplier on the module, closes the current serial port and reinitializes the serial port with the new baudrate. This can be difficult at times. Returns the confirmation code.

uint8_t reinitializePort (uint32_t baud);

Reinitializes the port with a new baud rate.

uint8_t setSecurityLevel (uint8_t level);

Sets the the security level. Values can be 1-5. Returns the confirmation code.

uint8_t setDataLength (uint16_t length);

Sets the data length. Values can be 32, 64, 128, 256 bytes. Returns the confirmation code.

uint8_t portControl (uint8_t value);

Turns the communication port on or off from the module side. Value can be 1 = ON or 0 = OFF. Returns the confirmation code.

uint8_t sendPacket (uint8_t type, uint8_t command, uint8_t* data = NULL, uint16_t dataLength = 0);

Creates a packet with command and data, and sends it out to the module. When there’s not data accompanied with a command, you can leave the data and dataLength parameters empty. If you enable debugging, the packet will be printed to the debug port. Returns the confirmation code.

uint8_t receivePacket (uint32_t timeout=FPS_DEFAULT_TIMEOUT);

Reads data from the serial monitor, extracts parameters from the packet and saves them to the variables. You could optionally send the timeout the host must wait for a reply. If you leave this empty, FPS_DEFAULT_TIMEOUT will be used which is 2 seconds. Returns the confirmation code.

vuint8_t readSysPara (void);

Reads the contents of the System Configuration Register (16 bytes) and saves values to the variables. Returns the confirmation code.

uint8_t captureAndRangeSearch (uint16_t captureTimeout, uint16_t startId, uint16_t count);

Scans a finger and search between a range of locations in the fingerprint library. You should send the timeout for the scan, start location and the number of locations to search. If the operation was successful, the results are stored in fingerId and matchScore. Returns the confirmation code.

uint8_t captureAndFullSearch (void);

Scans a finger and search the entire fingerprint library for a match. There’s no control over the timeout or anything. The module does everything itself. If you want to specify the timeout, use the 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.

uint8_t generateImage (void);

Scans the finger once and store the captured image to the Image Buffer. You may read the content of the buffer after executing this. Returns the confirmation code.

uint8_t downloadImage (void);

This retrieves the content of the Image Buffer to the host. After the confirmation from the module side, it will start transferring of data. The host must be prepared to accept the data. Returns the confirmation code. This function is not fully implemented.

uint8_t generateCharacter (uint8_t bufferId);

Generates a character file from the image stored in the Image Buffer. The generated character file is saved to one of the two character buffers, which must be specified to the function. Returns the confirmation code.

uint8_t generateTemplate (void);

Generates a template file combining the two character file buffers. Therefore two scans must be performed in order to generate a template file. The generated template file will be stored to the CharBuffer1. Returns the confirmation code.

uint8_t downloadCharacter (uint8_t bufferId);

Retrieves the character file content from one of the two buffers. You should specify the buffer number which can be 1 or 2. After the confirmation packet, the module will start sending the data. The host must be prepared to accept the data. Returns the confirmation code. This function is not fully implemented.

uint8_t uploadCharacter (uint8_t bufferId, uint8_t* dataBuffer);

This allows you to send a character file you already have to one of the buffers inside the module. This will allow you to save and restore fingerprint database. You should send the buffer number and data. After the confirmation the host must send the data to the module. Returns the confirmation code. This function is not fully implemented.

uint8_t saveTemplate (uint8_t bufferId, uint16_t location);

This function saves the template file in one of the buffers to any location in the fingerprint library. You should specify the buffer ID and the location you want save to. Returns the confirmation code.

uint8_t loadTemplate (uint8_t bufferId, uint16_t location);

Loads one of the character buffers with a template from the fingerprint library. You should specify the buffer you want to use and the location in the fingerprint library you want the template to load from. Returns the confirmation code.

uint8_t deleteTemplate (uint16_t startLocation, uint16_t count);

Deletes one or more templates from the specified range in the fingerprint library. Returns the confirmation code.

uint8_t clearLibrary (void);

Erases all contents of the fingerprint library. This action is irreversible. Returns the confirmation code.

uint8_t matchTemplates (void);

Precisely matches the contents of the two character file buffers. The result is stored in the matchScore variable. Returns the confirmation code.

uint8_t searchLibrary (uint8_t bufferId, uint16_t startLocation, uint16_t count);

Searches the fingerprint library for a template stored in one of the character buffers. You should specify the buffer number, start location and number of templates to match. The results are stored in fingerId and matchScore. Returns the confirmation code.

uint8_t getTemplateCount (void);

Gets the total number of templates available in the fingerprint library. The result is saved on templateCount. Returns the confirmation code.

Example Sketch

The example Arduino sketch to test the fingerprint scanner is available here –

I wrote this code for Arduino Due which has 4 hardware serial ports. I am using first serial port Serial for debugging and Serial1 for fingerprint scanner interface. The password and address are the default 0xFFFFFFFF. Three of these parameters are passed to the constructor. You must use the password and address of your module if they were 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 firstParamsecondParam 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 library
  • tmpcnt – get templates count
  • readsys – read system parameters
  • setdatlen <data length> – set data length
  • capranser <timeout> <start location> <quantity> – capture and range search library for fingerprint
  • capfulser – capture and full search the library for fingerprint
  • enroll <location> – enroll new fingerprint
  • verpwd <password> – verify 4 byte device password
  • setpwd <password> – set new 4 byte device password
  • setaddr <address> – set new 4 byte device address
  • setbaud <baudrate> – set the baudrate
  • reinitprt <baudrate> – reinitialize the port without changing device configuration
  • setseclvl <level> – set security level
  • genimg – generate image
  • genchar <buffer id> – generate character file from image
  • gentmp – generate template from character buffers
  • savtmp <buffer id> <location> – save template to library from buffer
  • lodtmp <buffer id> <location> – load template from library to buffer
  • deltmp <start location> <quantity> – delete one or more templates from library
  • mattmp – precisely match two templates available on buffers
  • serlib <buffer id> <start location> <quantity> – search library for content on the buffer

What appears between < and > are parameters that must be sent with the command (< or > should not be included). Commands and parameters must be separated by a single whitespace. For example, “enroll 12” will enroll a new fingerprint at location #12.

The enrollFinger() function implements the fingerprint enrolling process.

Result of capranser command with debug info

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.

Tested Boards

The library was tested with Arduino Due and Arduino Uno using R307 fingerprint scanner. To wire up, connect the TX and RX pins to the TX1 and RX1 pins of Due or Mega. If you’re using Uno or similar boards with only one hardware UART, use SoftwareSerial for the fingerprint sensor and hardware UART for debugging.

Even though not tested, the library is expected to work with other Arduino compatible microcontrollers and boards such as ESP8266, ESP32, STM32 Nucleo, TI Launchpad etc.


When something is not working, upload the example sketch to your board and run the commands to check if they’re working as expected.

  1. Getting “Password is not correct” message
    New modules will be coming with the default password and device address 0xFFFFFFFF. If the example sketch complains about wrong password, then try running the setpwd command. For example, setpwd FFFFFFFF
  2. Getting “Invalid command” message
    If your serial terminal application is sending NL/CR characters automatically, try turning this off. For example, you can turn this feature off at Arduino serial monitor.




  1. SYNO Demo [ZIP]
  2. SFG Demo [RAR]
  3. R30X Fingerprint Scanner User Manual [PDF]
  4. R300 Fingerprint Scanner User Manual [PDF]
  5. R301T Fingerprint Scanner User Manual [PDF]
  6. R302 Fingerprint Scanner User Manual [PDF]
  7. R303 Fingerprint Scanner User Manual [PDF]
  8. R303T Fingerprint Scanner User Manual [PDF]
  9. R305 Fingerprint Scanner User Manual [PDF]
  10. R306 Fingerprint Scanner User Manual [PDF]
  11. R307 Fingerprint Scanner User Manual [PDF]
  12. R308 Fingerprint Scanner User Manual [PDF]
  13. R311 Fingerprint Scanner User Manual [PDF]


  1. Adafruit Fingerprint Sensor Library
  2. RhydoLabz R30X Fingerprint Scanner Tutorial
Share to your friends
Default image
Vishnu Mohanan
Founder and Chief Editor at CIRCUITSTATE Electronics
Articles: 21

Leave a Reply