Continue to Site

Welcome to EDAboard.com

Welcome to our site! EDAboard.com is an international Electronics Discussion Forum focused on EDA software, circuits, schematics, books, theory, papers, asic, pld, 8051, DSP, Network, RF, Analog Design, PCB, Service Manuals... and a whole lot more! To participate you need to register. Registration is free. Click here to register now.

[PIC32] Problem with C Code {Biometric Attendance System project]

Status
Not open for further replies.

pic.programmer

Advanced Member level 3
Joined
Aug 19, 2015
Messages
773
Helped
141
Reputation
284
Reaction score
140
Trophy points
43
Activity points
7,531
I am making a Biometric Attendance System and I am have problem declaring a struct.

Here is the struct.

It is giving errors.


Code C - [expand]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
#define bool char
 
#define true 1
#define flase 0
 
struct Commands_Packet {
    struct Commands {
        enum Commands_Enum {
            NotSet              = 0x00,   // Default value for enum. Scanner will return error if sent this.
            Open                = 0x01,   // Open Initialization
            Close               = 0x02,   // Close Termination
            UsbInternalCheck    = 0x03,   // UsbInternalCheck Check if the connected USB device is valid
            ChangeEBaudRate     = 0x04,   // ChangeBaudrate Change UART baud rate
            SetIAPMode          = 0x05,   // SetIAPMode Enter IAP Mode In this mode, FW Upgrade is available
            CmosLed             = 0x12,   // CmosLed Control CMOS LED
            GetEnrollCount      = 0x20,   // Get enrolled fingerprint count
            CheckEnrolled       = 0x21,   // Check whether the specified ID is already enrolled
            EnrollStart         = 0x22,   // Start an enrollment
            Enroll1             = 0x23,   // Make 1st template for an enrollment
            Enroll2             = 0x24,   // Make 2nd template for an enrollment
            Enroll3             = 0x25,   // Make 3rd template for an enrollment, merge three templates into one template, save merged template to the database
            IsPressFinger       = 0x26,   // Check if a finger is placed on the sensor
            DeleteID            = 0x40,   // Delete the fingerprint with the specified ID
            DeleteAll           = 0x41,   // Delete all fingerprints from the database
            Verify1_1           = 0x50,   // Verification of the capture fingerprint image with the specified ID
            Identify1_N         = 0x51,   // Identification of the capture fingerprint image with the database
            VerifyTemplate1_1   = 0x52,   // Verification of a fingerprint template with the specified ID
            IdentifyTemplate1_N = 0x53,   // Identification of a fingerprint template with the database
            CaptureFinger       = 0x60,   // Capture a fingerprint image(256x256) from the sensor
            MakeTemplate        = 0x61,   // Make template for transmission
            GetImage            = 0x62,   // Download the captured fingerprint image(256x256)
            GetRawImage         = 0x63,   // Capture & Download raw fingerprint image(320x240)
            GetTemplate         = 0x70,   // Download the template of the specified ID
            SetTemplate         = 0x71,   // Upload the template of the specified ID
            GetDatabaseStart    = 0x72,   // Start database download, obsolete
            GetDatabaseEnd      = 0x73,   // End database download, obsolete
            UpgradeFirmware     = 0x80,   // Not supported
            UpgradeISOCDImage   = 0x81,   // Not supported
            Ack                 = 0x30,   // Acknowledge.
            Nack                = 0x31    // Non-acknowledge
        };
    };
 
 
 
Commands.Commands_Enum fpsCommand;
unsigned char Parameter[4];                // Parameter 4 bytes, changes meaning depending on command
 
static const byte COMMAND_START_CODE_1 = 0x55;  // Static byte to mark the beginning of a command packet  - never changes
static const byte COMMAND_START_CODE_2 = 0xAA;  // Static byte to mark the beginning of a command packet  - never changes
static const byte COMMAND_DEVICE_ID_1 = 0x01; // Device ID Byte 1 (lesser byte)             - theoretically never changes
static const byte COMMAND_DEVICE_ID_2 = 0x00; // Device ID Byte 2 (greater byte)              - theoretically never changes
unsigned char command[2];                // Command 2 bytes
 
unsigned char* GetPacketBytes();             // returns the bytes to be transmitted
void ParameterFromInt(int i);
unsigned int _CalculateChecksum();            // Checksum is calculated using byte addition
unsigned char GetHighByte(unsigned int w);
unsigned char GetLowByte(unsigned int w);
 
unsigned char* Command_Packet_GetPacketBytes()
{
  unsigned char packetbytes[12];
  unsigned int cmd, checksum;
 
  // update command before calculating checksum (important!)
  cmd = Command;
  command[0] = GetLowByte(cmd);
  command[1] = GetHighByte(cmd);
 
  checksum = _CalculateChecksum();
 
  packetbytes[0] = COMMAND_START_CODE_1;
  packetbytes[1] = COMMAND_START_CODE_2;
  packetbytes[2] = COMMAND_DEVICE_ID_1;
  packetbytes[3] = COMMAND_DEVICE_ID_2;
  packetbytes[4] = Parameter[0];
  packetbytes[5] = Parameter[1];
  packetbytes[6] = Parameter[2];
  packetbytes[7] = Parameter[3];
  packetbytes[8] = command[0];
  packetbytes[9] = command[1];
  packetbytes[10] = GetLowByte(checksum);
  packetbytes[11] = GetHighByte(checksum);
 
  return packetbytes;
}
 
// Converts the int to bytes and puts them into the paramter array
void Command_Packet_ParameterFromInt(int i)
{
  Parameter[0] = (i & 0x000000ff);
  Parameter[1] = (i & 0x0000ff00) >> 8;
  Parameter[2] = (i & 0x00ff0000) >> 16;
  Parameter[3] = (i & 0xff000000) >> 24;
}
 
// Returns the high byte from a word
unsigned char Command_Packet_GetHighByte(unsigned int w)
{
  return (unsigned char)(w>>8)&0x00FF;
}
 
// Returns the low byte from a word
unsigned char Command_Packet_GetLowByte(unsigned int w)
{
  return (unsigned char)w&0x00FF;
}
 
unsigned int Command_Packet__CalculateChecksum()
{
  unsigned int w = 0;
 
  w += COMMAND_START_CODE_1;
  w += COMMAND_START_CODE_2;
  w += COMMAND_DEVICE_ID_1;
  w += COMMAND_DEVICE_ID_2;
  w += Parameter[0];
  w += Parameter[1];
  w += Parameter[2];
  w += Parameter[3];
  w += command[0];
  w += command[1];
 
  return w;
}
};



Errors given are

Code:
0 122 Compilation Started FPS Text.c
41 396 Invalid declarator expected'(' or identifier FPS Text.c
42 396 Invalid declarator expected'(' or identifier FPS Text.c
46 300 Syntax Error: ';' expected,  but '.' found FPS Text.c
46 398 Declarator error FPS Text.c
46 371 Specifier needed FPS Text.c
46 402 ; expected, but 'fpsCommand' found FPS Text.c
49 402 ; expected, but 'COMMAND_START_CODE_1' found FPS Text.c
49 402 ; expected, but '=' found FPS Text.c
49 371 Specifier needed FPS Text.c
49 396 Invalid declarator expected'(' or identifier FPS Text.c
50 402 ; expected, but 'COMMAND_START_CODE_2' found FPS Text.c
50 312 Internal error '' FPS Text.c
0 102 Finished (with errors): 16 Jan 2016, 16:20:09 FPS Text.mcp32

- - - Updated - - -

I came to know that functions cannot be used inside struct.

Here is my new code. I am getting error creating a enum like myFpsCommands.


Code C - [expand]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
struct Cmds_Packet {
    struct Commands {
        enum Commands_Enum {
            NotSet              = 0x00,   // Default value for enum. Scanner will return error if sent this.
            Open                = 0x01,   // Open Initialization
            Close               = 0x02,   // Close Termination
            UsbInternalCheck    = 0x03,   // UsbInternalCheck Check if the connected USB device is valid
            ChangeEBaudRate     = 0x04,   // ChangeBaudrate Change UART baud rate
            SetIAPMode          = 0x05,   // SetIAPMode Enter IAP Mode In this mode, FW Upgrade is available
            CmosLed             = 0x12,   // CmosLed Control CMOS LED
            GetEnrollCount      = 0x20,   // Get enrolled fingerprint count
            CheckEnrolled       = 0x21,   // Check whether the specified ID is already enrolled
            EnrollStart         = 0x22,   // Start an enrollment
            Enroll1             = 0x23,   // Make 1st template for an enrollment
            Enroll2             = 0x24,   // Make 2nd template for an enrollment
            Enroll3             = 0x25,   // Make 3rd template for an enrollment, merge three templates into one template, save merged template to the database
            IsPressFinger       = 0x26,   // Check if a finger is placed on the sensor
            DeleteID            = 0x40,   // Delete the fingerprint with the specified ID
            DeleteAll           = 0x41,   // Delete all fingerprints from the database
            Verify1_1           = 0x50,   // Verification of the capture fingerprint image with the specified ID
            Identify1_N         = 0x51,   // Identification of the capture fingerprint image with the database
            VerifyTemplate1_1   = 0x52,   // Verification of a fingerprint template with the specified ID
            IdentifyTemplate1_N = 0x53,   // Identification of a fingerprint template with the database
            CaptureFinger       = 0x60,   // Capture a fingerprint image(256x256) from the sensor
            MakeTemplate        = 0x61,   // Make template for transmission
            GetImage            = 0x62,   // Download the captured fingerprint image(256x256)
            GetRawImage         = 0x63,   // Capture & Download raw fingerprint image(320x240)
            GetTemplate         = 0x70,   // Download the template of the specified ID
            SetTemplate         = 0x71,   // Upload the template of the specified ID
            GetDatabaseStart    = 0x72,   // Start database download, obsolete
            GetDatabaseEnd      = 0x73,   // End database download, obsolete
            UpgradeFirmware     = 0x80,   // Not supported
            UpgradeISOCDImage   = 0x81,   // Not supported
            Ack                 = 0x30,   // Acknowledge.
            Nack                = 0x31    // Non-acknowledge
        }myCommands_Enum;
    }myCommands;
 
    myCommands.Commands_Enum myFpsCommands
 
    unsigned char Parameter[4];                // Parameter 4 bytes, changes meaning depending on command
 
    unsigned char COMMAND_START_CODE_1;        // Static byte to mark the beginning of a command packet  - never changes
    unsigned char COMMAND_START_CODE_2;        // Static byte to mark the beginning of a command packet  - never changes
    unsigned char COMMAND_DEVICE_ID_1;         // Device ID Byte 1 (lesser byte)             - theoretically never changes
    unsigned char COMMAND_DEVICE_ID_2;         // Device ID Byte 2 (greater byte)              - theoretically never changes
    unsigned char  command[2];                 // Command 2 bytes
}Commands_Packet;

 

The enum C statement is one of the simplest array fitters available at the language and it usage is somewhat intuitive; It is plenty documented on the Web. Have you tried at least to make this change yourself ?
 

'enum' just assigns a number to the variable sequentially from zero or a new starting value. It doesn't define a variable or allocate any storage for it. There is no point in assigning a value to every item in an 'enum' list because thats what the 'enum' does by itself.

However, your problem is that you are trying to create a stucture wrongly. A structure is one or more variables which are grouped together so they can be referred to as one entity. Your structure contains no variabes!

I'm guessing the list of items are individual commands which are held in variable as part of the structure. If I'm right, what you should do is '#define' them instead of enumerate them and then add a variable, lets call it 'MyCommand' to the structure as 'char MyCommand'. You can then set MyCommand to one of the values you defined.

If you want to create a structure which has storage for all of those items simultaneously, you need to give each a type so the compiler can allocate the correct storage space for them all.

Brian.
 
I am trying to post a C++ Arduino Library to C and I am having difficultier. The library is for GT-511CR Fingerprint Sensor. The Arduino Code works fine. I have tested it.

In C++ code there are Classes and enums. I have converted the classes to structs.

https://www.instructables.com/id/DIY-Fingerprint-Scanning-Garage-Door-Opener/

This is my new struct and it compiles file. I have created a struct variable Command.

I can also create a global pointer to this struct but I am not able to create a pointer to this struct inside a function. That is local pointer to struct.


Code C - [expand]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
struct Cmd_Packet {
    struct Cmds {
        enum Cmds_Enum {
              NotSet              = 0x00,                // Default value for enum. Scanner will return error if sent this.
              Open                = 0x01,                // Open Initialization
              Close               = 0x02,                // Close Termination
              UsbInternalCheck    = 0x03,                // UsbInternalCheck Check if the connected USB device is valid
              ChangeEBaudRate     = 0x04,                // ChangeBaudrate Change UART baud rate
              SetIAPMode          = 0x05,                // SetIAPMode Enter IAP Mode In this mode, FW Upgrade is available
              CmosLed             = 0x12,                // CmosLed Control CMOS LED
              GetEnrollCount      = 0x20,                // Get enrolled fingerprint count
              CheckEnrolled       = 0x21,                // Check whether the specified ID is already enrolled
              EnrollStart         = 0x22,                // Start an enrollment
              Enroll1             = 0x23,                // Make 1st template for an enrollment
              Enroll2             = 0x24,                // Make 2nd template for an enrollment
              Enroll3             = 0x25,                // Make 3rd template for an enrollment, merge three templates into one template, save merged template to the database
              IsPressFinger       = 0x26,                // Check if a finger is placed on the sensor
              DeleteID            = 0x40,                // Delete the fingerprint with the specified ID
              DeleteAll           = 0x41,                // Delete all fingerprints from the database
              Verify1_1           = 0x50,                // Verification of the capture fingerprint image with the specified ID
              Identify1_N         = 0x51,                // Identification of the capture fingerprint image with the database
              VerifyTemplate1_1   = 0x52,                // Verification of a fingerprint template with the specified ID
              IdentifyTemplate1_N = 0x53,                // Identification of a fingerprint template with the database
              CaptureFinger       = 0x60,                // Capture a fingerprint image(256x256) from the sensor
              MakeTemplate        = 0x61,                // Make template for transmission
              GetImage            = 0x62,                // Download the captured fingerprint image(256x256)
              GetRawImage         = 0x63,                // Capture & Download raw fingerprint image(320x240)
              GetTemplate         = 0x70,                // Download the template of the specified ID
              SetTemplate         = 0x71,                // Upload the template of the specified ID
              GetDatabaseStart    = 0x72,                // Start database download, obsolete
              GetDatabaseEnd      = 0x73,                // End database download, obsolete
              UpgradeFirmware     = 0x80,                // Not supported
              UpgradeISOCDImage   = 0x81,                // Not supported
              Ack                 = 0x30,                // Acknowledge.
              Nack                = 0x31                 // Non-acknowledge
         }Command;
    }Commands;
 
    unsigned char Parameter[4];                                                                // Parameter 4 bytes, changes meaning depending on command
 
    unsigned char COMMAND_START_CODE_1;        // Static byte to mark the beginning of a command packet        -        never changes
    unsigned char COMMAND_START_CODE_2;        // Static byte to mark the beginning of a command packet        -        never changes
    unsigned char COMMAND_DEVICE_ID_1;         // Device ID Byte 1 (lesser byte)                                                        -        theoretically never changes
    unsigned char COMMAND_DEVICE_ID_2;         // Device ID Byte 2 (greater byte)                                                        -        theoretically never changes
    unsigned char command[2];                  // Command 2 bytes
}Command_packet;

 

Again it's most likely a trivial violation of C syntax rules, as in your first post.

Unfortunately we need to guess what you are exactly doing. Why don't you show the failing code, marking the error location?

- - - Updated - - -

You don't need to repeat the definition of the command_packet struct variable, just show how you reference it.

If you want to make multiple instances of or pointers to a structured variable, you'll preferably define the type first (using typedef) and then the variable instance(s) and pointers. If you need to access sub entities through pointers, use multiple hierarchical typedefs to define the structure.
 
Line 104 and 340 are giving errors. If I comment line 140 and also the function starting at line 340 then code compiles fine and also the test code which Opens the Sensor and Toggles the Sensor's CmosLED are working.


Code C - [expand]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
#define bool unsigned char
#define uint8_t unsigned char
 
#define TRUE 1
#define FALSE 0
 
bool UseSerialDebug;
 
//Command_Packet represents the 12 byte command that we send to the finger print scanner
 
struct Cmd_Packet {
    struct Cmds {
        enum Cmds_Enum {
              NotSet              = 0x00,                // Default value for enum. Scanner will return error if sent this.
              Open                = 0x01,                // Open Initialization
              Close               = 0x02,                // Close Termination
              UsbInternalCheck    = 0x03,                // UsbInternalCheck Check if the connected USB device is valid
              ChangeEBaudRate     = 0x04,                // ChangeBaudrate Change UART baud rate
              SetIAPMode          = 0x05,                // SetIAPMode Enter IAP Mode In this mode, FW Upgrade is available
              CmosLed             = 0x12,                // CmosLed Control CMOS LED
              GetEnrollCount      = 0x20,                // Get enrolled fingerprint count
              CheckEnrolled       = 0x21,                // Check whether the specified ID is already enrolled
              EnrollStart         = 0x22,                // Start an enrollment
              Enroll1             = 0x23,                // Make 1st template for an enrollment
              Enroll2             = 0x24,                // Make 2nd template for an enrollment
              Enroll3             = 0x25,                // Make 3rd template for an enrollment, merge three templates into one template, save merged template to the database
              IsPressFinger       = 0x26,                // Check if a finger is placed on the sensor
              DeleteID            = 0x40,                // Delete the fingerprint with the specified ID
              DeleteAll           = 0x41,                // Delete all fingerprints from the database
              Verify1_1           = 0x50,                // Verification of the capture fingerprint image with the specified ID
              Identify1_N         = 0x51,                // Identification of the capture fingerprint image with the database
              VerifyTemplate1_1   = 0x52,                // Verification of a fingerprint template with the specified ID
              IdentifyTemplate1_N = 0x53,                // Identification of a fingerprint template with the database
              CaptureFinger       = 0x60,                // Capture a fingerprint image(256x256) from the sensor
              MakeTemplate        = 0x61,                // Make template for transmission
              GetImage            = 0x62,                // Download the captured fingerprint image(256x256)
              GetRawImage         = 0x63,                // Capture & Download raw fingerprint image(320x240)
              GetTemplate         = 0x70,                // Download the template of the specified ID
              SetTemplate         = 0x71,                // Upload the template of the specified ID
              GetDatabaseStart    = 0x72,                // Start database download, obsolete
              GetDatabaseEnd      = 0x73,                // End database download, obsolete
              UpgradeFirmware     = 0x80,                // Not supported
              UpgradeISOCDImage   = 0x81,                // Not supported
              Ack                 = 0x30,                // Acknowledge.
              Nack                = 0x31                 // Non-acknowledge
         }Command;
    }Commands;
 
    unsigned char Parameter[4];                                                                // Parameter 4 bytes, changes meaning depending on command
 
    unsigned char COMMAND_START_CODE_1;        // Static byte to mark the beginning of a command packet        -        never changes
    unsigned char COMMAND_START_CODE_2;        // Static byte to mark the beginning of a command packet        -        never changes
    unsigned char COMMAND_DEVICE_ID_1;         // Device ID Byte 1 (lesser byte)                                                        -        theoretically never changes
    unsigned char COMMAND_DEVICE_ID_2;         // Device ID Byte 2 (greater byte)                                                        -        theoretically never changes
    unsigned char command[2];                  // Command 2 bytes
}Command_packet;
 
struct Resp_Packet {
    struct ErrCodes {
       enum Errs_Enum {
          NO_ERROR                    = 0x0000,        // Default value. no error
          NACK_TIMEOUT                = 0x1001,        // Obsolete, capture timeout
          NACK_INVALID_BAUDRATE       = 0x1002,        // Obsolete, Invalid serial baud rate
          NACK_INVALID_POS            = 0x1003,        // The specified ID is not between 0~199
          NACK_IS_NOT_USED            = 0x1004,        // The specified ID is not used
          NACK_IS_ALREADY_USED        = 0x1005,        // The specified ID is already used
          NACK_COMM_ERR               = 0x1006,        // Communication Error
          NACK_VERIFY_FAILED          = 0x1007,        // 1:1 Verification Failure
          NACK_IDENTIFY_FAILED        = 0x1008,        // 1:N Identification Failure
          NACK_DB_IS_FULL             = 0x1009,        // The database is full
          NACK_DB_IS_EMPTY            = 0x100A,        // The database is empty
          NACK_TURN_ERR               = 0x100B,        // Obsolete, Invalid order of the enrollment (The order was not as: EnrollStart -> Enroll1 -> Enroll2 -> Enroll3)
          NACK_BAD_FINGER             = 0x100C,        // Too bad fingerprint
          NACK_ENROLL_FAILED          = 0x100D,        // Enrollment Failure
          NACK_IS_NOT_SUPPORTED       = 0x100E,        // The specified command is not supported
          NACK_DEV_ERR                = 0x100F,        // Device Error, especially if Crypto-Chip is trouble
          NACK_CAPTURE_CANCELED       = 0x1010,        // Obsolete, The capturing is canceled
          NACK_INVALID_PARAM          = 0x1011,        // Invalid parameter
          NACK_FINGER_IS_NOT_PRESSED  = 0x1012,        // Finger is not pressed
          INVALID                     = 0XFFFF         // Used when parsing fails
       }Error, e;
 
 
    }ErrorCodes;
    
    //Response_Packet(unsigned char* buffer, bool UseSerialDebug);
    unsigned char RawBytes[12];
    unsigned char ParameterBytes[4];
    unsigned char ResponseBytes[2];
    bool ACK;
    unsigned char COMMAND_START_CODE_1;        // Static byte to mark the beginning of a command packet        -        never changes
    unsigned char COMMAND_START_CODE_2;        // Static byte to mark the beginning of a command packet        -        never changes
    unsigned char COMMAND_DEVICE_ID_1;        // Device ID Byte 1 (lesser byte)                                                        -        theoretically never changes
    unsigned char COMMAND_DEVICE_ID_2;        // Device ID Byte 2 (greater byte)                                                        -        theoretically never changes
 
}Response_Packet;
 
unsigned char* Command_Packet_GetPacketBytes();                                                        // returns the bytes to be transmitted
void Command_Packet_ParameterFromInt(int i);
unsigned int Command_Packet_CalculateChecksum();                                                // Checksum is calculated using byte addition
unsigned char Command_Packet_GetHighByte(unsigned int w);
unsigned char Command_Packet_GetLowByte(unsigned int w);
 
enum Response_Packet.ErrorCodes.Error Response_Packet_ErrorCodes_ParseFromBytes(unsigned char high, unsigned char low);
void Response_Packet_Response_Packet(unsigned char* buffer, bool UseSerialDebug);
 
int Response_Packet_IntFromParameter();
bool Response_Packet_CheckParsing(unsigned char b, unsigned char propervalue, unsigned char alternatevalue, char* varname, bool UseSerialDebug);
unsigned int Response_Packet_CalculateChecksum(unsigned char* buffer, int length);
unsigned char Response_Packet_GetHighByte(unsigned int w);
unsigned char Response_Packet_GetLowByte(unsigned int w);
 
//Initialises the device and gets ready for commands
void FPS_GT511C3_Open();
 
// Does not actually do anything (according to the datasheet)
// I implemented open, so had to do closed too... lol
void FPS_GT511C3_Close();
 
// Turns on or off the LED backlight
// LED must be on to see fingerprints
// Parameter: true turns on the backlight, false turns it off
// Returns: True if successful, false if not
bool FPS_GT511C3_SetLED(bool on);
 
// Changes the baud rate of the connection
// Parameter: 9600 - 115200
// Returns: True if success, false if invalid baud
// NOTE: Untested (don't have a logic level changer and a voltage divider is too slow)
bool FPS_GT511C3_ChangeBaudRate(int baud);
 
// Gets the number of enrolled fingerprints
// Return: The total number of enrolled fingerprints
int FPS_GT511C3_GetEnrollCount();
 
// checks to see if the ID number is in use or not
// Parameter: 0-199
// Return: True if the ID number is enrolled, false if not
bool FPS_GT511C3_CheckEnrolled(int id);
 
// Starts the Enrollment Process
// Parameter: 0-199
// Return:
//        0 - ACK
//        1 - Database is full
//        2 - Invalid Position
//        3 - Position(ID) is already used
int FPS_GT511C3_EnrollStart(int id);
 
// Gets the first scan of an enrollment
// Return:
//        0 - ACK
//        1 - Enroll Failed
//        2 - Bad finger
//        3 - ID in use
int FPS_GT511C3_Enroll1();
 
// Gets the Second scan of an enrollment
// Return:
//        0 - ACK
//        1 - Enroll Failed
//        2 - Bad finger
//        3 - ID in use
int FPS_GT511C3_Enroll2();
 
// Gets the Third scan of an enrollment
// Finishes Enrollment
// Return:
//        0 - ACK
//        1 - Enroll Failed
//        2 - Bad finger
//        3 - ID in use
int FPS_GT511C3_Enroll3();
 
// Checks to see if a finger is pressed on the FPS
// Return: true if finger pressed, false if not
bool FPS_GT511C3_IsPressFinger();
 
// Deletes the specified ID (enrollment) from the database
// Returns: true if successful, false if position invalid
bool FPS_GT511C3_DeleteID(int ID);
 
// Deletes all IDs (enrollments) from the database
// Returns: true if successful, false if db is empty
bool FPS_GT511C3_DeleteAll();
 
// Checks the currently pressed finger against a specific ID
// Parameter: 0-199 (id number to be checked)
// Returns:
//        0 - Verified OK (the correct finger)
//        1 - Invalid Position
//        2 - ID is not in use
//        3 - Verified FALSE (not the correct finger)
int FPS_GT511C3_Verify1_1(int id);
 
// Checks the currently pressed finger against all enrolled fingerprints
// Returns:
//        0-199: Verified against the specified ID (found, and here is the ID number)
//        200: Failed to find the fingerprint in the database
int FPS_GT511C3_Identify1_N();
 
// Captures the currently pressed finger into onboard ram
// Parameter: true for high quality image(slower), false for low quality image (faster)
// Generally, use high quality for enrollment, and low quality for verification/identification
// Returns: True if ok, false if no finger pressed
bool FPS_GT511C3_CaptureFinger(bool highquality);
 
//-= Not implemented commands =-
 
// Gets an image that is 258x202 (52116 bytes) and returns it in 407 Data_Packets
// Use StartDataDownload, and then GetNextDataPacket until done
// Returns: True (device confirming download starting)
// Not implemented due to memory restrictions on the arduino
// may revisit this if I find a need for it
//bool GetImage();
 
// Gets an image that is qvga 160x120 (19200 bytes) and returns it in 150 Data_Packets
// Use StartDataDownload, and then GetNextDataPacket until done
// Returns: True (device confirming download starting)
// Not implemented due to memory restrictions on the arduino
// may revisit this if I find a need for it
//bool GetRawImage();
 
// Gets a template from the fps (498 bytes) in 4 Data_Packets
// Use StartDataDownload, and then GetNextDataPacket until done
// Parameter: 0-199 ID number
// Returns:
//        0 - ACK Download starting
//        1 - Invalid position
//        2 - ID not used (no template to download
// Not implemented due to memory restrictions on the arduino
// may revisit this if I find a need for it
//int GetTemplate(int id);
 
// Uploads a template to the fps
// Parameter: the template (498 bytes)
// Parameter: the ID number to upload
// Parameter: Check for duplicate fingerprints already on fps
// Returns:
//        0-199 - ID duplicated
//        200 - Uploaded ok (no duplicate if enabled)
//        201 - Invalid position
//        202 - Communications error
//        203 - Device error
// Not implemented due to memory restrictions on the arduino
// may revisit this if I find a need for it
//int SetTemplate(byte* tmplt, int id, bool duplicateCheck);
 
// Commands that are not implemented (and why)
// VerifyTemplate1_1 - Couldn't find a good reason to implement this on an arduino
// IdentifyTemplate1_N - Couldn't find a good reason to implement this on an arduino
// MakeTemplate - Couldn't find a good reason to implement this on an arduino
// UsbInternalCheck - not implemented - Not valid config for arduino
// GetDatabaseStart - historical command, no longer supported
// GetDatabaseEnd - historical command, no longer supported
// UpgradeFirmware - Data Sheet says not supported
// UpgradeISOCDImage - Data Sheet says not supported
// SetIAPMode - for upgrading firmware (which is not supported)
// Ack and Nack        are listed as a commands for some unknown reason... not implemented
 
void FPS_GT511C3_serialPrintHex(unsigned char data_);
void FPS_GT511C3_SendToSerial(unsigned char data[], int length);
 
// resets the Data_Packet class, and gets ready to download
// Not implemented due to memory restrictions on the arduino
// may revisit this if I find a need for it
//void StartDataDownload();
 
// Returns the next data packet
// Not implemented due to memory restrictions on the arduino
// may revisit this if I find a need for it
//Data_Packet GetNextDataPacket();
 
void SendCommand(unsigned char cmd[], int length);
void GetResponse();
 
unsigned char* Command_Packet_GetPacketBytes() {
    unsigned char packetbytes[12];
    unsigned int cmd, checksum;
    // update command before calculating checksum (important!)
    cmd = Command_packet.Commands.Command;
    Command_Packet.command[0] = Command_Packet_GetLowByte(cmd);
    Command_Packet.command[1] = Command_Packet_GetHighByte(cmd);
 
    checksum = Command_Packet_CalculateChecksum();
 
    packetbytes[0] = Command_Packet.COMMAND_START_CODE_1;
    packetbytes[1] = Command_Packet.COMMAND_START_CODE_2;
    packetbytes[2] = Command_Packet.COMMAND_DEVICE_ID_1;
    packetbytes[3] = Command_Packet.COMMAND_DEVICE_ID_2;
    packetbytes[4] = Command_Packet.Parameter[0];
    packetbytes[5] = Command_Packet.Parameter[1];
    packetbytes[6] = Command_Packet.Parameter[2];
    packetbytes[7] = Command_Packet.Parameter[3];
    packetbytes[8] = Command_Packet.command[0];
    packetbytes[9] = Command_Packet.command[1];
    packetbytes[10] = Command_Packet_GetLowByte(checksum);
    packetbytes[11] = Command_Packet_GetHighByte(checksum);
 
    return &packetbytes;
}
 
// Converts the int to bytes and puts them into the paramter array
void Command_Packet_ParameterFromInt(int i) {
    Command_Packet.Parameter[0] = (i & 0x000000ff);
    Command_Packet.Parameter[1] = (i & 0x0000ff00) >> 8;
    Command_Packet.Parameter[2] = (i & 0x00ff0000) >> 16;
    Command_Packet.Parameter[3] = (i & 0xff000000) >> 24;
}
 
// Returns the high byte from a word
unsigned char Command_Packet_GetHighByte(unsigned int w) {
    return (unsigned char)(w>>8)&0x00FF;
}
 
// Returns the low byte from a word
unsigned char Command_Packet_GetLowByte(unsigned int w) {
    return (unsigned char)w&0x00FF;
}
 
unsigned int Command_Packet_CalculateChecksum() {
    unsigned int w = 0;
 
    w += Command_Packet.COMMAND_START_CODE_1;
    w += Command_Packet.COMMAND_START_CODE_2;
    w += Command_Packet.COMMAND_DEVICE_ID_1;
    w += Command_Packet.COMMAND_DEVICE_ID_2;
    w += Command_Packet.Parameter[0];
    w += Command_Packet.Parameter[1];
    w += Command_Packet.Parameter[2];
    w += Command_Packet.Parameter[3];
    w += Command_Packet.command[0];
    w += Command_Packet.command[1];
 
    return w;
}
 
// parses bytes into one of the possible errors from the finger print scanner
//Response_Packet::ErrorCodes::Errors_Enum Response_Packet_ErrorCodes_ParseFromBytes(unsigned char high, unsigned char low)
enum Response_Packet.ErrorCodes.Error Response_Packet_ErrorCodes_ParseFromBytes(unsigned char high, unsigned char low) {
    Response_Packet.ErrorCodes.e = INVALID;
 
    if (high == 0x00)
    {
    }
    // grw 01/03/15 - replaced if clause with else clause for any non-zero high byte
    // if (high == 0x01)
    // {
    else {
        switch(low) {
            case 0x00: Response_Packet.ErrorCodes.e = NO_ERROR; break;
            case 0x01: Response_Packet.ErrorCodes.e = NACK_TIMEOUT; break;
            case 0x02: Response_Packet.ErrorCodes.e = NACK_INVALID_BAUDRATE; break;
            case 0x03: Response_Packet.ErrorCodes.e = NACK_INVALID_POS; break;
            case 0x04: Response_Packet.ErrorCodes.e = NACK_IS_NOT_USED; break;
            case 0x05: Response_Packet.ErrorCodes.e = NACK_IS_ALREADY_USED; break;
            case 0x06: Response_Packet.ErrorCodes.e = NACK_COMM_ERR; break;
            case 0x07: Response_Packet.ErrorCodes.e = NACK_VERIFY_FAILED; break;
            case 0x08: Response_Packet.ErrorCodes.e = NACK_IDENTIFY_FAILED; break;
            case 0x09: Response_Packet.ErrorCodes.e = NACK_DB_IS_FULL; break;
            case 0x0A: Response_Packet.ErrorCodes.e = NACK_DB_IS_EMPTY; break;
            case 0x0B: Response_Packet.ErrorCodes.e = NACK_TURN_ERR; break;
            case 0x0C: Response_Packet.ErrorCodes.e = NACK_BAD_FINGER; break;
            case 0x0D: Response_Packet.ErrorCodes.e = NACK_ENROLL_FAILED; break;
            case 0x0E: Response_Packet.ErrorCodes.e = NACK_IS_NOT_SUPPORTED; break;
            case 0x0F: Response_Packet.ErrorCodes.e = NACK_DEV_ERR; break;
            case 0x10: Response_Packet.ErrorCodes.e = NACK_CAPTURE_CANCELED; break;
            case 0x11: Response_Packet.ErrorCodes.e = NACK_INVALID_PARAM; break;
            case 0x12: Response_Packet.ErrorCodes.e = NACK_FINGER_IS_NOT_PRESSED; break;
        };
    }
 
    return Response_Packet.ErrorCodes.e;
}
 
void Response_Packet_Response_Packet(unsigned char* buffer, bool UseSerialDebug) {
 
    unsigned int checksum, i;
    unsigned char checksum_low;
    unsigned char checksum_high;
 
    Response_Packet_CheckParsing(buffer[0], Response_Packet.COMMAND_START_CODE_1, Response_Packet.COMMAND_START_CODE_1, "COMMAND_START_CODE_1", UseSerialDebug);
    Response_Packet_CheckParsing(buffer[1], Response_Packet.COMMAND_START_CODE_2, Response_Packet.COMMAND_START_CODE_2, "COMMAND_START_CODE_2", UseSerialDebug);
    Response_Packet_CheckParsing(buffer[2], Response_Packet.COMMAND_DEVICE_ID_1, Response_Packet.COMMAND_DEVICE_ID_1, "COMMAND_DEVICE_ID_1", UseSerialDebug);
    Response_Packet_CheckParsing(buffer[3], Response_Packet.COMMAND_DEVICE_ID_2, Response_Packet.COMMAND_DEVICE_ID_2, "COMMAND_DEVICE_ID_2", UseSerialDebug);
    Response_Packet_CheckParsing(buffer[8], 0x30, 0x31, "AckNak_LOW", UseSerialDebug);
    if (buffer[8] == 0x30) Response_Packet.ACK = TRUE; else Response_Packet.ACK = FALSE;
    Response_Packet_CheckParsing(buffer[9], 0x00, 0x00, "AckNak_HIGH", UseSerialDebug);
 
    checksum = Response_Packet_CalculateChecksum(buffer, 10);
    checksum_low = Response_Packet_GetLowByte(checksum);
    checksum_high = Response_Packet_GetHighByte(checksum);
    Response_Packet_CheckParsing(buffer[10], checksum_low, checksum_low, "Checksum_LOW", UseSerialDebug);
    Response_Packet_CheckParsing(buffer[11], checksum_high, checksum_high, "Checksum_HIGH", UseSerialDebug);
 
    Response_Packet.ErrorCodes.Error = Response_Packet_ErrorCodes_ParseFromBytes(buffer[5], buffer[4]);
 
    Response_Packet.ParameterBytes[0] = buffer[4];
    Response_Packet.ParameterBytes[1] = buffer[5];
    Response_Packet.ParameterBytes[2] = buffer[6];
    Response_Packet.ParameterBytes[3] = buffer[7];
    Response_Packet.ResponseBytes[0] = buffer[8];
    Response_Packet.ResponseBytes[1] = buffer[9];
 
    for(i = 0; i < 12; i++) {
        Response_Packet.RawBytes[i] = buffer[i];
    }
}
 
// Gets an int from the parameter bytes
int Response_Packet_IntFromParameter() {
    int retval = 0;
 
    retval = (retval << 8) + Response_Packet.ParameterBytes[3];
    retval = (retval << 8) + Response_Packet.ParameterBytes[2];
    retval = (retval << 8) + Response_Packet.ParameterBytes[1];
    retval = (retval << 8) + Response_Packet.ParameterBytes[0];
 
    return retval;
}
 
// calculates the checksum from the bytes in the Packet
unsigned int Response_Packet_CalculateChecksum(unsigned char* buffer, int length) {
    unsigned int checksum = 0;
    unsigned int i = 0;
    
    for(i = 0; i < length; i++) {
        checksum += buffer[i];
    }
 
    return checksum;
}
 
// Returns the high byte from a word
unsigned char Response_Packet_GetHighByte(unsigned int w) {
    return (unsigned char)(w>>8)&0x00FF;
}
 
// Returns the low byte from a word
unsigned char Response_Packet_GetLowByte(unsigned int w) {
    return (unsigned char)w&0x00FF;
}
 
// checks to see if the byte is the proper value, and logs it to the serial channel if not
bool Response_Packet_CheckParsing(unsigned char b, unsigned char propervalue, unsigned char alternatevalue, char* varname, bool UseSerialDebug) {
    bool retval;
    char str[22];
    
    retval = (b != propervalue) && (b != alternatevalue);
    
    if((UseSerialDebug) && (retval)) {
        UART5_Write_Text("Response_Packet parsing error \r\n");
        UART5_Write_Text(varname);
        UART5_Write_Text(" ");
        ByteToHex(propervalue, str);
        Ltrim(str);
        Rtrim(str);
        UART5_Write_Text(str);
        UART5_Write_Text(" || ");
        ByteToHex(alternatevalue, str);
        Ltrim(str);
        Rtrim(str);
        UART5_Write_Text(str);
        UART5_Write_Text(" != ");
        ByteToHex(b, str);
        Ltrim(str);
        Rtrim(str);
        UART5_Write_Text(str);
    }
}
void FPS_GT511C3_SendCommand(unsigned char cmd[], int length) {
    unsigned int i = 0;
 
    for(i = 0; i < length; i++) {
         UART2_Write(cmd[i]);
    }
 
    if(UseSerialDebug) {
        UART5_Write_Text("FPS - SEND: ");
        for(i = 0; i < length; i++) {
           UART5_Write(cmd[i]);
        }
 
        UART5_Write_Text("\r\n");
    }
}
 
// sends a byte to the serial debugger in the hex format we want EX "0F"
void FPS_GT511C3_serialPrintHex(unsigned char data_) {
    char tmp[16];
    ByteToHex(tmp, data_);
    Ltrim(tmp);
    Rtrim(tmp);
    UART5_Write_Text(tmp);
}
 
// sends the bye aray to the serial debugger in our hex format EX: "00 AF FF 10 00 13"
void FPS_GT511C3_SendToSerial(unsigned char data_[], int length) {
    bool first = TRUE;
    unsigned int i;
 
    UART5_Write_Text(""");
 
    for(i = 0; i < length; i++) {
       if(first)first = FALSE;
       else UART5_Write_Text(" ");
       FPS_GT511C3_serialPrintHex(data_[i]);
    }
 
    UART5_Write_Text(""");
}
 
// Gets the response to the command from the software serial channel (and waits for it)
void FPS_GT511C3_GetResponse() {
    unsigned char firstbyte = 0;
    bool done = FALSE;
    unsigned char resp[12];
    unsigned int i;
 
    while(done == FALSE) {
       firstbyte = (unsigned char)UART2_Read();
 
       if(firstbyte == Response_Packet.COMMAND_START_CODE_1) {
            done = TRUE;
       }
    }
 
    resp[0] = firstbyte;
 
    for(i = 1; i < 12; i++) {
          resp[i]= (unsigned char)UART2_Read();
    }
 
    Response_Packet_Response_Packet(resp, UseSerialDebug);
 
    if(UseSerialDebug) {
              UART5_Write_Text("FPS - RECV: ");
              FPS_GT511C3_SendToSerial(Response_Packet.RawBytes, 12);
              UART5_Write_Text("\r\n");
              UART5_Write_Text("\r\n");
    }
}
 
bool FPS_GT511C3_ChangeBaudRate(int baud) {
    unsigned char* Packetbytes;
    bool retval;
    
    if((baud == 9600) || (baud == 19200) || (baud == 38400) || (baud == 57600) || (baud == 115200)) {
        if(UseSerialDebug)UART5_Write_Text("FPS - ChangeBaudRate\r\n");
        Command_Packet.Commands.Command = Open;
        Command_Packet_ParameterFromInt(baud);
        Packetbytes = Command_Packet_GetPacketBytes();
        FPS_GT511C3_SendCommand(Packetbytes, 12);
        FPS_GT511C3_GetResponse();
        retval = Response_Packet.ACK;
        
        if(retval) {
            UART2_Init(baud);
            Delay_ms(200);
        }
 
        return retval;
    }
    
    return FALSE;
}
 
void FPS_GT511C3_Open() {
    unsigned char* Packetbytes;
    
    if(UseSerialDebug)UART5_Write_Text("FPS - Open\r\n");
    Command_Packet.Commands.Command = Open;
    Command_Packet.Parameter[0] = 0x00;
    Command_Packet.Parameter[1] = 0x00;
    Command_Packet.Parameter[2] = 0x00;
    Command_Packet.Parameter[3] = 0x00;
    Packetbytes = Command_Packet_GetPacketBytes();
    FPS_GT511C3_SendCommand(Packetbytes, 12);
    FPS_GT511C3_GetResponse();
}
 
// Turns on or off the LED backlight
// Parameter: true turns on the backlight, false turns it off
// Returns: True if successful, false if not
bool FPS_GT511C3_SetLED(bool on) {
    unsigned char* Packetbytes;
    bool retval;
    
    Command_Packet.Commands.Command = CmosLed;
    
    if(on) {
       if(UseSerialDebug)UART5_Write_Text("FPS - LED on\r\n");
       Command_Packet.Parameter[0] = 0x01;
    }
    else {
       if(UseSerialDebug)UART5_Write_Text("FPS - LED off\r\n");
       Command_Packet.Parameter[0] = 0x00;
    }
    
    Command_Packet.Parameter[1] = 0x00;
    Command_Packet.Parameter[2] = 0x00;
    Command_Packet.Parameter[3] = 0x00;
    Packetbytes = Command_Packet_GetPacketBytes();
    FPS_GT511C3_SendCommand(Packetbytes, 12);
    FPS_GT511C3_GetResponse();
    retval = TRUE;
    if(Response_Packet.ACK == FALSE)retval = FALSE;
    return retval;
}
 
// Gets the number of enrolled fingerprints
// Return: The total number of enrolled fingerprints
int FPS_GT511C3_GetEnrollCount() {
    unsigned char* Packetbytes;
    int retval;
    
    if(UseSerialDebug)UART5_Write_Text("FPS - GetEnrolledCount\r\n");
    Command_Packet.Commands.Command = GetEnrollCount;
    Command_Packet.Parameter[0] = 0x00;
    Command_Packet.Parameter[1] = 0x00;
    Command_Packet.Parameter[2] = 0x00;
    Command_Packet.Parameter[3] = 0x00;
    Packetbytes = Command_Packet_GetPacketBytes();
    FPS_GT511C3_SendCommand(Packetbytes, 12);
    FPS_GT511C3_GetResponse();
 
    retval = Response_Packet_IntFromParameter();
    return retval;
}
 
// checks to see if the ID number is in use or not
// Parameter: 0-199
// Return: True if the ID number is enrolled, false if not
bool FPS_GT511C3_CheckEnrolled(int id) {
    unsigned char* Packetbytes;
    bool retval;
    
    if(UseSerialDebug)UART5_Write_Text("FPS - CheckEnrolled\r\n");
    Command_Packet.Commands.Command = CheckEnrolled;
    Command_Packet_ParameterFromInt(id);
    Packetbytes = Command_Packet_GetPacketBytes();
    FPS_GT511C3_SendCommand(Packetbytes, 12);
    FPS_GT511C3_GetResponse();
    retval = FALSE;
    retval = Response_Packet.ACK;
    return retval;
}
 
// Starts the Enrollment Process
// Parameter: 0-199
// Return:
//        0 - ACK
//        1 - Database is full
//        2 - Invalid Position
//        3 - Position(ID) is already used
int FPS_GT511C3_EnrollStart(int id) {
    unsigned char* Packetbytes;
    int retval;
    
    if(UseSerialDebug)UART5_Write_Text("FPS - EnrollStart\r\n");
    Command_Packet.Commands.Command = EnrollStart;
    Command_Packet_ParameterFromInt(id);
    Packetbytes = Command_Packet_GetPacketBytes();
    FPS_GT511C3_SendCommand(Packetbytes, 12);
    FPS_GT511C3_GetResponse();
    retval = 0;
    /*
    if(Response_Packet.ACK == FALSE)
    {
            if (if (rp->Error == Response_Packet::ErrorCodes::NACK_DB_IS_FULL) retval = 1;
            if (if (rp->Error ==  Response_Packet::ErrorCodes::NACK_INVALID_POS) retval = 2;
            if (if (rp->Error ==  Response_Packet::ErrorCodes::NACK_IS_ALREADY_USED) retval = 3;
    }
    */
    return retval;
}
 
// Gets the first scan of an enrollment
// Return:
//        0 - ACK
//        1 - Enroll Failed
//        2 - Bad finger
//        3 - ID in use
int FPS_GT511C3_Enroll1() {
    unsigned char* Packetbytes;
    int retval;
 
    if(UseSerialDebug)UART5_Write_Text("FPS - Enroll1\r\n");
    Command_Packet.Commands.Command = Enroll1;
    Packetbytes = Command_Packet_GetPacketBytes();
    FPS_GT511C3_SendCommand(Packetbytes, 12);
    FPS_GT511C3_GetResponse();
    retval = Response_Packet_IntFromParameter();
    
    if(retval < 200) retval = 3; else retval = 0;
    /*
    if(Response_Packet.ACK == FALSE)
    {
          if (rp->Error == Response_Packet::ErrorCodes::NACK_ENROLL_FAILED) retval = 1;
          if (rp->Error == Response_Packet::ErrorCodes::NACK_BAD_FINGER) retval = 2;
    }
    */
 
    if(Response_Packet.ACK) return 0; else return retval;
}
 
// Gets the Second scan of an enrollment
// Return:
//        0 - ACK
//        1 - Enroll Failed
//        2 - Bad finger
//        3 - ID in use
int FPS_GT511C3_Enroll2() {
    unsigned char* Packetbytes;
    int retval;
 
    if(UseSerialDebug)UART5_Write_Text("FPS - Enroll1\r\n");
    Command_Packet.Commands.Command = Enroll2;
    Packetbytes = Command_Packet_GetPacketBytes();
    FPS_GT511C3_SendCommand(Packetbytes, 12);
    FPS_GT511C3_GetResponse();
    retval = Response_Packet_IntFromParameter();
 
    if(retval < 200) retval = 3; else retval = 0;
    /*
    if(Response_Packet.ACK == FALSE)
    {
          if (rp->Error == Response_Packet::ErrorCodes::NACK_ENROLL_FAILED) retval = 1;
          if (rp->Error == Response_Packet::ErrorCodes::NACK_BAD_FINGER) retval = 2;
    }
    */
 
    if(Response_Packet.ACK) return 0; else return retval;
}
 
// Gets the Third scan of an enrollment
// Finishes Enrollment
// Return:
//        0 - ACK
//        1 - Enroll Failed
//        2 - Bad finger
//        3 - ID in use
int FPS_GT511C3_Enroll3() {
    unsigned char* Packetbytes;
    int retval;
 
    if(UseSerialDebug)UART5_Write_Text("FPS - Enroll1\r\n");
    Command_Packet.Commands.Command = Enroll3;
    Packetbytes = Command_Packet_GetPacketBytes();
    FPS_GT511C3_SendCommand(Packetbytes, 12);
    FPS_GT511C3_GetResponse();
    retval = Response_Packet_IntFromParameter();
 
    if(retval < 200) retval = 3; else retval = 0;
    /*
    if(Response_Packet.ACK == FALSE)
    {
          if (rp->Error == Response_Packet::ErrorCodes::NACK_ENROLL_FAILED) retval = 1;
          if (rp->Error == Response_Packet::ErrorCodes::NACK_BAD_FINGER) retval = 2;
    }
    */
 
    if(Response_Packet.ACK) return 0; else return retval;
}
 
// Checks to see if a finger is pressed on the FPS
// Return: true if finger pressed, false if not
bool FPS_GT511C3_IsPressFinger() {
    unsigned char* Packetbytes;
    bool retval;
    int pval;
    
    if(UseSerialDebug)UART5_Write_Text("FPS - IsPressFinger\r\n");
    Command_Packet.Commands.Command = IsPressFinger;
    Packetbytes = Command_Packet_GetPacketBytes();
    FPS_GT511C3_SendCommand(Packetbytes, 12);
    FPS_GT511C3_GetResponse();
    retval = FALSE;
    pval = Response_Packet.ParameterBytes[0];
    pval += Response_Packet.ParameterBytes[1];
    pval += Response_Packet.ParameterBytes[2];
    pval += Response_Packet.ParameterBytes[3];
    
    if(pval == 0)retval = TRUE;
 
    return retval;
}
 
// Deletes the specified ID (enrollment) from the database
// Parameter: 0-199 (id number to be deleted)
// Returns: true if successful, false if position invalid
bool FPS_GT511C3_DeleteID(int id) {
    unsigned char* Packetbytes;
    bool retval;
 
    if(UseSerialDebug)UART5_Write_Text("FPS - DeleteID\r\n");
    Command_Packet.Commands.Command = DeleteID;
    Command_Packet_ParameterFromInt(id);
    Packetbytes = Command_Packet_GetPacketBytes();
    FPS_GT511C3_SendCommand(Packetbytes, 12);
    FPS_GT511C3_GetResponse();
    retval = Response_Packet.ACK;
 
    return retval;
}
 
// Deletes all IDs (enrollments) from the database
// Returns: true if successful, false if db is empty
bool FPS_GT511C3_DeleteAll() {
    unsigned char* Packetbytes;
    bool retval;
    
    if(UseSerialDebug)UART5_Write_Text("FPS - DeleteAll\r\n");
    Command_Packet.Commands.Command = DeleteAll;
    Packetbytes = Command_Packet_GetPacketBytes();
    FPS_GT511C3_SendCommand(Packetbytes, 12);
    FPS_GT511C3_GetResponse();
    retval = Response_Packet.ACK;
 
    return retval;
}
 
// Checks the currently pressed finger against a specific ID
// Parameter: 0-199 (id number to be checked)
// Returns:
//        0 - Verified OK (the correct finger)
//        1 - Invalid Position
//        2 - ID is not in use
//        3 - Verified FALSE (not the correct finger)
int FPS_GT511C3_Verify1_1(int id) {
    unsigned char* Packetbytes;
    int retval;
    
    if(UseSerialDebug)UART5_Write_Text("FPS - Verify1_1\r\n");
    Command_Packet.Commands.Command = Verify1_1;
    Command_Packet_ParameterFromInt(id);
    Packetbytes = Command_Packet_GetPacketBytes();
    FPS_GT511C3_SendCommand(Packetbytes, 12);
    FPS_GT511C3_GetResponse();
    retval = 0;
    
    /*
    if(Response_Packet.ACK == FALSE)
    {
          retval = 3; // grw 01/03/15 - set default value of not verified before assignment
          if (rp->Error == Response_Packet::ErrorCodes::NACK_INVALID_POS) retval = 1;
          if (rp->Error == Response_Packet::ErrorCodes::NACK_IS_NOT_USED) retval = 2;
          if (rp->Error == Response_Packet::ErrorCodes::NACK_VERIFY_FAILED) retval = 3;
    }
    */
 
    return retval;
}
 
// Checks the currently pressed finger against all enrolled fingerprints
// Returns:
//        0-199: Verified against the specified ID (found, and here is the ID number)
//        200: Failed to find the fingerprint in the database
int FPS_GT511C3_Identify1_N() {
    unsigned char* Packetbytes;
    int retval;
    
    if(UseSerialDebug)UART5_Write_Text("FPS - Identify1_N\r\n");
    Command_Packet.Commands.Command = Identify1_N;
    Packetbytes = Command_Packet_GetPacketBytes();
    FPS_GT511C3_SendCommand(Packetbytes, 12);
    FPS_GT511C3_GetResponse();
    retval = Response_Packet_IntFromParameter();
    
    if(retval > 200) retval = 200;
 
    return retval;
}
 
// Captures the currently pressed finger into onboard ram use this prior to other commands
// Parameter: true for high quality image(slower), false for low quality image (faster)
// Generally, use high quality for enrollment, and low quality for verification/identification
// Returns: True if ok, false if no finger pressed
bool FPS_GT511C3_CaptureFinger(bool highquality) {
 
    unsigned char* Packetbytes;
    bool retval;
 
    if(UseSerialDebug)UART5_Write_Text("FPS - CaptureFinger\r\n");
    Command_Packet.Commands.Command = CaptureFinger;
    if(highquality) {
        Command_Packet_ParameterFromInt(1);
    }
    else {
        Command_Packet_ParameterFromInt(0);
    }
    
    Packetbytes = Command_Packet_GetPacketBytes();
    FPS_GT511C3_SendCommand(Packetbytes, 12);
    FPS_GT511C3_GetResponse();
    retval = Response_Packet.ACK;
 
    return retval;
}
 
void Enroll() {
     // Enroll test
 
    // find open enroll id
    int enrollid = 0;
    int bret, iret;
    bool usedid = TRUE;
    
    while(usedid == TRUE) {
        usedid = FPS_GT511C3_CheckEnrolled(enrollid);
        if (usedid == TRUE)enrollid++;
    }
    
    FPS_GT511C3_EnrollStart(enrollid);
 
    // enroll
    UART_Write_Text("Press finger to Enroll #");
    UART_Write_Text(enrollid);
    UART_Write_Text("\r\n");
    while(FPS_GT511C3_IsPressFinger() == FALSE)Delay_ms(100);
    bret = FPS_GT511C3_CaptureFinger(TRUE);
    iret = 0;
    
    if(bret != FALSE) {
            UART5_Write_Text("Remove finger\r\n");
            FPS_GT511C3_Enroll1();
            while(FPS_GT511C3_IsPressFinger() == TRUE)Delay_ms(100);
            UART5_Write_Text("Press same finger again\r\n");
            while(FPS_GT511C3_IsPressFinger() == FALSE)Delay_ms(100);
            bret = FPS_GT511C3_CaptureFinger(TRUE);
            
            if(bret != FALSE)
            {
                    UART5_Write_Text("Remove finger\r\n");
                    FPS_GT511C3_Enroll2();
                    while(FPS_GT511C3_IsPressFinger() == TRUE)Delay_ms(100);
                    UART5_Write_Text("Press same finger yet again\r\n");
                    while(FPS_GT511C3_IsPressFinger() == FALSE)Delay_ms(100);
                    bret = FPS_GT511C3_CaptureFinger(TRUE);
                    if (bret != FALSE)
                    {
                            UART5_Write_Text("Remove finger\r\n");
                            iret = FPS_GT511C3_Enroll3();
                            if (iret == 0)
                            {
                                    UART5_Write_Text("Enrolling Successfull\r\n");
                            }
                            else
                            {
                                    UART5_Write_Text("Enrolling Failed with error code:");
                                    UART5_Write_Text(iret);
                                    UART5_Write_Text("\r\n");
                            }
                    }
                    else UART5_Write_Text("Failed to capture third finger\r\n");
            }
            else UART5_Write_Text("Failed to capture second finger\r\n");
    }
    else UART5_Write_Text("Failed to capture first finger\r\n");
}
 
void main() {
 
    AD1PCFG = 0xFFFF;
    JTAGEN_bit = 0;
    
    Command_Packet.COMMAND_START_CODE_1 = 0x55;
    Command_Packet.COMMAND_START_CODE_2 = 0xAA;
    Command_Packet.COMMAND_DEVICE_ID_1 = 0x01;
    Command_Packet.COMMAND_DEVICE_ID_2 = 0x00;
    
    Response_Packet.COMMAND_START_CODE_1 = 0x55;
    Response_Packet.COMMAND_START_CODE_2 = 0xAA;
    Response_Packet.COMMAND_DEVICE_ID_1 = 0x01;
    Response_Packet.COMMAND_DEVICE_ID_2 = 0x00;
    
    UART5_Init(9600);
    Delay_ms(200);
    UART2_Init(9600);
    Delay_ms(200);
    
    U2IP0_bit = 0;                     // Set UART2 interrupt
    U2IP1_bit = 1;                     // Set interrupt priorities
    U2IP2_bit = 1;                     // Set UART2 interrupt to level 6
 
 
    U2RXIE_bit = 1;
    Delay_ms(200);
    U2RXIF_bit = 0;
    EnableInterrupts();       // Enable all interrupts
    
    UseSerialDebug = TRUE;
    
    UART5_Write_Text("UART5 Ready...");
    
    FPS_GT511C3_Open();
    Delay_ms(200);
    FPS_GT511C3_SetLED(1);
    Delay_ms(200);
 
    while(1) {
    
          Delay_ms(5000);
          Enroll();
    }
}



This is the code of one of the C++ functions. I want to do similar thing using C. That is I want to use Arrow Operator and do a similar coding.

C++ Code


Code C - [expand]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void FPS_GT511C3::Open()
{
    if (UseSerialDebug) Serial.println("FPS - Open");
    Command_Packet* cp = new Command_Packet();
    cp->Command = Command_Packet::Commands::Open;
    cp->Parameter[0] = 0x00;
    cp->Parameter[1] = 0x00;
    cp->Parameter[2] = 0x00;
    cp->Parameter[3] = 0x00;
    byte* packetbytes = cp->GetPacketBytes();
    SendCommand(packetbytes, 12);
    Response_Packet* rp = GetResponse();
    delete rp;
    delete packetbytes;
}

 
Last edited:

That's not possible in C.

1. an enum isn't a type, it's a list of constants. An enum value can be assigned to an integer type (char, int etc.). If you want to return an enum value by a function, the function must be defined with an integer return type.

2. Command_Packet and Response_Packet are structured variable definitions, not type definitions. You can't reference them to define other variables, except for instances of the outer level using the tag name. And you can't use a subentity of struct respectively typedef struct as a new type.

As suggested before, I would cut the C++ class definition into hierarchical typedefs, so you can easily access sub entities.

Don't try to put the enum definition into the struct, define it on it's own and use it where appropriate. Other than in C++, the enums are sharing a single global namespace, so each name must be unique.
 
Please show how to do that.

- - - Updated - - -

I changed the return type to unsigned int and it worked. But still the enrolling is not happening. Have to debug the code and see what is causing the problem. Maybe I have to use Serial Interrupt to receive the data.


Code C - [expand]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// parses bytes into one of the possible errors from the finger print scanner
//Response_Packet::ErrorCodes::Errors_Enum Response_Packet_ErrorCodes_ParseFromBytes(unsigned char high, unsigned char low)
unsigned int Response_Packet_ErrorCodes_ParseFromBytes(unsigned char high, unsigned char low) {
    Response_Packet.ErrorCodes.e = INVALID;
 
    if (high == 0x00)
    {
    }
    // grw 01/03/15 - replaced if clause with else clause for any non-zero high byte
    // if (high == 0x01)
    // {
    else {
        switch(low) {
            case 0x00: Response_Packet.ErrorCodes.e = NO_ERROR; break;
            case 0x01: Response_Packet.ErrorCodes.e = NACK_TIMEOUT; break;
            case 0x02: Response_Packet.ErrorCodes.e = NACK_INVALID_BAUDRATE; break;
            case 0x03: Response_Packet.ErrorCodes.e = NACK_INVALID_POS; break;
            case 0x04: Response_Packet.ErrorCodes.e = NACK_IS_NOT_USED; break;
            case 0x05: Response_Packet.ErrorCodes.e = NACK_IS_ALREADY_USED; break;
            case 0x06: Response_Packet.ErrorCodes.e = NACK_COMM_ERR; break;
            case 0x07: Response_Packet.ErrorCodes.e = NACK_VERIFY_FAILED; break;
            case 0x08: Response_Packet.ErrorCodes.e = NACK_IDENTIFY_FAILED; break;
            case 0x09: Response_Packet.ErrorCodes.e = NACK_DB_IS_FULL; break;
            case 0x0A: Response_Packet.ErrorCodes.e = NACK_DB_IS_EMPTY; break;
            case 0x0B: Response_Packet.ErrorCodes.e = NACK_TURN_ERR; break;
            case 0x0C: Response_Packet.ErrorCodes.e = NACK_BAD_FINGER; break;
            case 0x0D: Response_Packet.ErrorCodes.e = NACK_ENROLL_FAILED; break;
            case 0x0E: Response_Packet.ErrorCodes.e = NACK_IS_NOT_SUPPORTED; break;
            case 0x0F: Response_Packet.ErrorCodes.e = NACK_DEV_ERR; break;
            case 0x10: Response_Packet.ErrorCodes.e = NACK_CAPTURE_CANCELED; break;
            case 0x11: Response_Packet.ErrorCodes.e = NACK_INVALID_PARAM; break;
            case 0x12: Response_Packet.ErrorCodes.e = NACK_FINGER_IS_NOT_PRESSED; break;
        };
    }
 
    return Response_Packet.ErrorCodes.e;
}

 

I have a new problem.

I converted this piece of C++ Code to C code using Interrupts but I see that if I don't check for response then everything works fine but if I check for response then it doesn't work in hardware. Also I see that in the resp[] buffer the received bytes are one element shifted.

C++ Code


Code C - [expand]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// Gets the response to the command from the software serial channel (and waits for it)
Response_Packet* FPS_GT511C3::GetResponse()
{
    byte firstbyte = 0;
    bool done = false;
    _serial.listen();
    while (done == false)
    {
        firstbyte = (byte)_serial.read();
        if (firstbyte == Response_Packet::COMMAND_START_CODE_1)
        {
            done = true;
        }
    }
    byte* resp = new byte[12];
    resp[0] = firstbyte;
    for (int i=1; i < 12; i++)
    {
        while (_serial.available() == false) delay(10);
        resp[i]= (byte) _serial.read();
    }
    Response_Packet* rp = new Response_Packet(resp, UseSerialDebug);
    delete resp;
    if (UseSerialDebug) 
    {
        Serial.print("FPS - RECV: ");
        SendToSerial(rp->RawBytes, 12);
        Serial.println();
        Serial.println();
    }
    return rp;
};



Converted C Code


Code C - [expand]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
unsigned char resp[20];
unsigned char gfirstbyte = 0;
bool gdone = FALSE;
unsigned gIndex = 1;
 
 
// Gets the response to the command from the software serial channel (and waits for it)
void FPS_GT511C3_GetResponse() {
    /*
    unsigned char firstbyte = 0;
    bool done = FALSE;
    unsigned char resp[12];
    unsigned int i;
 
    while(done == FALSE) {
       firstbyte = (unsigned char)UART2_Read();
 
       if(firstbyte == Response_Packet.COMMAND_START_CODE_1) {
            done = TRUE;
       }
    }
 
    resp[0] = firstbyte;
 
    for(i = 1; i < 12; i++) {
          resp[i]= (unsigned char)UART2_Read();
    }
    */
    Delay_ms(2000);
    Response_Packet_Response_Packet(resp, UseSerialDebug);
 
    if(UseSerialDebug) {
         UART5_Write_Text("FPS - RECV: ");
         FPS_GT511C3_SendToSerial(Response_Packet.RawBytes, 12);
         UART5_Write_Text("\r\n");
         UART5_Write_Text("\r\n");
    }
}
 
 
 
 
void UART2() iv IVT_UART_2 ilevel 2 ics ICS_AUTO {
    
    if(gdone = TRUE) {
       resp[gIndex++]= UART2_Read();
    }
    else if(gdone == FALSE) {
       gfirstbyte = UART2_Read();
 
       if(gfirstbyte == Response_Packet.COMMAND_START_CODE_1) {
            resp[0] = gfirstbyte;
            gIndex = 1;
            gdone = TRUE;
       }
    }
    
    U2RXIF_bit = 0;
}
 
 
void FPS_GT511C3_Open() {
    unsigned char* Packetbytes;
    
    if(UseSerialDebug)UART5_Write_Text("FPS - Open\r\n");
    Command_Packet.Commands.Command = Open;
    Command_Packet.Parameter[0] = 0x00;
    Command_Packet.Parameter[1] = 0x00;
    Command_Packet.Parameter[2] = 0x00;
    Command_Packet.Parameter[3] = 0x00;
    Packetbytes = Command_Packet_GetPacketBytes();
    FPS_GT511C3_SendCommand(Packetbytes, 12);
    FPS_GT511C3_GetResponse();
    PrintResponseBytes(resp);
    ResetVars();
}
 
// Turns on or off the LED backlight
// Parameter: true turns on the backlight, false turns it off
// Returns: True if successful, false if not
bool FPS_GT511C3_SetLED(bool on) {
    unsigned char* Packetbytes;
    bool retval;
    
    Command_Packet.Commands.Command = CmosLed;
    
    if(on) {
       if(UseSerialDebug)UART5_Write_Text("FPS - LED on\r\n");
       Command_Packet.Parameter[0] = 0x01;
    }
    else {
       if(UseSerialDebug)UART5_Write_Text("FPS - LED off\r\n");
       Command_Packet.Parameter[0] = 0x00;
    }
    
    Command_Packet.Parameter[1] = 0x00;
    Command_Packet.Parameter[2] = 0x00;
    Command_Packet.Parameter[3] = 0x00;
    Packetbytes = Command_Packet_GetPacketBytes();
    FPS_GT511C3_SendCommand(Packetbytes, 12);
    FPS_GT511C3_GetResponse();
    ResetVars();
    retval = TRUE;
    if(Response_Packet.ACK == FALSE)retval = FALSE;
    return retval;
}




Latest Full Code is here.


Code C - [expand]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
#define bool unsigned char
#define uint8_t unsigned char
 
#define TRUE 1
#define FALSE 0
 
unsigned char resp[20];
unsigned char gfirstbyte = 0;
bool gdone = FALSE;
unsigned gIndex = 1;
 
bool UseSerialDebug;
 
//Command_Packet represents the 12 byte command that we send to the finger print scanner
 
struct Cmd_Packet {
    struct Cmds {
        enum Cmds_Enum {
              NotSet              = 0x00,                // Default value for enum. Scanner will return error if sent this.
              Open                = 0x01,                // Open Initialization
              Close               = 0x02,                // Close Termination
              UsbInternalCheck    = 0x03,                // UsbInternalCheck Check if the connected USB device is valid
              ChangeEBaudRate     = 0x04,                // ChangeBaudrate Change UART baud rate
              SetIAPMode          = 0x05,                // SetIAPMode Enter IAP Mode In this mode, FW Upgrade is available
              CmosLed             = 0x12,                // CmosLed Control CMOS LED
              GetEnrollCount      = 0x20,                // Get enrolled fingerprint count
              CheckEnrolled       = 0x21,                // Check whether the specified ID is already enrolled
              EnrollStart         = 0x22,                // Start an enrollment
              Enroll1             = 0x23,                // Make 1st template for an enrollment
              Enroll2             = 0x24,                // Make 2nd template for an enrollment
              Enroll3             = 0x25,                // Make 3rd template for an enrollment, merge three templates into one template, save merged template to the database
              IsPressFinger       = 0x26,                // Check if a finger is placed on the sensor
              DeleteID            = 0x40,                // Delete the fingerprint with the specified ID
              DeleteAll           = 0x41,                // Delete all fingerprints from the database
              Verify1_1           = 0x50,                // Verification of the capture fingerprint image with the specified ID
              Identify1_N         = 0x51,                // Identification of the capture fingerprint image with the database
              VerifyTemplate1_1   = 0x52,                // Verification of a fingerprint template with the specified ID
              IdentifyTemplate1_N = 0x53,                // Identification of a fingerprint template with the database
              CaptureFinger       = 0x60,                // Capture a fingerprint image(256x256) from the sensor
              MakeTemplate        = 0x61,                // Make template for transmission
              GetImage            = 0x62,                // Download the captured fingerprint image(256x256)
              GetRawImage         = 0x63,                // Capture & Download raw fingerprint image(320x240)
              GetTemplate         = 0x70,                // Download the template of the specified ID
              SetTemplate         = 0x71,                // Upload the template of the specified ID
              GetDatabaseStart    = 0x72,                // Start database download, obsolete
              GetDatabaseEnd      = 0x73,                // End database download, obsolete
              UpgradeFirmware     = 0x80,                // Not supported
              UpgradeISOCDImage   = 0x81,                // Not supported
              Ack                 = 0x30,                // Acknowledge.
              Nack                = 0x31                 // Non-acknowledge
         }Command;
    }Commands;
 
    unsigned char Parameter[4];                                                                // Parameter 4 bytes, changes meaning depending on command
 
    unsigned char COMMAND_START_CODE_1;        // Static byte to mark the beginning of a command packet        -        never changes
    unsigned char COMMAND_START_CODE_2;        // Static byte to mark the beginning of a command packet        -        never changes
    unsigned char COMMAND_DEVICE_ID_1;         // Device ID Byte 1 (lesser byte)                                                        -        theoretically never changes
    unsigned char COMMAND_DEVICE_ID_2;         // Device ID Byte 2 (greater byte)                                                        -        theoretically never changes
    unsigned char command[2];                  // Command 2 bytes
}Command_packet;
 
struct Resp_Packet {
    struct ErrCodes {
       enum Errs_Enum {
          NO_ERROR                    = 0x0000,        // Default value. no error
          NACK_TIMEOUT                = 0x1001,        // Obsolete, capture timeout
          NACK_INVALID_BAUDRATE       = 0x1002,        // Obsolete, Invalid serial baud rate
          NACK_INVALID_POS            = 0x1003,        // The specified ID is not between 0~199
          NACK_IS_NOT_USED            = 0x1004,        // The specified ID is not used
          NACK_IS_ALREADY_USED        = 0x1005,        // The specified ID is already used
          NACK_COMM_ERR               = 0x1006,        // Communication Error
          NACK_VERIFY_FAILED          = 0x1007,        // 1:1 Verification Failure
          NACK_IDENTIFY_FAILED        = 0x1008,        // 1:N Identification Failure
          NACK_DB_IS_FULL             = 0x1009,        // The database is full
          NACK_DB_IS_EMPTY            = 0x100A,        // The database is empty
          NACK_TURN_ERR               = 0x100B,        // Obsolete, Invalid order of the enrollment (The order was not as: EnrollStart -> Enroll1 -> Enroll2 -> Enroll3)
          NACK_BAD_FINGER             = 0x100C,        // Too bad fingerprint
          NACK_ENROLL_FAILED          = 0x100D,        // Enrollment Failure
          NACK_IS_NOT_SUPPORTED       = 0x100E,        // The specified command is not supported
          NACK_DEV_ERR                = 0x100F,        // Device Error, especially if Crypto-Chip is trouble
          NACK_CAPTURE_CANCELED       = 0x1010,        // Obsolete, The capturing is canceled
          NACK_INVALID_PARAM          = 0x1011,        // Invalid parameter
          NACK_FINGER_IS_NOT_PRESSED  = 0x1012,        // Finger is not pressed
          INVALID                     = 0XFFFF         // Used when parsing fails
       }Error, e;
 
 
    }ErrorCodes;
    
    //Response_Packet(unsigned char* buffer, bool UseSerialDebug);
    unsigned char RawBytes[12];
    unsigned char ParameterBytes[4];
    unsigned char ResponseBytes[2];
    bool ACK;
    unsigned char COMMAND_START_CODE_1;        // Static byte to mark the beginning of a command packet        -        never changes
    unsigned char COMMAND_START_CODE_2;        // Static byte to mark the beginning of a command packet        -        never changes
    unsigned char COMMAND_DEVICE_ID_1;        // Device ID Byte 1 (lesser byte)                                                        -        theoretically never changes
    unsigned char COMMAND_DEVICE_ID_2;        // Device ID Byte 2 (greater byte)                                                        -        theoretically never changes
 
}Response_Packet;
 
unsigned char* Command_Packet_GetPacketBytes();                                                        // returns the bytes to be transmitted
void Command_Packet_ParameterFromInt(int i);
unsigned int Command_Packet_CalculateChecksum();                                                // Checksum is calculated using byte addition
unsigned char Command_Packet_GetHighByte(unsigned int w);
unsigned char Command_Packet_GetLowByte(unsigned int w);
 
unsigned int Response_Packet_ErrorCodes_ParseFromBytes(unsigned char high, unsigned char low);
void Response_Packet_Response_Packet(unsigned char* buffer, bool UseSerialDebug);
 
int Response_Packet_IntFromParameter();
bool Response_Packet_CheckParsing(unsigned char b, unsigned char propervalue, unsigned char alternatevalue, char* varname, bool UseSerialDebug);
unsigned int Response_Packet_CalculateChecksum(unsigned char* buffer, int length);
unsigned char Response_Packet_GetHighByte(unsigned int w);
unsigned char Response_Packet_GetLowByte(unsigned int w);
 
//Initialises the device and gets ready for commands
void FPS_GT511C3_Open();
 
// Does not actually do anything (according to the datasheet)
// I implemented open, so had to do closed too... lol
void FPS_GT511C3_Close();
 
// Turns on or off the LED backlight
// LED must be on to see fingerprints
// Parameter: true turns on the backlight, false turns it off
// Returns: True if successful, false if not
bool FPS_GT511C3_SetLED(bool on);
 
// Changes the baud rate of the connection
// Parameter: 9600 - 115200
// Returns: True if success, false if invalid baud
// NOTE: Untested (don't have a logic level changer and a voltage divider is too slow)
bool FPS_GT511C3_ChangeBaudRate(int baud);
 
// Gets the number of enrolled fingerprints
// Return: The total number of enrolled fingerprints
int FPS_GT511C3_GetEnrollCount();
 
// checks to see if the ID number is in use or not
// Parameter: 0-199
// Return: True if the ID number is enrolled, false if not
bool FPS_GT511C3_CheckEnrolled(int id);
 
// Starts the Enrollment Process
// Parameter: 0-199
// Return:
//        0 - ACK
//        1 - Database is full
//        2 - Invalid Position
//        3 - Position(ID) is already used
int FPS_GT511C3_EnrollStart(int id);
 
// Gets the first scan of an enrollment
// Return:
//        0 - ACK
//        1 - Enroll Failed
//        2 - Bad finger
//        3 - ID in use
int FPS_GT511C3_Enroll1();
 
// Gets the Second scan of an enrollment
// Return:
//        0 - ACK
//        1 - Enroll Failed
//        2 - Bad finger
//        3 - ID in use
int FPS_GT511C3_Enroll2();
 
// Gets the Third scan of an enrollment
// Finishes Enrollment
// Return:
//        0 - ACK
//        1 - Enroll Failed
//        2 - Bad finger
//        3 - ID in use
int FPS_GT511C3_Enroll3();
 
// Checks to see if a finger is pressed on the FPS
// Return: true if finger pressed, false if not
bool FPS_GT511C3_IsPressFinger();
 
// Deletes the specified ID (enrollment) from the database
// Returns: true if successful, false if position invalid
bool FPS_GT511C3_DeleteID(int ID);
 
// Deletes all IDs (enrollments) from the database
// Returns: true if successful, false if db is empty
bool FPS_GT511C3_DeleteAll();
 
// Checks the currently pressed finger against a specific ID
// Parameter: 0-199 (id number to be checked)
// Returns:
//        0 - Verified OK (the correct finger)
//        1 - Invalid Position
//        2 - ID is not in use
//        3 - Verified FALSE (not the correct finger)
int FPS_GT511C3_Verify1_1(int id);
 
// Checks the currently pressed finger against all enrolled fingerprints
// Returns:
//        0-199: Verified against the specified ID (found, and here is the ID number)
//        200: Failed to find the fingerprint in the database
int FPS_GT511C3_Identify1_N();
 
// Captures the currently pressed finger into onboard ram
// Parameter: true for high quality image(slower), false for low quality image (faster)
// Generally, use high quality for enrollment, and low quality for verification/identification
// Returns: True if ok, false if no finger pressed
bool FPS_GT511C3_CaptureFinger(bool highquality);
 
//-= Not implemented commands =-
 
// Gets an image that is 258x202 (52116 bytes) and returns it in 407 Data_Packets
// Use StartDataDownload, and then GetNextDataPacket until done
// Returns: True (device confirming download starting)
// Not implemented due to memory restrictions on the arduino
// may revisit this if I find a need for it
//bool GetImage();
 
// Gets an image that is qvga 160x120 (19200 bytes) and returns it in 150 Data_Packets
// Use StartDataDownload, and then GetNextDataPacket until done
// Returns: True (device confirming download starting)
// Not implemented due to memory restrictions on the arduino
// may revisit this if I find a need for it
//bool GetRawImage();
 
// Gets a template from the fps (498 bytes) in 4 Data_Packets
// Use StartDataDownload, and then GetNextDataPacket until done
// Parameter: 0-199 ID number
// Returns:
//        0 - ACK Download starting
//        1 - Invalid position
//        2 - ID not used (no template to download
// Not implemented due to memory restrictions on the arduino
// may revisit this if I find a need for it
//int GetTemplate(int id);
 
// Uploads a template to the fps
// Parameter: the template (498 bytes)
// Parameter: the ID number to upload
// Parameter: Check for duplicate fingerprints already on fps
// Returns:
//        0-199 - ID duplicated
//        200 - Uploaded ok (no duplicate if enabled)
//        201 - Invalid position
//        202 - Communications error
//        203 - Device error
// Not implemented due to memory restrictions on the arduino
// may revisit this if I find a need for it
//int SetTemplate(byte* tmplt, int id, bool duplicateCheck);
 
// Commands that are not implemented (and why)
// VerifyTemplate1_1 - Couldn't find a good reason to implement this on an arduino
// IdentifyTemplate1_N - Couldn't find a good reason to implement this on an arduino
// MakeTemplate - Couldn't find a good reason to implement this on an arduino
// UsbInternalCheck - not implemented - Not valid config for arduino
// GetDatabaseStart - historical command, no longer supported
// GetDatabaseEnd - historical command, no longer supported
// UpgradeFirmware - Data Sheet says not supported
// UpgradeISOCDImage - Data Sheet says not supported
// SetIAPMode - for upgrading firmware (which is not supported)
// Ack and Nack        are listed as a commands for some unknown reason... not implemented
 
void FPS_GT511C3_serialPrintHex(unsigned char data_);
void FPS_GT511C3_SendToSerial(unsigned char data[], int length);
 
// resets the Data_Packet class, and gets ready to download
// Not implemented due to memory restrictions on the arduino
// may revisit this if I find a need for it
//void StartDataDownload();
 
// Returns the next data packet
// Not implemented due to memory restrictions on the arduino
// may revisit this if I find a need for it
//Data_Packet GetNextDataPacket();
 
void SendCommand(unsigned char cmd[], int length);
void GetResponse();
 
void ResetVars() {
    gfirstbyte = 0;
    gdone = FALSE;
    gIndex = 1;
}
 
unsigned char* Command_Packet_GetPacketBytes() {
    unsigned char packetbytes[12];
    unsigned int cmd, checksum;
    // update command before calculating checksum (important!)
    cmd = Command_packet.Commands.Command;
    Command_Packet.command[0] = Command_Packet_GetLowByte(cmd);
    Command_Packet.command[1] = Command_Packet_GetHighByte(cmd);
 
    checksum = Command_Packet_CalculateChecksum();
 
    packetbytes[0] = Command_Packet.COMMAND_START_CODE_1;
    packetbytes[1] = Command_Packet.COMMAND_START_CODE_2;
    packetbytes[2] = Command_Packet.COMMAND_DEVICE_ID_1;
    packetbytes[3] = Command_Packet.COMMAND_DEVICE_ID_2;
    packetbytes[4] = Command_Packet.Parameter[0];
    packetbytes[5] = Command_Packet.Parameter[1];
    packetbytes[6] = Command_Packet.Parameter[2];
    packetbytes[7] = Command_Packet.Parameter[3];
    packetbytes[8] = Command_Packet.command[0];
    packetbytes[9] = Command_Packet.command[1];
    packetbytes[10] = Command_Packet_GetLowByte(checksum);
    packetbytes[11] = Command_Packet_GetHighByte(checksum);
 
    return &packetbytes;
}
 
// Converts the int to bytes and puts them into the paramter array
void Command_Packet_ParameterFromInt(int i) {
    Command_Packet.Parameter[0] = (i & 0x000000ff);
    Command_Packet.Parameter[1] = (i & 0x0000ff00) >> 8;
    Command_Packet.Parameter[2] = (i & 0x00ff0000) >> 16;
    Command_Packet.Parameter[3] = (i & 0xff000000) >> 24;
}
 
// Returns the high byte from a word
unsigned char Command_Packet_GetHighByte(unsigned int w) {
    return (unsigned char)(w>>8)&0x00FF;
}
 
// Returns the low byte from a word
unsigned char Command_Packet_GetLowByte(unsigned int w) {
    return (unsigned char)w&0x00FF;
}
 
unsigned int Command_Packet_CalculateChecksum() {
    unsigned int w = 0;
 
    w += Command_Packet.COMMAND_START_CODE_1;
    w += Command_Packet.COMMAND_START_CODE_2;
    w += Command_Packet.COMMAND_DEVICE_ID_1;
    w += Command_Packet.COMMAND_DEVICE_ID_2;
    w += Command_Packet.Parameter[0];
    w += Command_Packet.Parameter[1];
    w += Command_Packet.Parameter[2];
    w += Command_Packet.Parameter[3];
    w += Command_Packet.command[0];
    w += Command_Packet.command[1];
 
    return w;
}
 
// parses bytes into one of the possible errors from the finger print scanner
//Response_Packet::ErrorCodes::Errors_Enum Response_Packet_ErrorCodes_ParseFromBytes(unsigned char high, unsigned char low)
unsigned int Response_Packet_ErrorCodes_ParseFromBytes(unsigned char high, unsigned char low) {
    Response_Packet.ErrorCodes.e = INVALID;
 
    if (high == 0x00)
    {
    }
    // grw 01/03/15 - replaced if clause with else clause for any non-zero high byte
    // if (high == 0x01)
    // {
    else {
        switch(low) {
            case 0x00: Response_Packet.ErrorCodes.e = NO_ERROR; break;
            case 0x01: Response_Packet.ErrorCodes.e = NACK_TIMEOUT; break;
            case 0x02: Response_Packet.ErrorCodes.e = NACK_INVALID_BAUDRATE; break;
            case 0x03: Response_Packet.ErrorCodes.e = NACK_INVALID_POS; break;
            case 0x04: Response_Packet.ErrorCodes.e = NACK_IS_NOT_USED; break;
            case 0x05: Response_Packet.ErrorCodes.e = NACK_IS_ALREADY_USED; break;
            case 0x06: Response_Packet.ErrorCodes.e = NACK_COMM_ERR; break;
            case 0x07: Response_Packet.ErrorCodes.e = NACK_VERIFY_FAILED; break;
            case 0x08: Response_Packet.ErrorCodes.e = NACK_IDENTIFY_FAILED; break;
            case 0x09: Response_Packet.ErrorCodes.e = NACK_DB_IS_FULL; break;
            case 0x0A: Response_Packet.ErrorCodes.e = NACK_DB_IS_EMPTY; break;
            case 0x0B: Response_Packet.ErrorCodes.e = NACK_TURN_ERR; break;
            case 0x0C: Response_Packet.ErrorCodes.e = NACK_BAD_FINGER; break;
            case 0x0D: Response_Packet.ErrorCodes.e = NACK_ENROLL_FAILED; break;
            case 0x0E: Response_Packet.ErrorCodes.e = NACK_IS_NOT_SUPPORTED; break;
            case 0x0F: Response_Packet.ErrorCodes.e = NACK_DEV_ERR; break;
            case 0x10: Response_Packet.ErrorCodes.e = NACK_CAPTURE_CANCELED; break;
            case 0x11: Response_Packet.ErrorCodes.e = NACK_INVALID_PARAM; break;
            case 0x12: Response_Packet.ErrorCodes.e = NACK_FINGER_IS_NOT_PRESSED; break;
        };
    }
 
    return Response_Packet.ErrorCodes.e;
}
 
// checks to see if the byte is the proper value, and logs it to the serial channel if not
bool Response_Packet_CheckParsing(unsigned char b, unsigned char propervalue, unsigned char alternatevalue, char* varname, bool UseSerialDebug) {
    bool retval;
    char str[22];
 
    retval = (b != propervalue) && (b != alternatevalue);
 
    if((UseSerialDebug) && (retval)) {
        UART5_Write_Text("Response_Packet parsing error \r\n");
        UART5_Write_Text(varname);
        UART5_Write_Text(" ");
        ByteToHex(propervalue, str);
        Ltrim(str);
        Rtrim(str);
        UART5_Write_Text(str);
        UART5_Write_Text(" || ");
        ByteToHex(alternatevalue, str);
        Ltrim(str);
        Rtrim(str);
        UART5_Write_Text(str);
        UART5_Write_Text(" != ");
        ByteToHex(b, str);
        Ltrim(str);
        Rtrim(str);
        UART5_Write_Text(str);
    }
}
 
void Response_Packet_Response_Packet(unsigned char* buffer, bool UseSerialDebug) {
 
    unsigned int checksum, i;
    unsigned char checksum_low;
    unsigned char checksum_high;
 
    Response_Packet_CheckParsing(buffer[0], Response_Packet.COMMAND_START_CODE_1, Response_Packet.COMMAND_START_CODE_1, "COMMAND_START_CODE_1", UseSerialDebug);
    Response_Packet_CheckParsing(buffer[1], Response_Packet.COMMAND_START_CODE_2, Response_Packet.COMMAND_START_CODE_2, "COMMAND_START_CODE_2", UseSerialDebug);
    Response_Packet_CheckParsing(buffer[2], Response_Packet.COMMAND_DEVICE_ID_1, Response_Packet.COMMAND_DEVICE_ID_1, "COMMAND_DEVICE_ID_1", UseSerialDebug);
    Response_Packet_CheckParsing(buffer[3], Response_Packet.COMMAND_DEVICE_ID_2, Response_Packet.COMMAND_DEVICE_ID_2, "COMMAND_DEVICE_ID_2", UseSerialDebug);
    Response_Packet_CheckParsing(buffer[8], 0x30, 0x31, "AckNak_LOW", UseSerialDebug);
    if(buffer[8] == 0x30)Response_Packet.ACK = TRUE; else Response_Packet.ACK = FALSE;
    Response_Packet_CheckParsing(buffer[9], 0x00, 0x00, "AckNak_HIGH", UseSerialDebug);
 
    checksum = Response_Packet_CalculateChecksum(buffer, 10);
    checksum_low = Response_Packet_GetLowByte(checksum);
    checksum_high = Response_Packet_GetHighByte(checksum);
    Response_Packet_CheckParsing(buffer[10], checksum_low, checksum_low, "Checksum_LOW", UseSerialDebug);
    Response_Packet_CheckParsing(buffer[11], checksum_high, checksum_high, "Checksum_HIGH", UseSerialDebug);
 
    Response_Packet.ErrorCodes.Error = Response_Packet_ErrorCodes_ParseFromBytes(buffer[5], buffer[4]);
 
    Response_Packet.ParameterBytes[0] = buffer[4];
    Response_Packet.ParameterBytes[1] = buffer[5];
    Response_Packet.ParameterBytes[2] = buffer[6];
    Response_Packet.ParameterBytes[3] = buffer[7];
    Response_Packet.ResponseBytes[0] = buffer[8];
    Response_Packet.ResponseBytes[1] = buffer[9];
 
    for(i = 0; i < 12; i++) {
        Response_Packet.RawBytes[i] = buffer[i];
    }
}
 
// Gets an int from the parameter bytes
int Response_Packet_IntFromParameter() {
    int retval = 0;
 
    retval = (retval << 8) + Response_Packet.ParameterBytes[3];
    retval = (retval << 8) + Response_Packet.ParameterBytes[2];
    retval = (retval << 8) + Response_Packet.ParameterBytes[1];
    retval = (retval << 8) + Response_Packet.ParameterBytes[0];
 
    return retval;
}
 
// calculates the checksum from the bytes in the Packet
unsigned int Response_Packet_CalculateChecksum(unsigned char* buffer, int length) {
    unsigned int checksum = 0;
    unsigned int i = 0;
    
    for(i = 0; i < length; i++) {
        checksum += buffer[i];
    }
 
    return checksum;
}
 
// Returns the high byte from a word
unsigned char Response_Packet_GetHighByte(unsigned int w) {
    return (unsigned char)(w>>8)&0x00FF;
}
 
// Returns the low byte from a word
unsigned char Response_Packet_GetLowByte(unsigned int w) {
    return (unsigned char)w&0x00FF;
}
 
void FPS_GT511C3_SendCommand(unsigned char cmd[], int length) {
    unsigned int i = 0;
 
    for(i = 0; i < length; i++) {
         UART2_Write(cmd[i]);
    }
 
    if(UseSerialDebug) {
        UART5_Write_Text("FPS - SEND: ");
        for(i = 0; i < length; i++) {
           UART5_Write(cmd[i]);
        }
 
        UART5_Write_Text("\r\n");
    }
}
 
// sends a byte to the serial debugger in the hex format we want EX "0F"
void FPS_GT511C3_serialPrintHex(unsigned char data_) {
    char tmp[16];
    ByteToHex(tmp, data_);
    Ltrim(tmp);
    Rtrim(tmp);
    UART5_Write_Text(tmp);
}
 
// sends the bye aray to the serial debugger in our hex format EX: "00 AF FF 10 00 13"
void FPS_GT511C3_SendToSerial(unsigned char data_[], int length) {
    bool first = TRUE;
    unsigned int i;
 
    UART5_Write_Text(""");
 
    for(i = 0; i < length; i++) {
       if(first)first = FALSE;
       else UART5_Write_Text(" ");
       FPS_GT511C3_serialPrintHex(data_[i]);
    }
 
    UART5_Write_Text(""");
}
 
void PrintResponseBytes(unsigned char *response) {
     unsigned int i = 0;
 
     for(i = 0; i < 12; i++) {
          FPS_GT511C3_serialPrintHex(response[i]);
     }
}
 
// Gets the response to the command from the software serial channel (and waits for it)
void FPS_GT511C3_GetResponse() {
    /*
    unsigned char firstbyte = 0;
    bool done = FALSE;
    unsigned char resp[12];
    unsigned int i;
 
    while(done == FALSE) {
       firstbyte = (unsigned char)UART2_Read();
 
       if(firstbyte == Response_Packet.COMMAND_START_CODE_1) {
            done = TRUE;
       }
    }
 
    resp[0] = firstbyte;
 
    for(i = 1; i < 12; i++) {
          resp[i]= (unsigned char)UART2_Read();
    }
    */
    Delay_ms(2000);
    Response_Packet_Response_Packet(resp, UseSerialDebug);
 
    if(UseSerialDebug) {
         UART5_Write_Text("FPS - RECV: ");
         FPS_GT511C3_SendToSerial(Response_Packet.RawBytes, 12);
         UART5_Write_Text("\r\n");
         UART5_Write_Text("\r\n");
    }
}
 
bool FPS_GT511C3_ChangeBaudRate(int baud) {
    unsigned char* Packetbytes;
    bool retval;
    
    if((baud == 9600) || (baud == 19200) || (baud == 38400) || (baud == 57600) || (baud == 115200)) {
        if(UseSerialDebug)UART5_Write_Text("FPS - ChangeBaudRate\r\n");
        Command_Packet.Commands.Command = Open;
        Command_Packet_ParameterFromInt(baud);
        Packetbytes = Command_Packet_GetPacketBytes();
        FPS_GT511C3_SendCommand(Packetbytes, 12);
        FPS_GT511C3_GetResponse();
        ResetVars();
        retval = Response_Packet.ACK;
        
        if(retval) {
            UART2_Init(baud);
            Delay_ms(200);
        }
 
        return retval;
    }
    
    return FALSE;
}
 
void FPS_GT511C3_Open() {
    unsigned char* Packetbytes;
    
    if(UseSerialDebug)UART5_Write_Text("FPS - Open\r\n");
    Command_Packet.Commands.Command = Open;
    Command_Packet.Parameter[0] = 0x00;
    Command_Packet.Parameter[1] = 0x00;
    Command_Packet.Parameter[2] = 0x00;
    Command_Packet.Parameter[3] = 0x00;
    Packetbytes = Command_Packet_GetPacketBytes();
    FPS_GT511C3_SendCommand(Packetbytes, 12);
    FPS_GT511C3_GetResponse();
    PrintResponseBytes(resp);
    ResetVars();
}
 
// Turns on or off the LED backlight
// Parameter: true turns on the backlight, false turns it off
// Returns: True if successful, false if not
bool FPS_GT511C3_SetLED(bool on) {
    unsigned char* Packetbytes;
    bool retval;
    
    Command_Packet.Commands.Command = CmosLed;
    
    if(on) {
       if(UseSerialDebug)UART5_Write_Text("FPS - LED on\r\n");
       Command_Packet.Parameter[0] = 0x01;
    }
    else {
       if(UseSerialDebug)UART5_Write_Text("FPS - LED off\r\n");
       Command_Packet.Parameter[0] = 0x00;
    }
    
    Command_Packet.Parameter[1] = 0x00;
    Command_Packet.Parameter[2] = 0x00;
    Command_Packet.Parameter[3] = 0x00;
    Packetbytes = Command_Packet_GetPacketBytes();
    FPS_GT511C3_SendCommand(Packetbytes, 12);
    FPS_GT511C3_GetResponse();
    ResetVars();
    retval = TRUE;
    if(Response_Packet.ACK == FALSE)retval = FALSE;
    return retval;
}
 
// Gets the number of enrolled fingerprints
// Return: The total number of enrolled fingerprints
int FPS_GT511C3_GetEnrollCount() {
    unsigned char* Packetbytes;
    int retval;
    
    if(UseSerialDebug)UART5_Write_Text("FPS - GetEnrolledCount\r\n");
    Command_Packet.Commands.Command = GetEnrollCount;
    Command_Packet.Parameter[0] = 0x00;
    Command_Packet.Parameter[1] = 0x00;
    Command_Packet.Parameter[2] = 0x00;
    Command_Packet.Parameter[3] = 0x00;
    Packetbytes = Command_Packet_GetPacketBytes();
    FPS_GT511C3_SendCommand(Packetbytes, 12);
    FPS_GT511C3_GetResponse();
    ResetVars();
 
    retval = Response_Packet_IntFromParameter();
    return retval;
}
 
// checks to see if the ID number is in use or not
// Parameter: 0-199
// Return: True if the ID number is enrolled, false if not
bool FPS_GT511C3_CheckEnrolled(int id) {
    unsigned char* Packetbytes;
    bool retval;
    
    if(UseSerialDebug)UART5_Write_Text("FPS - CheckEnrolled\r\n");
    Command_Packet.Commands.Command = CheckEnrolled;
    Command_Packet_ParameterFromInt(id);
    Packetbytes = Command_Packet_GetPacketBytes();
    FPS_GT511C3_SendCommand(Packetbytes, 12);
    FPS_GT511C3_GetResponse();
    ResetVars();
    retval = FALSE;
    retval = Response_Packet.ACK;
    return retval;
}
 
// Starts the Enrollment Process
// Parameter: 0-199
// Return:
//        0 - ACK
//        1 - Database is full
//        2 - Invalid Position
//        3 - Position(ID) is already used
int FPS_GT511C3_EnrollStart(int id) {
    unsigned char* Packetbytes;
    int retval;
    
    if(UseSerialDebug)UART5_Write_Text("FPS - EnrollStart\r\n");
    Command_Packet.Commands.Command = EnrollStart;
    Command_Packet_ParameterFromInt(id);
    Packetbytes = Command_Packet_GetPacketBytes();
    FPS_GT511C3_SendCommand(Packetbytes, 12);
    FPS_GT511C3_GetResponse();
    ResetVars();
    retval = 0;
 
    if(Response_Packet.ACK == FALSE)
    {
         if(Response_Packet.ErrorCodes.Error == NACK_DB_IS_FULL)retval = 1;
         if(Response_Packet.ErrorCodes.Error == NACK_INVALID_POS)retval = 2;
         if(Response_Packet.ErrorCodes.Error == NACK_IS_ALREADY_USED)retval = 3;
    }
 
    return retval;
}
 
// Gets the first scan of an enrollment
// Return:
//        0 - ACK
//        1 - Enroll Failed
//        2 - Bad finger
//        3 - ID in use
int FPS_GT511C3_Enroll1() {
    unsigned char* Packetbytes;
    int retval;
 
    if(UseSerialDebug)UART5_Write_Text("FPS - Enroll1\r\n");
    Command_Packet.Commands.Command = Enroll1;
    Packetbytes = Command_Packet_GetPacketBytes();
    FPS_GT511C3_SendCommand(Packetbytes, 12);
    FPS_GT511C3_GetResponse();
    ResetVars();
    retval = Response_Packet_IntFromParameter();
    
    if(retval < 200) retval = 3; else retval = 0;
 
    if(Response_Packet.ACK == FALSE)
    {
        if(Response_Packet.ErrorCodes.Error == NACK_ENROLL_FAILED)retval = 1;
        if(Response_Packet.ErrorCodes.Error == NACK_BAD_FINGER)retval = 2;
    }
 
 
    if(Response_Packet.ACK) return 0; else return retval;
}
 
// Gets the Second scan of an enrollment
// Return:
//        0 - ACK
//        1 - Enroll Failed
//        2 - Bad finger
//        3 - ID in use
int FPS_GT511C3_Enroll2() {
    unsigned char* Packetbytes;
    int retval;
 
    if(UseSerialDebug)UART5_Write_Text("FPS - Enroll1\r\n");
    Command_Packet.Commands.Command = Enroll2;
    Packetbytes = Command_Packet_GetPacketBytes();
    FPS_GT511C3_SendCommand(Packetbytes, 12);
    FPS_GT511C3_GetResponse();
    ResetVars();
    retval = Response_Packet_IntFromParameter();
 
    if(retval < 200) retval = 3; else retval = 0;
 
    if(Response_Packet.ACK == FALSE)
    {
        if(Response_Packet.ErrorCodes.Error == NACK_ENROLL_FAILED)retval = 1;
        if(Response_Packet.ErrorCodes.Error == NACK_BAD_FINGER)retval = 2;
    }
 
 
    if(Response_Packet.ACK) return 0; else return retval;
}
 
// Gets the Third scan of an enrollment
// Finishes Enrollment
// Return:
//        0 - ACK
//        1 - Enroll Failed
//        2 - Bad finger
//        3 - ID in use
int FPS_GT511C3_Enroll3() {
    unsigned char* Packetbytes;
    int retval;
 
    if(UseSerialDebug)UART5_Write_Text("FPS - Enroll1\r\n");
    Command_Packet.Commands.Command = Enroll3;
    Packetbytes = Command_Packet_GetPacketBytes();
    FPS_GT511C3_SendCommand(Packetbytes, 12);
    FPS_GT511C3_GetResponse();
    ResetVars();
    retval = Response_Packet_IntFromParameter();
 
    if(retval < 200) retval = 3; else retval = 0;
 
    if(Response_Packet.ACK == FALSE)
    {
        if(Response_Packet.ErrorCodes.Error == NACK_ENROLL_FAILED)retval = 1;
        if(Response_Packet.ErrorCodes.Error == NACK_BAD_FINGER)retval = 2;
    }
 
 
    if(Response_Packet.ACK) return 0; else return retval;
}
 
// Checks to see if a finger is pressed on the FPS
// Return: true if finger pressed, false if not
bool FPS_GT511C3_IsPressFinger() {
    unsigned char* Packetbytes;
    bool retval;
    int pval;
    
    if(UseSerialDebug)UART5_Write_Text("FPS - IsPressFinger\r\n");
    Command_Packet.Commands.Command = IsPressFinger;
    Packetbytes = Command_Packet_GetPacketBytes();
    FPS_GT511C3_SendCommand(Packetbytes, 12);
    FPS_GT511C3_GetResponse();
    ResetVars();
    retval = FALSE;
    pval = Response_Packet.ParameterBytes[0];
    pval += Response_Packet.ParameterBytes[1];
    pval += Response_Packet.ParameterBytes[2];
    pval += Response_Packet.ParameterBytes[3];
    
    if(pval == 0)retval = TRUE;
 
    return retval;
}
 
// Deletes the specified ID (enrollment) from the database
// Parameter: 0-199 (id number to be deleted)
// Returns: true if successful, false if position invalid
bool FPS_GT511C3_DeleteID(int id) {
    unsigned char* Packetbytes;
    bool retval;
 
    if(UseSerialDebug)UART5_Write_Text("FPS - DeleteID\r\n");
    Command_Packet.Commands.Command = DeleteID;
    Command_Packet_ParameterFromInt(id);
    Packetbytes = Command_Packet_GetPacketBytes();
    FPS_GT511C3_SendCommand(Packetbytes, 12);
    FPS_GT511C3_GetResponse();
    ResetVars();
    retval = Response_Packet.ACK;
 
    return retval;
}
 
// Deletes all IDs (enrollments) from the database
// Returns: true if successful, false if db is empty
bool FPS_GT511C3_DeleteAll() {
    unsigned char* Packetbytes;
    bool retval;
    
    if(UseSerialDebug)UART5_Write_Text("FPS - DeleteAll\r\n");
    Command_Packet.Commands.Command = DeleteAll;
    Packetbytes = Command_Packet_GetPacketBytes();
    FPS_GT511C3_SendCommand(Packetbytes, 12);
    FPS_GT511C3_GetResponse();
    ResetVars();
    retval = Response_Packet.ACK;
 
    return retval;
}
 
// Checks the currently pressed finger against a specific ID
// Parameter: 0-199 (id number to be checked)
// Returns:
//        0 - Verified OK (the correct finger)
//        1 - Invalid Position
//        2 - ID is not in use
//        3 - Verified FALSE (not the correct finger)
int FPS_GT511C3_Verify1_1(int id) {
    unsigned char* Packetbytes;
    int retval;
    
    if(UseSerialDebug)UART5_Write_Text("FPS - Verify1_1\r\n");
    Command_Packet.Commands.Command = Verify1_1;
    Command_Packet_ParameterFromInt(id);
    Packetbytes = Command_Packet_GetPacketBytes();
    FPS_GT511C3_SendCommand(Packetbytes, 12);
    FPS_GT511C3_GetResponse();
    ResetVars();
    retval = 0;
    
 
    if(Response_Packet.ACK == FALSE)
    {
          retval = 3; // grw 01/03/15 - set default value of not verified before assignment
          
          if (Response_Packet.ErrorCodes.Error == NACK_INVALID_POS)retval = 1;
          if (Response_Packet.ErrorCodes.Error == NACK_IS_NOT_USED) retval = 2;
          if (Response_Packet.ErrorCodes.Error == NACK_VERIFY_FAILED) retval = 3;
    }
 
 
    return retval;
}
 
// Checks the currently pressed finger against all enrolled fingerprints
// Returns:
//        0-199: Verified against the specified ID (found, and here is the ID number)
//        200: Failed to find the fingerprint in the database
int FPS_GT511C3_Identify1_N() {
    unsigned char* Packetbytes;
    int retval;
    
    if(UseSerialDebug)UART5_Write_Text("FPS - Identify1_N\r\n");
    Command_Packet.Commands.Command = Identify1_N;
    Packetbytes = Command_Packet_GetPacketBytes();
    FPS_GT511C3_SendCommand(Packetbytes, 12);
    FPS_GT511C3_GetResponse();
    ResetVars();
    retval = Response_Packet_IntFromParameter();
    
    if(retval > 200) retval = 200;
 
    return retval;
}
 
// Captures the currently pressed finger into onboard ram use this prior to other commands
// Parameter: true for high quality image(slower), false for low quality image (faster)
// Generally, use high quality for enrollment, and low quality for verification/identification
// Returns: True if ok, false if no finger pressed
bool FPS_GT511C3_CaptureFinger(bool highquality) {
 
    unsigned char* Packetbytes;
    bool retval;
 
    if(UseSerialDebug)UART5_Write_Text("FPS - CaptureFinger\r\n");
    Command_Packet.Commands.Command = CaptureFinger;
    if(highquality) {
        Command_Packet_ParameterFromInt(1);
    }
    else {
        Command_Packet_ParameterFromInt(0);
    }
    
    Packetbytes = Command_Packet_GetPacketBytes();
    FPS_GT511C3_SendCommand(Packetbytes, 12);
    FPS_GT511C3_GetResponse();
    ResetVars();
    retval = Response_Packet.ACK;
 
    return retval;
}
 
void Enroll() {
     // Enroll test
 
    // find open enroll id
    int enrollid = 0;
    int bret, iret;
    bool usedid = TRUE;
    
    while(usedid == TRUE) {
        usedid = FPS_GT511C3_CheckEnrolled(enrollid);
        if (usedid == TRUE)enrollid++;
    }
    
    FPS_GT511C3_EnrollStart(enrollid);
 
    // enroll
    UART_Write_Text("Press finger to Enroll #");
    UART_Write_Text(enrollid);
    UART_Write_Text("\r\n");
    while(FPS_GT511C3_IsPressFinger() == FALSE)Delay_ms(100);
    bret = FPS_GT511C3_CaptureFinger(TRUE);
    iret = 0;
    
    if(bret != FALSE) {
            UART5_Write_Text("Remove finger\r\n");
            FPS_GT511C3_Enroll1();
            while(FPS_GT511C3_IsPressFinger() == TRUE)Delay_ms(100);
            UART5_Write_Text("Press same finger again\r\n");
            while(FPS_GT511C3_IsPressFinger() == FALSE)Delay_ms(100);
            bret = FPS_GT511C3_CaptureFinger(TRUE);
            
            if(bret != FALSE)
            {
                    UART5_Write_Text("Remove finger\r\n");
                    FPS_GT511C3_Enroll2();
                    while(FPS_GT511C3_IsPressFinger() == TRUE)Delay_ms(100);
                    UART5_Write_Text("Press same finger yet again\r\n");
                    while(FPS_GT511C3_IsPressFinger() == FALSE)Delay_ms(100);
                    bret = FPS_GT511C3_CaptureFinger(TRUE);
                    if (bret != FALSE)
                    {
                            UART5_Write_Text("Remove finger\r\n");
                            iret = FPS_GT511C3_Enroll3();
                            if (iret == 0)
                            {
                                    UART5_Write_Text("Enrolling Successfull\r\n");
                            }
                            else
                            {
                                    UART5_Write_Text("Enrolling Failed with error code:");
                                    UART5_Write_Text(iret);
                                    UART5_Write_Text("\r\n");
                            }
                    }
                    else UART5_Write_Text("Failed to capture third finger\r\n");
            }
            else UART5_Write_Text("Failed to capture second finger\r\n");
    }
    else UART5_Write_Text("Failed to capture first finger\r\n");
}
 
void UART2() iv IVT_UART_2 ilevel 2 ics ICS_AUTO {
    
    if(gdone = TRUE) {
       resp[gIndex++]= UART2_Read();
    }
    else if(gdone == FALSE) {
       gfirstbyte = UART2_Read();
 
       if(gfirstbyte == Response_Packet.COMMAND_START_CODE_1) {
            resp[0] = gfirstbyte;
            gIndex = 1;
            gdone = TRUE;
       }
    }
    
    U2RXIF_bit = 0;
}
 
void main() {
 
    AD1PCFG = 0xFFFF;
    JTAGEN_bit = 0;
    
    TRISB = 0x00000000;
    
    
    Command_Packet.COMMAND_START_CODE_1 = 0x55;
    Command_Packet.COMMAND_START_CODE_2 = 0xAA;
    Command_Packet.COMMAND_DEVICE_ID_1 = 0x01;
    Command_Packet.COMMAND_DEVICE_ID_2 = 0x00;
    
    Response_Packet.COMMAND_START_CODE_1 = 0x55;
    Response_Packet.COMMAND_START_CODE_2 = 0xAA;
    Response_Packet.COMMAND_DEVICE_ID_1 = 0x01;
    Response_Packet.COMMAND_DEVICE_ID_2 = 0x00;
    
    UART5_Init(9600);
    Delay_ms(200);
    UART2_Init(9600);
    Delay_ms(200);
    
    U2IP0_bit = 0;                     // Set UART2 interrupt
    U2IP1_bit = 1;                     // Set interrupt priorities
    U2IP2_bit = 1;                     // Set UART2 interrupt to level 6
 
 
    U2RXIE_bit = 1;
    Delay_ms(200);
    U2RXIF_bit = 0;
    EnableInterrupts();       // Enable all interrupts
    
    UseSerialDebug = TRUE;
    
    UART5_Write_Text("UART5 Ready...");
    
    FPS_GT511C3_Open();
    Delay_ms(200);
 
    while(1) {
    
          Delay_ms(2000);
          //Enroll();
          FPS_GT511C3_SetLED(1);
          Delay_ms(2000);
          FPS_GT511C3_SetLED(0);
    }
}





Screenshot showing the debug. You can see that resp[] array elements are 1 byte shifted and doesn't match with the data in the below function.


Code C - [expand]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
void Response_Packet_Response_Packet(unsigned char* buffer, bool UseSerialDebug) {
 
    unsigned int checksum, i;
    unsigned char checksum_low;
    unsigned char checksum_high;
 
    Response_Packet_CheckParsing(buffer[0], Response_Packet.COMMAND_START_CODE_1, Response_Packet.COMMAND_START_CODE_1, "COMMAND_START_CODE_1", UseSerialDebug);
    Response_Packet_CheckParsing(buffer[1], Response_Packet.COMMAND_START_CODE_2, Response_Packet.COMMAND_START_CODE_2, "COMMAND_START_CODE_2", UseSerialDebug);
    Response_Packet_CheckParsing(buffer[2], Response_Packet.COMMAND_DEVICE_ID_1, Response_Packet.COMMAND_DEVICE_ID_1, "COMMAND_DEVICE_ID_1", UseSerialDebug);
    Response_Packet_CheckParsing(buffer[3], Response_Packet.COMMAND_DEVICE_ID_2, Response_Packet.COMMAND_DEVICE_ID_2, "COMMAND_DEVICE_ID_2", UseSerialDebug);
    Response_Packet_CheckParsing(buffer[8], 0x30, 0x31, "AckNak_LOW", UseSerialDebug);
    if(buffer[8] == 0x30)Response_Packet.ACK = TRUE; else Response_Packet.ACK = FALSE;
    Response_Packet_CheckParsing(buffer[9], 0x00, 0x00, "AckNak_HIGH", UseSerialDebug);
 
    checksum = Response_Packet_CalculateChecksum(buffer, 10);
    checksum_low = Response_Packet_GetLowByte(checksum);
    checksum_high = Response_Packet_GetHighByte(checksum);
    Response_Packet_CheckParsing(buffer[10], checksum_low, checksum_low, "Checksum_LOW", UseSerialDebug);
    Response_Packet_CheckParsing(buffer[11], checksum_high, checksum_high, "Checksum_HIGH", UseSerialDebug);
 
    Response_Packet.ErrorCodes.Error = Response_Packet_ErrorCodes_ParseFromBytes(buffer[5], buffer[4]);
 
    Response_Packet.ParameterBytes[0] = buffer[4];
    Response_Packet.ParameterBytes[1] = buffer[5];
    Response_Packet.ParameterBytes[2] = buffer[6];
    Response_Packet.ParameterBytes[3] = buffer[7];
    Response_Packet.ResponseBytes[0] = buffer[8];
    Response_Packet.ResponseBytes[1] = buffer[9];
 
    for(i = 0; i < 12; i++) {
        Response_Packet.RawBytes[i] = buffer[i];
    }
}



Also in the GetResponse() function it is not executing the below function.


Code C - [expand]
1
FPS_GT511C3_SendToSerial(Response_Packet.RawBytes, 12);



This is the piece of code inside GetResponse() function.


Code C - [expand]
1
2
3
4
5
6
if(UseSerialDebug) {
         UART5_Write_Text("FPS - RECV: ");
         FPS_GT511C3_SendToSerial(Response_Packet.RawBytes, 12);
         UART5_Write_Text("\r\n");
         UART5_Write_Text("\r\n");
    }



You can see in the screenshot that it is printing "FPS - RECV: ". But after that it is not printing 12 rawbytes.

- - - Updated - - -

Here is the debug showing that it is working if I don't check for response. To do an enroll I have to get the response thing working.
 

Attachments

  • FPS Test.png
    FPS Test.png
    15.2 KB · Views: 88
  • FPS Test 1.png
    FPS Test 1.png
    9.8 KB · Views: 87
Last edited:

This is my latest code. See the screenshot of Termite Serial Terminal Software. It shows what is happening. I don't understand why the bytes in resp[] array are 1 element shifted. You can see at the end of each reception it prints the received bytes.


Code C - [expand]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
#define bool unsigned char
#define uint8_t unsigned char
 
#define TRUE 1
#define FALSE 0
 
unsigned char resp[20];
unsigned char gfirstbyte = 0;
bool gdone = FALSE;
unsigned gIndex = 1;
 
bool UseSerialDebug;
 
//Command_Packet represents the 12 byte command that we send to the finger print scanner
 
struct Cmd_Packet {
    struct Cmds {
        enum Cmds_Enum {
              NotSet              = 0x00,                // Default value for enum. Scanner will return error if sent this.
              Open                = 0x01,                // Open Initialization
              Close               = 0x02,                // Close Termination
              UsbInternalCheck    = 0x03,                // UsbInternalCheck Check if the connected USB device is valid
              ChangeEBaudRate     = 0x04,                // ChangeBaudrate Change UART baud rate
              SetIAPMode          = 0x05,                // SetIAPMode Enter IAP Mode In this mode, FW Upgrade is available
              CmosLed             = 0x12,                // CmosLed Control CMOS LED
              GetEnrollCount      = 0x20,                // Get enrolled fingerprint count
              CheckEnrolled       = 0x21,                // Check whether the specified ID is already enrolled
              EnrollStart         = 0x22,                // Start an enrollment
              Enroll1             = 0x23,                // Make 1st template for an enrollment
              Enroll2             = 0x24,                // Make 2nd template for an enrollment
              Enroll3             = 0x25,                // Make 3rd template for an enrollment, merge three templates into one template, save merged template to the database
              IsPressFinger       = 0x26,                // Check if a finger is placed on the sensor
              DeleteID            = 0x40,                // Delete the fingerprint with the specified ID
              DeleteAll           = 0x41,                // Delete all fingerprints from the database
              Verify1_1           = 0x50,                // Verification of the capture fingerprint image with the specified ID
              Identify1_N         = 0x51,                // Identification of the capture fingerprint image with the database
              VerifyTemplate1_1   = 0x52,                // Verification of a fingerprint template with the specified ID
              IdentifyTemplate1_N = 0x53,                // Identification of a fingerprint template with the database
              CaptureFinger       = 0x60,                // Capture a fingerprint image(256x256) from the sensor
              MakeTemplate        = 0x61,                // Make template for transmission
              GetImage            = 0x62,                // Download the captured fingerprint image(256x256)
              GetRawImage         = 0x63,                // Capture & Download raw fingerprint image(320x240)
              GetTemplate         = 0x70,                // Download the template of the specified ID
              SetTemplate         = 0x71,                // Upload the template of the specified ID
              GetDatabaseStart    = 0x72,                // Start database download, obsolete
              GetDatabaseEnd      = 0x73,                // End database download, obsolete
              UpgradeFirmware     = 0x80,                // Not supported
              UpgradeISOCDImage   = 0x81,                // Not supported
              Ack                 = 0x30,                // Acknowledge.
              Nack                = 0x31                 // Non-acknowledge
         }Command;
    }Commands;
 
    unsigned char Parameter[4];                                                                // Parameter 4 bytes, changes meaning depending on command
 
    unsigned char COMMAND_START_CODE_1;        // Static byte to mark the beginning of a command packet        -        never changes
    unsigned char COMMAND_START_CODE_2;        // Static byte to mark the beginning of a command packet        -        never changes
    unsigned char COMMAND_DEVICE_ID_1;         // Device ID Byte 1 (lesser byte)                                                        -        theoretically never changes
    unsigned char COMMAND_DEVICE_ID_2;         // Device ID Byte 2 (greater byte)                                                        -        theoretically never changes
    unsigned char command[2];                  // Command 2 bytes
}Command_packet;
 
struct Resp_Packet {
    struct ErrCodes {
       enum Errs_Enum {
          NO_ERROR                    = 0x0000,        // Default value. no error
          NACK_TIMEOUT                = 0x1001,        // Obsolete, capture timeout
          NACK_INVALID_BAUDRATE       = 0x1002,        // Obsolete, Invalid serial baud rate
          NACK_INVALID_POS            = 0x1003,        // The specified ID is not between 0~199
          NACK_IS_NOT_USED            = 0x1004,        // The specified ID is not used
          NACK_IS_ALREADY_USED        = 0x1005,        // The specified ID is already used
          NACK_COMM_ERR               = 0x1006,        // Communication Error
          NACK_VERIFY_FAILED          = 0x1007,        // 1:1 Verification Failure
          NACK_IDENTIFY_FAILED        = 0x1008,        // 1:N Identification Failure
          NACK_DB_IS_FULL             = 0x1009,        // The database is full
          NACK_DB_IS_EMPTY            = 0x100A,        // The database is empty
          NACK_TURN_ERR               = 0x100B,        // Obsolete, Invalid order of the enrollment (The order was not as: EnrollStart -> Enroll1 -> Enroll2 -> Enroll3)
          NACK_BAD_FINGER             = 0x100C,        // Too bad fingerprint
          NACK_ENROLL_FAILED          = 0x100D,        // Enrollment Failure
          NACK_IS_NOT_SUPPORTED       = 0x100E,        // The specified command is not supported
          NACK_DEV_ERR                = 0x100F,        // Device Error, especially if Crypto-Chip is trouble
          NACK_CAPTURE_CANCELED       = 0x1010,        // Obsolete, The capturing is canceled
          NACK_INVALID_PARAM          = 0x1011,        // Invalid parameter
          NACK_FINGER_IS_NOT_PRESSED  = 0x1012,        // Finger is not pressed
          INVALID                     = 0XFFFF         // Used when parsing fails
       }Error, e;
 
 
    }ErrorCodes;
    
    //Response_Packet(unsigned char* buffer, bool UseSerialDebug);
    unsigned char RawBytes[12];
    unsigned char ParameterBytes[4];
    unsigned char ResponseBytes[2];
    bool ACK;
    unsigned char COMMAND_START_CODE_1;        // Static byte to mark the beginning of a command packet        -        never changes
    unsigned char COMMAND_START_CODE_2;        // Static byte to mark the beginning of a command packet        -        never changes
    unsigned char COMMAND_DEVICE_ID_1;        // Device ID Byte 1 (lesser byte)                                                        -        theoretically never changes
    unsigned char COMMAND_DEVICE_ID_2;        // Device ID Byte 2 (greater byte)                                                        -        theoretically never changes
 
}Response_Packet;
 
unsigned char* Command_Packet_GetPacketBytes();                                                        // returns the bytes to be transmitted
void Command_Packet_ParameterFromInt(int i);
unsigned int Command_Packet_CalculateChecksum();                                                // Checksum is calculated using byte addition
unsigned char Command_Packet_GetHighByte(unsigned int w);
unsigned char Command_Packet_GetLowByte(unsigned int w);
 
unsigned int Response_Packet_ErrorCodes_ParseFromBytes(unsigned char high, unsigned char low);
void Response_Packet_Response_Packet(unsigned char* buffer, bool UseSerialDebug);
 
int Response_Packet_IntFromParameter();
bool Response_Packet_CheckParsing(unsigned char b, unsigned char propervalue, unsigned char alternatevalue, char* varname, bool UseSerialDebug);
unsigned int Response_Packet_CalculateChecksum(unsigned char* buffer, int length);
unsigned char Response_Packet_GetHighByte(unsigned int w);
unsigned char Response_Packet_GetLowByte(unsigned int w);
 
//Initialises the device and gets ready for commands
void FPS_GT511C3_Open();
 
// Does not actually do anything (according to the datasheet)
// I implemented open, so had to do closed too... lol
void FPS_GT511C3_Close();
 
// Turns on or off the LED backlight
// LED must be on to see fingerprints
// Parameter: true turns on the backlight, false turns it off
// Returns: True if successful, false if not
bool FPS_GT511C3_SetLED(bool on);
 
// Changes the baud rate of the connection
// Parameter: 9600 - 115200
// Returns: True if success, false if invalid baud
// NOTE: Untested (don't have a logic level changer and a voltage divider is too slow)
bool FPS_GT511C3_ChangeBaudRate(int baud);
 
// Gets the number of enrolled fingerprints
// Return: The total number of enrolled fingerprints
int FPS_GT511C3_GetEnrollCount();
 
// checks to see if the ID number is in use or not
// Parameter: 0-199
// Return: True if the ID number is enrolled, false if not
bool FPS_GT511C3_CheckEnrolled(int id);
 
// Starts the Enrollment Process
// Parameter: 0-199
// Return:
//        0 - ACK
//        1 - Database is full
//        2 - Invalid Position
//        3 - Position(ID) is already used
int FPS_GT511C3_EnrollStart(int id);
 
// Gets the first scan of an enrollment
// Return:
//        0 - ACK
//        1 - Enroll Failed
//        2 - Bad finger
//        3 - ID in use
int FPS_GT511C3_Enroll1();
 
// Gets the Second scan of an enrollment
// Return:
//        0 - ACK
//        1 - Enroll Failed
//        2 - Bad finger
//        3 - ID in use
int FPS_GT511C3_Enroll2();
 
// Gets the Third scan of an enrollment
// Finishes Enrollment
// Return:
//        0 - ACK
//        1 - Enroll Failed
//        2 - Bad finger
//        3 - ID in use
int FPS_GT511C3_Enroll3();
 
// Checks to see if a finger is pressed on the FPS
// Return: true if finger pressed, false if not
bool FPS_GT511C3_IsPressFinger();
 
// Deletes the specified ID (enrollment) from the database
// Returns: true if successful, false if position invalid
bool FPS_GT511C3_DeleteID(int ID);
 
// Deletes all IDs (enrollments) from the database
// Returns: true if successful, false if db is empty
bool FPS_GT511C3_DeleteAll();
 
// Checks the currently pressed finger against a specific ID
// Parameter: 0-199 (id number to be checked)
// Returns:
//        0 - Verified OK (the correct finger)
//        1 - Invalid Position
//        2 - ID is not in use
//        3 - Verified FALSE (not the correct finger)
int FPS_GT511C3_Verify1_1(int id);
 
// Checks the currently pressed finger against all enrolled fingerprints
// Returns:
//        0-199: Verified against the specified ID (found, and here is the ID number)
//        200: Failed to find the fingerprint in the database
int FPS_GT511C3_Identify1_N();
 
// Captures the currently pressed finger into onboard ram
// Parameter: true for high quality image(slower), false for low quality image (faster)
// Generally, use high quality for enrollment, and low quality for verification/identification
// Returns: True if ok, false if no finger pressed
bool FPS_GT511C3_CaptureFinger(bool highquality);
 
//-= Not implemented commands =-
 
// Gets an image that is 258x202 (52116 bytes) and returns it in 407 Data_Packets
// Use StartDataDownload, and then GetNextDataPacket until done
// Returns: True (device confirming download starting)
// Not implemented due to memory restrictions on the arduino
// may revisit this if I find a need for it
//bool GetImage();
 
// Gets an image that is qvga 160x120 (19200 bytes) and returns it in 150 Data_Packets
// Use StartDataDownload, and then GetNextDataPacket until done
// Returns: True (device confirming download starting)
// Not implemented due to memory restrictions on the arduino
// may revisit this if I find a need for it
//bool GetRawImage();
 
// Gets a template from the fps (498 bytes) in 4 Data_Packets
// Use StartDataDownload, and then GetNextDataPacket until done
// Parameter: 0-199 ID number
// Returns:
//        0 - ACK Download starting
//        1 - Invalid position
//        2 - ID not used (no template to download
// Not implemented due to memory restrictions on the arduino
// may revisit this if I find a need for it
//int GetTemplate(int id);
 
// Uploads a template to the fps
// Parameter: the template (498 bytes)
// Parameter: the ID number to upload
// Parameter: Check for duplicate fingerprints already on fps
// Returns:
//        0-199 - ID duplicated
//        200 - Uploaded ok (no duplicate if enabled)
//        201 - Invalid position
//        202 - Communications error
//        203 - Device error
// Not implemented due to memory restrictions on the arduino
// may revisit this if I find a need for it
//int SetTemplate(byte* tmplt, int id, bool duplicateCheck);
 
// Commands that are not implemented (and why)
// VerifyTemplate1_1 - Couldn't find a good reason to implement this on an arduino
// IdentifyTemplate1_N - Couldn't find a good reason to implement this on an arduino
// MakeTemplate - Couldn't find a good reason to implement this on an arduino
// UsbInternalCheck - not implemented - Not valid config for arduino
// GetDatabaseStart - historical command, no longer supported
// GetDatabaseEnd - historical command, no longer supported
// UpgradeFirmware - Data Sheet says not supported
// UpgradeISOCDImage - Data Sheet says not supported
// SetIAPMode - for upgrading firmware (which is not supported)
// Ack and Nack        are listed as a commands for some unknown reason... not implemented
 
void FPS_GT511C3_serialPrintHex(unsigned char data_);
void FPS_GT511C3_SendToSerial(unsigned char data[], int length);
 
// resets the Data_Packet class, and gets ready to download
// Not implemented due to memory restrictions on the arduino
// may revisit this if I find a need for it
//void StartDataDownload();
 
// Returns the next data packet
// Not implemented due to memory restrictions on the arduino
// may revisit this if I find a need for it
//Data_Packet GetNextDataPacket();
 
void SendCommand(unsigned char cmd[], int length);
void GetResponse();
 
void ResetVars() {
    gfirstbyte = 0;
    gdone = FALSE;
    gIndex = 1;
}
 
unsigned char* Command_Packet_GetPacketBytes() {
    unsigned char packetbytes[12];
    unsigned int cmd, checksum;
    // update command before calculating checksum (important!)
    cmd = Command_packet.Commands.Command;
    Command_Packet.command[0] = Command_Packet_GetLowByte(cmd);
    Command_Packet.command[1] = Command_Packet_GetHighByte(cmd);
 
    checksum = Command_Packet_CalculateChecksum();
 
    packetbytes[0] = Command_Packet.COMMAND_START_CODE_1;
    packetbytes[1] = Command_Packet.COMMAND_START_CODE_2;
    packetbytes[2] = Command_Packet.COMMAND_DEVICE_ID_1;
    packetbytes[3] = Command_Packet.COMMAND_DEVICE_ID_2;
    packetbytes[4] = Command_Packet.Parameter[0];
    packetbytes[5] = Command_Packet.Parameter[1];
    packetbytes[6] = Command_Packet.Parameter[2];
    packetbytes[7] = Command_Packet.Parameter[3];
    packetbytes[8] = Command_Packet.command[0];
    packetbytes[9] = Command_Packet.command[1];
    packetbytes[10] = Command_Packet_GetLowByte(checksum);
    packetbytes[11] = Command_Packet_GetHighByte(checksum);
 
    return &packetbytes;
}
 
// Converts the int to bytes and puts them into the paramter array
void Command_Packet_ParameterFromInt(int i) {
    Command_Packet.Parameter[0] = (i & 0x000000ff);
    Command_Packet.Parameter[1] = (i & 0x0000ff00) >> 8;
    Command_Packet.Parameter[2] = (i & 0x00ff0000) >> 16;
    Command_Packet.Parameter[3] = (i & 0xff000000) >> 24;
}
 
// Returns the high byte from a word
unsigned char Command_Packet_GetHighByte(unsigned int w) {
    return (unsigned char)(w>>8)&0x00FF;
}
 
// Returns the low byte from a word
unsigned char Command_Packet_GetLowByte(unsigned int w) {
    return (unsigned char)w&0x00FF;
}
 
unsigned int Command_Packet_CalculateChecksum() {
    unsigned int w = 0;
 
    w += Command_Packet.COMMAND_START_CODE_1;
    w += Command_Packet.COMMAND_START_CODE_2;
    w += Command_Packet.COMMAND_DEVICE_ID_1;
    w += Command_Packet.COMMAND_DEVICE_ID_2;
    w += Command_Packet.Parameter[0];
    w += Command_Packet.Parameter[1];
    w += Command_Packet.Parameter[2];
    w += Command_Packet.Parameter[3];
    w += Command_Packet.command[0];
    w += Command_Packet.command[1];
 
    return w;
}
 
// Gets an int from the parameter bytes
int Response_Packet_IntFromParameter() {
    int retval = 0;
 
    retval = (retval << 8) + Response_Packet.ParameterBytes[3];
    retval = (retval << 8) + Response_Packet.ParameterBytes[2];
    retval = (retval << 8) + Response_Packet.ParameterBytes[1];
    retval = (retval << 8) + Response_Packet.ParameterBytes[0];
 
    return retval;
}
 
// calculates the checksum from the bytes in the Packet
//unsigned int Response_Packet_CalculateChecksum(unsigned char buffer[], int length) {
unsigned int Response_Packet_CalculateChecksum(unsigned char buffer[], int length) {
    unsigned int checksum = 0;
    unsigned int i = 0;
 
    for(i = 0; i < length; i++) {
        checksum += buffer[i];
    }
 
    return checksum;
}
 
// Returns the high byte from a word
unsigned char Response_Packet_GetHighByte(unsigned int w) {
    return (unsigned char)(w>>8)&0x00FF;
}
 
// Returns the low byte from a word
unsigned char Response_Packet_GetLowByte(unsigned int w) {
    return (unsigned char)w&0x00FF;
}
 
// parses bytes into one of the possible errors from the finger print scanner
//Response_Packet::ErrorCodes::Errors_Enum Response_Packet_ErrorCodes_ParseFromBytes(unsigned char high, unsigned char low)
unsigned int Response_Packet_ErrorCodes_ParseFromBytes(unsigned char high, unsigned char low) {
    Response_Packet.ErrorCodes.e = INVALID;
 
    if (high == 0x00)
    {
    }
    // grw 01/03/15 - replaced if clause with else clause for any non-zero high byte
    // if (high == 0x01)
    // {
    else {
        switch(low) {
            case 0x00: Response_Packet.ErrorCodes.e = NO_ERROR; break;
            case 0x01: Response_Packet.ErrorCodes.e = NACK_TIMEOUT; break;
            case 0x02: Response_Packet.ErrorCodes.e = NACK_INVALID_BAUDRATE; break;
            case 0x03: Response_Packet.ErrorCodes.e = NACK_INVALID_POS; break;
            case 0x04: Response_Packet.ErrorCodes.e = NACK_IS_NOT_USED; break;
            case 0x05: Response_Packet.ErrorCodes.e = NACK_IS_ALREADY_USED; break;
            case 0x06: Response_Packet.ErrorCodes.e = NACK_COMM_ERR; break;
            case 0x07: Response_Packet.ErrorCodes.e = NACK_VERIFY_FAILED; break;
            case 0x08: Response_Packet.ErrorCodes.e = NACK_IDENTIFY_FAILED; break;
            case 0x09: Response_Packet.ErrorCodes.e = NACK_DB_IS_FULL; break;
            case 0x0A: Response_Packet.ErrorCodes.e = NACK_DB_IS_EMPTY; break;
            case 0x0B: Response_Packet.ErrorCodes.e = NACK_TURN_ERR; break;
            case 0x0C: Response_Packet.ErrorCodes.e = NACK_BAD_FINGER; break;
            case 0x0D: Response_Packet.ErrorCodes.e = NACK_ENROLL_FAILED; break;
            case 0x0E: Response_Packet.ErrorCodes.e = NACK_IS_NOT_SUPPORTED; break;
            case 0x0F: Response_Packet.ErrorCodes.e = NACK_DEV_ERR; break;
            case 0x10: Response_Packet.ErrorCodes.e = NACK_CAPTURE_CANCELED; break;
            case 0x11: Response_Packet.ErrorCodes.e = NACK_INVALID_PARAM; break;
            case 0x12: Response_Packet.ErrorCodes.e = NACK_FINGER_IS_NOT_PRESSED; break;
        };
    }
 
    return Response_Packet.ErrorCodes.e;
}
 
// checks to see if the byte is the proper value, and logs it to the serial channel if not
bool Response_Packet_CheckParsing(unsigned char b, unsigned char propervalue, unsigned char alternatevalue, char* varname, bool UseSerialDebug) {
    bool retval;
    char str[22];
 
    retval = (b != propervalue) && (b != alternatevalue);
 
    if((UseSerialDebug) && (retval)) {
        UART5_Write_Text("Response_Packet parsing error \r\n");
        UART5_Write_Text(varname);
        UART5_Write_Text(" ");
        ByteToHex(propervalue, str);
        Ltrim(str);
        Rtrim(str);
        UART5_Write_Text(str);
        UART5_Write_Text(" || ");
        ByteToHex(alternatevalue, str);
        Ltrim(str);
        Rtrim(str);
        UART5_Write_Text(str);
        UART5_Write_Text(" != ");
        ByteToHex(b, str);
        Ltrim(str);
        Rtrim(str);
        UART5_Write_Text(str);
    }
    
    return retval;
}
 
void Response_Packet_Response_Packet(unsigned char* buffer, bool UseSerialDebug) {
 
    unsigned int checksum, i;
    unsigned char checksum_low;
    unsigned char checksum_high;
 
    Response_Packet_CheckParsing(buffer[0], Response_Packet.COMMAND_START_CODE_1, Response_Packet.COMMAND_START_CODE_1, "COMMAND_START_CODE_1", UseSerialDebug);
    Response_Packet_CheckParsing(buffer[1], Response_Packet.COMMAND_START_CODE_2, Response_Packet.COMMAND_START_CODE_2, "COMMAND_START_CODE_2", UseSerialDebug);
    Response_Packet_CheckParsing(buffer[2], Response_Packet.COMMAND_DEVICE_ID_1, Response_Packet.COMMAND_DEVICE_ID_1, "COMMAND_DEVICE_ID_1", UseSerialDebug);
    Response_Packet_CheckParsing(buffer[3], Response_Packet.COMMAND_DEVICE_ID_2, Response_Packet.COMMAND_DEVICE_ID_2, "COMMAND_DEVICE_ID_2", UseSerialDebug);
    Response_Packet_CheckParsing(buffer[9], 0x30, 0x31, "AckNak_LOW", UseSerialDebug);
    if(buffer[8] == 0x30)Response_Packet.ACK = TRUE; else Response_Packet.ACK = FALSE;
    Response_Packet_CheckParsing(buffer[10], 0x00, 0x00, "AckNak_HIGH", UseSerialDebug);
 
    checksum = Response_Packet_CalculateChecksum(buffer, 10);
    checksum_low = Response_Packet_GetLowByte(checksum);
    checksum_high = Response_Packet_GetHighByte(checksum);
    Response_Packet_CheckParsing(buffer[11], checksum_low, checksum_low, "Checksum_LOW", UseSerialDebug);
    Response_Packet_CheckParsing(buffer[12], checksum_high, checksum_high, "Checksum_HIGH", UseSerialDebug);
 
    Response_Packet.ErrorCodes.Error = Response_Packet_ErrorCodes_ParseFromBytes(buffer[5], buffer[4]);
 
    Response_Packet.ParameterBytes[0] = buffer[4];
    Response_Packet.ParameterBytes[1] = buffer[5];
    Response_Packet.ParameterBytes[2] = buffer[6];
    Response_Packet.ParameterBytes[3] = buffer[7];
    Response_Packet.ResponseBytes[0] = buffer[8];
    Response_Packet.ResponseBytes[1] = buffer[9];
 
    for(i = 0; i < 12; i++) {
        Response_Packet.RawBytes[i] = buffer[i];
    }
}
 
/*
void Response_Packet_Response_Packet(unsigned char* buffer, bool UseSerialDebug) {
 
    unsigned int checksum, i;
    unsigned char checksum_low;
    unsigned char checksum_high;
 
    Response_Packet_CheckParsing(buffer[0], Response_Packet.COMMAND_START_CODE_1, Response_Packet.COMMAND_START_CODE_1, "COMMAND_START_CODE_1", UseSerialDebug);
    Response_Packet_CheckParsing(buffer[1], Response_Packet.COMMAND_START_CODE_2, Response_Packet.COMMAND_START_CODE_2, "COMMAND_START_CODE_2", UseSerialDebug);
    Response_Packet_CheckParsing(buffer[2], Response_Packet.COMMAND_DEVICE_ID_1, Response_Packet.COMMAND_DEVICE_ID_1, "COMMAND_DEVICE_ID_1", UseSerialDebug);
    Response_Packet_CheckParsing(buffer[3], Response_Packet.COMMAND_DEVICE_ID_2, Response_Packet.COMMAND_DEVICE_ID_2, "COMMAND_DEVICE_ID_2", UseSerialDebug);
    Response_Packet_CheckParsing(buffer[8], 0x30, 0x31, "AckNak_LOW", UseSerialDebug);
    if(buffer[8] == 0x30)Response_Packet.ACK = TRUE; else Response_Packet.ACK = FALSE;
    Response_Packet_CheckParsing(buffer[9], 0x00, 0x00, "AckNak_HIGH", UseSerialDebug);
 
    checksum = Response_Packet_CalculateChecksum(buffer, 10);
    checksum_low = Response_Packet_GetLowByte(checksum);
    checksum_high = Response_Packet_GetHighByte(checksum);
    Response_Packet_CheckParsing(buffer[10], checksum_low, checksum_low, "Checksum_LOW", UseSerialDebug);
    Response_Packet_CheckParsing(buffer[11], checksum_high, checksum_high, "Checksum_HIGH", UseSerialDebug);
 
    Response_Packet.ErrorCodes.Error = Response_Packet_ErrorCodes_ParseFromBytes(buffer[5], buffer[4]);
 
    Response_Packet.ParameterBytes[0] = buffer[4];
    Response_Packet.ParameterBytes[1] = buffer[5];
    Response_Packet.ParameterBytes[2] = buffer[6];
    Response_Packet.ParameterBytes[3] = buffer[7];
    Response_Packet.ResponseBytes[0] = buffer[8];
    Response_Packet.ResponseBytes[1] = buffer[9];
 
    for(i = 0; i < 12; i++) {
        Response_Packet.RawBytes[i] = buffer[i];
    }
}
*/
 
void FPS_GT511C3_SendCommand(unsigned char cmd[], int length) {
    unsigned int i = 0;
 
    for(i = 0; i < length; i++) {
         UART2_Write(cmd[i]);
    }
 
    if(UseSerialDebug) {
        UART5_Write_Text("FPS - SEND: ");
        for(i = 0; i < length; i++) {
           UART5_Write(cmd[i]);
        }
 
        UART5_Write_Text("\r\n\r\n");
    }
}
 
void PrintResponseBytes(unsigned char response[]) {
     unsigned int i = 0;
 
     for(i = 0; i < 12; i++) {
          FPS_GT511C3_serialPrintHex(response[i]);
     }
}
 
// sends a byte to the serial debugger in the hex format we want EX "0F"
void FPS_GT511C3_serialPrintHex(unsigned char data_) {
    char tmp[22];
    ByteToHex(data_, tmp);
    Ltrim(tmp);
    Rtrim(tmp);
    UART5_Write_Text(tmp);
}
 
// sends the bye aray to the serial debugger in our hex format EX: "00 AF FF 10 00 13"
void FPS_GT511C3_SendToSerial(unsigned char data_[], int length) {
    bool first = TRUE;
    unsigned int i;
 
    UART5_Write_Text(""");
 
    for(i = 0; i < length; i++) {
       if(first)first = FALSE;
       else UART5_Write_Text(" ");
       FPS_GT511C3_serialPrintHex(data_[i]);
    }
 
    UART5_Write_Text(""");
}
 
// Gets the response to the command from the software serial channel (and waits for it)
void FPS_GT511C3_GetResponse() {
    /*
    unsigned char firstbyte = 0;
    bool done = FALSE;
    unsigned char resp[12];
    unsigned int i;
 
    while(done == FALSE) {
       firstbyte = (unsigned char)UART2_Read();
 
       if(firstbyte == Response_Packet.COMMAND_START_CODE_1) {
            done = TRUE;
       }
    }
 
    resp[0] = firstbyte;
 
    for(i = 1; i < 12; i++) {
          resp[i]= (unsigned char)UART2_Read();
    }
    */
    Delay_ms(2000);
    Response_Packet_Response_Packet(resp, UseSerialDebug);
 
    if(UseSerialDebug) {
         UART5_Write_Text("FPS - RECV: ");
         FPS_GT511C3_SendToSerial(Response_Packet.RawBytes, 12);
         UART5_Write_Text("\r\n");
         UART5_Write_Text("\r\n");
    }
}
 
bool FPS_GT511C3_ChangeBaudRate(int baud) {
    unsigned char* Packetbytes;
    bool retval;
    
    if((baud == 9600) || (baud == 19200) || (baud == 38400) || (baud == 57600) || (baud == 115200)) {
        if(UseSerialDebug)UART5_Write_Text("FPS - ChangeBaudRate\r\n");
        Command_Packet.Commands.Command = Open;
        Command_Packet_ParameterFromInt(baud);
        Packetbytes = Command_Packet_GetPacketBytes();
        FPS_GT511C3_SendCommand(Packetbytes, 12);
        FPS_GT511C3_GetResponse();
        ResetVars();
        retval = Response_Packet.ACK;
        
        if(retval) {
            UART2_Init(baud);
            Delay_ms(200);
        }
 
        return retval;
    }
    
    return FALSE;
}
 
void FPS_GT511C3_Open() {
    unsigned char* Packetbytes;
    
    if(UseSerialDebug)UART5_Write_Text("FPS - Open\r\n");
    Command_Packet.Commands.Command = Open;
    Command_Packet.Parameter[0] = 0x00;
    Command_Packet.Parameter[1] = 0x00;
    Command_Packet.Parameter[2] = 0x00;
    Command_Packet.Parameter[3] = 0x00;
    Packetbytes = Command_Packet_GetPacketBytes();
    FPS_GT511C3_SendCommand(Packetbytes, 12);
    FPS_GT511C3_GetResponse();
    //PrintResponseBytes(resp);
    ResetVars();
}
 
// Turns on or off the LED backlight
// Parameter: true turns on the backlight, false turns it off
// Returns: True if successful, false if not
bool FPS_GT511C3_SetLED(bool on) {
    unsigned char* Packetbytes;
    bool retval;
    
    Command_Packet.Commands.Command = CmosLed;
    
    if(on) {
       if(UseSerialDebug)UART5_Write_Text("FPS - LED on\r\n");
       Command_Packet.Parameter[0] = 0x01;
    }
    else {
       if(UseSerialDebug)UART5_Write_Text("FPS - LED off\r\n");
       Command_Packet.Parameter[0] = 0x00;
    }
    
    Command_Packet.Parameter[1] = 0x00;
    Command_Packet.Parameter[2] = 0x00;
    Command_Packet.Parameter[3] = 0x00;
    Packetbytes = Command_Packet_GetPacketBytes();
    FPS_GT511C3_SendCommand(Packetbytes, 12);
    FPS_GT511C3_GetResponse();
    ResetVars();
    retval = TRUE;
    if(Response_Packet.ACK == FALSE)retval = FALSE;
    return retval;
}
 
// Gets the number of enrolled fingerprints
// Return: The total number of enrolled fingerprints
int FPS_GT511C3_GetEnrollCount() {
    unsigned char* Packetbytes;
    int retval;
    
    if(UseSerialDebug)UART5_Write_Text("FPS - GetEnrolledCount\r\n");
    Command_Packet.Commands.Command = GetEnrollCount;
    Command_Packet.Parameter[0] = 0x00;
    Command_Packet.Parameter[1] = 0x00;
    Command_Packet.Parameter[2] = 0x00;
    Command_Packet.Parameter[3] = 0x00;
    Packetbytes = Command_Packet_GetPacketBytes();
    FPS_GT511C3_SendCommand(Packetbytes, 12);
    FPS_GT511C3_GetResponse();
    ResetVars();
 
    retval = Response_Packet_IntFromParameter();
    return retval;
}
 
// checks to see if the ID number is in use or not
// Parameter: 0-199
// Return: True if the ID number is enrolled, false if not
bool FPS_GT511C3_CheckEnrolled(int id) {
    unsigned char* Packetbytes;
    bool retval;
    
    if(UseSerialDebug)UART5_Write_Text("FPS - CheckEnrolled\r\n");
    Command_Packet.Commands.Command = CheckEnrolled;
    Command_Packet_ParameterFromInt(id);
    Packetbytes = Command_Packet_GetPacketBytes();
    FPS_GT511C3_SendCommand(Packetbytes, 12);
    FPS_GT511C3_GetResponse();
    ResetVars();
    retval = FALSE;
    retval = Response_Packet.ACK;
    
    return retval;
}
 
// Starts the Enrollment Process
// Parameter: 0-199
// Return:
//        0 - ACK
//        1 - Database is full
//        2 - Invalid Position
//        3 - Position(ID) is already used
int FPS_GT511C3_EnrollStart(int id) {
    unsigned char* Packetbytes;
    int retval;
    
    if(UseSerialDebug)UART5_Write_Text("FPS - EnrollStart\r\n");
    Command_Packet.Commands.Command = EnrollStart;
    Command_Packet_ParameterFromInt(id);
    Packetbytes = Command_Packet_GetPacketBytes();
    FPS_GT511C3_SendCommand(Packetbytes, 12);
    FPS_GT511C3_GetResponse();
    ResetVars();
    retval = 0;
 
    if(Response_Packet.ACK == FALSE)
    {
         if(Response_Packet.ErrorCodes.Error == NACK_DB_IS_FULL)retval = 1;
         if(Response_Packet.ErrorCodes.Error == NACK_INVALID_POS)retval = 2;
         if(Response_Packet.ErrorCodes.Error == NACK_IS_ALREADY_USED)retval = 3;
    }
 
    return retval;
}
 
// Gets the first scan of an enrollment
// Return:
//        0 - ACK
//        1 - Enroll Failed
//        2 - Bad finger
//        3 - ID in use
int FPS_GT511C3_Enroll1() {
    unsigned char* Packetbytes;
    int retval;
 
    if(UseSerialDebug)UART5_Write_Text("FPS - Enroll1\r\n");
    Command_Packet.Commands.Command = Enroll1;
    Packetbytes = Command_Packet_GetPacketBytes();
    FPS_GT511C3_SendCommand(Packetbytes, 12);
    FPS_GT511C3_GetResponse();
    ResetVars();
    retval = Response_Packet_IntFromParameter();
    
    if(retval < 200) retval = 3; else retval = 0;
 
    if(Response_Packet.ACK == FALSE)
    {
        if(Response_Packet.ErrorCodes.Error == NACK_ENROLL_FAILED)retval = 1;
        if(Response_Packet.ErrorCodes.Error == NACK_BAD_FINGER)retval = 2;
    }
 
 
    if(Response_Packet.ACK) return 0; else return retval;
}
 
// Gets the Second scan of an enrollment
// Return:
//        0 - ACK
//        1 - Enroll Failed
//        2 - Bad finger
//        3 - ID in use
int FPS_GT511C3_Enroll2() {
    unsigned char* Packetbytes;
    int retval;
 
    if(UseSerialDebug)UART5_Write_Text("FPS - Enroll1\r\n");
    Command_Packet.Commands.Command = Enroll2;
    Packetbytes = Command_Packet_GetPacketBytes();
    FPS_GT511C3_SendCommand(Packetbytes, 12);
    FPS_GT511C3_GetResponse();
    ResetVars();
    retval = Response_Packet_IntFromParameter();
 
    if(retval < 200) retval = 3; else retval = 0;
 
    if(Response_Packet.ACK == FALSE)
    {
        if(Response_Packet.ErrorCodes.Error == NACK_ENROLL_FAILED)retval = 1;
        if(Response_Packet.ErrorCodes.Error == NACK_BAD_FINGER)retval = 2;
    }
 
 
    if(Response_Packet.ACK) return 0; else return retval;
}
 
// Gets the Third scan of an enrollment
// Finishes Enrollment
// Return:
//        0 - ACK
//        1 - Enroll Failed
//        2 - Bad finger
//        3 - ID in use
int FPS_GT511C3_Enroll3() {
    unsigned char* Packetbytes;
    int retval;
 
    if(UseSerialDebug)UART5_Write_Text("FPS - Enroll1\r\n");
    Command_Packet.Commands.Command = Enroll3;
    Packetbytes = Command_Packet_GetPacketBytes();
    FPS_GT511C3_SendCommand(Packetbytes, 12);
    FPS_GT511C3_GetResponse();
    ResetVars();
    retval = Response_Packet_IntFromParameter();
 
    if(retval < 200) retval = 3; else retval = 0;
 
    if(Response_Packet.ACK == FALSE)
    {
        if(Response_Packet.ErrorCodes.Error == NACK_ENROLL_FAILED)retval = 1;
        if(Response_Packet.ErrorCodes.Error == NACK_BAD_FINGER)retval = 2;
    }
 
 
    if(Response_Packet.ACK) return 0; else return retval;
}
 
// Checks to see if a finger is pressed on the FPS
// Return: true if finger pressed, false if not
bool FPS_GT511C3_IsPressFinger() {
    unsigned char* Packetbytes;
    bool retval;
    int pval;
    
    if(UseSerialDebug)UART5_Write_Text("FPS - IsPressFinger\r\n");
    Command_Packet.Commands.Command = IsPressFinger;
    Packetbytes = Command_Packet_GetPacketBytes();
    FPS_GT511C3_SendCommand(Packetbytes, 12);
    FPS_GT511C3_GetResponse();
    ResetVars();
    retval = FALSE;
    pval = Response_Packet.ParameterBytes[0];
    pval += Response_Packet.ParameterBytes[1];
    pval += Response_Packet.ParameterBytes[2];
    pval += Response_Packet.ParameterBytes[3];
    
    if(pval == 0)retval = TRUE;
 
    return retval;
}
 
// Deletes the specified ID (enrollment) from the database
// Parameter: 0-199 (id number to be deleted)
// Returns: true if successful, false if position invalid
bool FPS_GT511C3_DeleteID(int id) {
    unsigned char* Packetbytes;
    bool retval;
 
    if(UseSerialDebug)UART5_Write_Text("FPS - DeleteID\r\n");
    Command_Packet.Commands.Command = DeleteID;
    Command_Packet_ParameterFromInt(id);
    Packetbytes = Command_Packet_GetPacketBytes();
    FPS_GT511C3_SendCommand(Packetbytes, 12);
    FPS_GT511C3_GetResponse();
    ResetVars();
    retval = Response_Packet.ACK;
 
    return retval;
}
 
// Deletes all IDs (enrollments) from the database
// Returns: true if successful, false if db is empty
bool FPS_GT511C3_DeleteAll() {
    unsigned char* Packetbytes;
    bool retval;
    
    if(UseSerialDebug)UART5_Write_Text("FPS - DeleteAll\r\n");
    Command_Packet.Commands.Command = DeleteAll;
    Packetbytes = Command_Packet_GetPacketBytes();
    FPS_GT511C3_SendCommand(Packetbytes, 12);
    FPS_GT511C3_GetResponse();
    ResetVars();
    retval = Response_Packet.ACK;
 
    return retval;
}
 
// Checks the currently pressed finger against a specific ID
// Parameter: 0-199 (id number to be checked)
// Returns:
//        0 - Verified OK (the correct finger)
//        1 - Invalid Position
//        2 - ID is not in use
//        3 - Verified FALSE (not the correct finger)
int FPS_GT511C3_Verify1_1(int id) {
    unsigned char* Packetbytes;
    int retval;
    
    if(UseSerialDebug)UART5_Write_Text("FPS - Verify1_1\r\n");
    Command_Packet.Commands.Command = Verify1_1;
    Command_Packet_ParameterFromInt(id);
    Packetbytes = Command_Packet_GetPacketBytes();
    FPS_GT511C3_SendCommand(Packetbytes, 12);
    FPS_GT511C3_GetResponse();
    ResetVars();
    retval = 0;
    
 
    if(Response_Packet.ACK == FALSE)
    {
          retval = 3; // grw 01/03/15 - set default value of not verified before assignment
          
          if (Response_Packet.ErrorCodes.Error == NACK_INVALID_POS)retval = 1;
          if (Response_Packet.ErrorCodes.Error == NACK_IS_NOT_USED) retval = 2;
          if (Response_Packet.ErrorCodes.Error == NACK_VERIFY_FAILED) retval = 3;
    }
 
 
    return retval;
}
 
// Checks the currently pressed finger against all enrolled fingerprints
// Returns:
//        0-199: Verified against the specified ID (found, and here is the ID number)
//        200: Failed to find the fingerprint in the database
int FPS_GT511C3_Identify1_N() {
    unsigned char* Packetbytes;
    int retval;
    
    if(UseSerialDebug)UART5_Write_Text("FPS - Identify1_N\r\n");
    Command_Packet.Commands.Command = Identify1_N;
    Packetbytes = Command_Packet_GetPacketBytes();
    FPS_GT511C3_SendCommand(Packetbytes, 12);
    FPS_GT511C3_GetResponse();
    ResetVars();
    retval = Response_Packet_IntFromParameter();
    
    if(retval > 200) retval = 200;
 
    return retval;
}
 
// Captures the currently pressed finger into onboard ram use this prior to other commands
// Parameter: true for high quality image(slower), false for low quality image (faster)
// Generally, use high quality for enrollment, and low quality for verification/identification
// Returns: True if ok, false if no finger pressed
bool FPS_GT511C3_CaptureFinger(bool highquality) {
 
    unsigned char* Packetbytes;
    bool retval;
 
    if(UseSerialDebug)UART5_Write_Text("FPS - CaptureFinger\r\n");
    Command_Packet.Commands.Command = CaptureFinger;
    if(highquality) {
        Command_Packet_ParameterFromInt(1);
    }
    else {
        Command_Packet_ParameterFromInt(0);
    }
    
    Packetbytes = Command_Packet_GetPacketBytes();
    FPS_GT511C3_SendCommand(Packetbytes, 12);
    FPS_GT511C3_GetResponse();
    ResetVars();
    retval = Response_Packet.ACK;
 
    return retval;
}
 
void Enroll() {
     // Enroll test
 
    // find open enroll id
    static int enrollid = 0;
    int bret, iret;
    bool usedid = TRUE;
    
    while(usedid == TRUE) {
        usedid = FPS_GT511C3_CheckEnrolled(enrollid);
        if(usedid == TRUE)enrollid++;
    }
    
    FPS_GT511C3_EnrollStart(enrollid);
 
    // enroll
    UART5_Write_Text("Press finger to Enroll #");
    UART5_Write_Text(enrollid);
    UART5_Write_Text("\r\n");
    while(FPS_GT511C3_IsPressFinger() == FALSE)Delay_ms(100);
    bret = FPS_GT511C3_CaptureFinger(TRUE);
    iret = 0;
    
    if(bret != FALSE) {
            UART5_Write_Text("Remove finger\r\n");
            FPS_GT511C3_Enroll1();
            while(FPS_GT511C3_IsPressFinger() == TRUE)Delay_ms(100);
            UART5_Write_Text("Press same finger again\r\n");
            while(FPS_GT511C3_IsPressFinger() == FALSE)Delay_ms(100);
            bret = FPS_GT511C3_CaptureFinger(TRUE);
            
            if(bret != FALSE)
            {
                    UART5_Write_Text("Remove finger\r\n");
                    FPS_GT511C3_Enroll2();
                    while(FPS_GT511C3_IsPressFinger() == TRUE)Delay_ms(100);
                    UART5_Write_Text("Press same finger yet again\r\n");
                    while(FPS_GT511C3_IsPressFinger() == FALSE)Delay_ms(100);
                    bret = FPS_GT511C3_CaptureFinger(TRUE);
                    if (bret != FALSE)
                    {
                            UART5_Write_Text("Remove finger\r\n");
                            iret = FPS_GT511C3_Enroll3();
                            if (iret == 0)
                            {
                                    UART5_Write_Text("Enrolling Successfull\r\n");
                            }
                            else
                            {
                                    UART5_Write_Text("Enrolling Failed with error code:");
                                    UART5_Write_Text(iret);
                                    UART5_Write_Text("\r\n");
                            }
                    }
                    else UART5_Write_Text("Failed to capture third finger\r\n");
            }
            else UART5_Write_Text("Failed to capture second finger\r\n");
    }
    else UART5_Write_Text("Failed to capture first finger\r\n");
}
 
void UART2() iv IVT_UART_2 ilevel 2 ics ICS_AUTO {
    
    if(gdone = TRUE) {
       resp[gIndex]= UART2_Read();
       //UART5_Write(resp[gIndex]);
       gIndex++;
    }
    else if(gdone == FALSE) {
       gfirstbyte = UART2_Read();
       //UART5_Write(gfirstbyte);
 
       if(gfirstbyte == Response_Packet.COMMAND_START_CODE_1) {
            resp[0] = gfirstbyte;
            gIndex = 1;
            gdone = TRUE;
       }
    }
    
    U2RXIF_bit = 0;
}
 
void main() {
 
    AD1PCFG = 0xFFFF;
    JTAGEN_bit = 0;
    
    TRISB = 0x00000000;
 
    Command_Packet.COMMAND_START_CODE_1 = 0x55;
    Command_Packet.COMMAND_START_CODE_2 = 0xAA;
    Command_Packet.COMMAND_DEVICE_ID_1 = 0x01;
    Command_Packet.COMMAND_DEVICE_ID_2 = 0x00;
    
    Response_Packet.COMMAND_START_CODE_1 = 0x55;
    Response_Packet.COMMAND_START_CODE_2 = 0xAA;
    Response_Packet.COMMAND_DEVICE_ID_1 = 0x01;
    Response_Packet.COMMAND_DEVICE_ID_2 = 0x00;
    
    UART5_Init(9600);
    Delay_ms(200);
    UART2_Init(9600);
    Delay_ms(200);
    
    U2IP0_bit = 0;                     // Set UART2 interrupt
    U2IP1_bit = 1;                     // Set interrupt priorities
    U2IP2_bit = 1;                     // Set UART2 interrupt to level 6
 
    U2RXIE_bit = 1;
    U2RXIF_bit = 0;
    EnableInterrupts();       // Enable all interrupts
    
    UseSerialDebug = TRUE;
    
    FPS_GT511C3_Open();
    Delay_ms(500);
    FPS_GT511C3_SetLED(1);
    Delay_ms(500);
    
    while(1) {
    
          //Delay_ms(2000);
          Enroll();
          //FPS_GT511C3_SetLED(1);
          //Delay_ms(2000);
          //FPS_GT511C3_SetLED(0);
    }
}




The RawBytes[] contains the response received from FPS.


Code C - [expand]
1
2
3
for(i = 0; i < 12; i++) {
        Response_Packet.RawBytes[i] = buffer[i];
    }




In the second screenshot you can see that the received response bytes (resp[] or RawBytes[]) are printed after "FPS RECV: "


Edit: This is the modified function. Now I don't see the Response Packet Parsing Error messages and it is passing all functions. You can see it in the third screenshot.

I don't know why the unmodified (C++) code works in Arduino but same code implemented in C doesn't work. But if the changes shown below are made then it works.



Code C - [expand]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
void Response_Packet_Response_Packet(unsigned char* buffer, bool UseSerialDebug) {
 
    unsigned int checksum, i;
    unsigned char checksum_low;
    unsigned char checksum_high;
 
    Response_Packet_CheckParsing(buffer[1], Response_Packet.COMMAND_START_CODE_1, Response_Packet.COMMAND_START_CODE_1, "COMMAND_START_CODE_1", UseSerialDebug);
    Response_Packet_CheckParsing(buffer[2], Response_Packet.COMMAND_START_CODE_2, Response_Packet.COMMAND_START_CODE_2, "COMMAND_START_CODE_2", UseSerialDebug);
    Response_Packet_CheckParsing(buffer[3], Response_Packet.COMMAND_DEVICE_ID_1, Response_Packet.COMMAND_DEVICE_ID_1, "COMMAND_DEVICE_ID_1", UseSerialDebug);
    Response_Packet_CheckParsing(buffer[4], Response_Packet.COMMAND_DEVICE_ID_2, Response_Packet.COMMAND_DEVICE_ID_2, "COMMAND_DEVICE_ID_2", UseSerialDebug);
    Response_Packet_CheckParsing(buffer[9], 0x30, 0x31, "AckNak_LOW", UseSerialDebug);
    if(buffer[8] == 0x30)Response_Packet.ACK = TRUE; else Response_Packet.ACK = FALSE;
    Response_Packet_CheckParsing(buffer[10], 0x00, 0x00, "AckNak_HIGH", UseSerialDebug);
 
    checksum = Response_Packet_CalculateChecksum(buffer, 10);
    checksum_low = Response_Packet_GetLowByte(checksum);
    checksum_high = Response_Packet_GetHighByte(checksum);
    Response_Packet_CheckParsing(buffer[11], checksum_low, checksum_low, "Checksum_LOW", UseSerialDebug);
    Response_Packet_CheckParsing(buffer[12], checksum_high, checksum_high, "Checksum_HIGH", UseSerialDebug);
 
    Response_Packet.ErrorCodes.Error = Response_Packet_ErrorCodes_ParseFromBytes(buffer[5], buffer[4]);
 
    Response_Packet.ParameterBytes[0] = buffer[4];
    Response_Packet.ParameterBytes[1] = buffer[5];
    Response_Packet.ParameterBytes[2] = buffer[6];
    Response_Packet.ParameterBytes[3] = buffer[7];
    Response_Packet.ResponseBytes[0] = buffer[8];
    Response_Packet.ResponseBytes[1] = buffer[9];
 
    for(i = 0; i < 12; i++) {
        Response_Packet.RawBytes[i] = buffer[i];
    }
}




The original piece of code


Code C - [expand]
1
2
3
4
Response_Packet_CheckParsing(buffer[0], Response_Packet.COMMAND_START_CODE_1, Response_Packet.COMMAND_START_CODE_1, "COMMAND_START_CODE_1", UseSerialDebug);
    Response_Packet_CheckParsing(buffer[1], Response_Packet.COMMAND_START_CODE_2, Response_Packet.COMMAND_START_CODE_2, "COMMAND_START_CODE_2", UseSerialDebug);
    Response_Packet_CheckParsing(buffer[2], Response_Packet.COMMAND_DEVICE_ID_1, Response_Packet.COMMAND_DEVICE_ID_1, "COMMAND_DEVICE_ID_1", UseSerialDebug);
    Response_Packet_CheckParsing(buffer[3], Response_Packet.COMMAND_DEVICE_ID_2, Response_Packet.COMMAND_DEVICE_ID_2, "COMMAND_DEVICE_ID_2", UseSerialDebug);



The modified piece of code.


Code C - [expand]
1
2
3
4
Response_Packet_CheckParsing(buffer[1], Response_Packet.COMMAND_START_CODE_1, Response_Packet.COMMAND_START_CODE_1, "COMMAND_START_CODE_1", UseSerialDebug);
    Response_Packet_CheckParsing(buffer[2], Response_Packet.COMMAND_START_CODE_2, Response_Packet.COMMAND_START_CODE_2, "COMMAND_START_CODE_2", UseSerialDebug);
    Response_Packet_CheckParsing(buffer[3], Response_Packet.COMMAND_DEVICE_ID_1, Response_Packet.COMMAND_DEVICE_ID_1, "COMMAND_DEVICE_ID_1", UseSerialDebug);
    Response_Packet_CheckParsing(buffer[4], Response_Packet.COMMAND_DEVICE_ID_2, Response_Packet.COMMAND_DEVICE_ID_2, "COMMAND_DEVICE_ID_2", UseSerialDebug);




This is another modified function. I have made changes to print sent bytes.


Code - [expand]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
;
    unsigned int cmd, checksum;
    // update command before calculating checksum (important!)
    cmd = Command_packet.Commands.Command;
    Command_Packet.command[0] = Command_Packet_GetLowByte(cmd);
    Command_Packet.command[1] = Command_Packet_GetHighByte(cmd);
 
    checksum = Command_Packet_CalculateChecksum();
 
    packetbytes[0] = Command_Packet.COMMAND_START_CODE_1;
    packetbytes[1] = Command_Packet.COMMAND_START_CODE_2;
    packetbytes[2] = Command_Packet.COMMAND_DEVICE_ID_1;
    packetbytes[3] = Command_Packet.COMMAND_DEVICE_ID_2;
    packetbytes[4] = Command_Packet.Parameter[0];
    packetbytes[5] = Command_Packet.Parameter[1];
    packetbytes[6] = Command_Packet.Parameter[2];
    packetbytes[7] = Command_Packet.Parameter[3];
    packetbytes[8] = Command_Packet.command[0];
    packetbytes[9] = Command_Packet.command[1];
    packetbytes[10] = Command_Packet_GetLowByte(checksum);
    packetbytes[11] = Command_Packet_GetHighByte(checksum);
    
    if(UseSerialDebug) {
         UART5_Write_Text("\r\n\r\n");
         UART5_Write_Text("FPS - SENT BYTES: ");
         FPS_GT511C3_SendToSerial(Response_Packet.RawBytes, 12);
         UART5_Write_Text("\r\n\r\n");
    }
 
    return &packetbytes;
}



In the screenshot you can see that the "SENT BYTES: " are the same as "FPS RECV: " bytes.

- - - Updated - - -
 

Attachments

  • FPS Test 2.png
    FPS Test 2.png
    35.5 KB · Views: 78
  • FPS Test 3.png
    FPS Test 3.png
    31.9 KB · Views: 94
  • FPS Test 4.png
    FPS Test 4.png
    13.1 KB · Views: 94
  • FPS Test 5.png
    FPS Test 5.png
    16.9 KB · Views: 86
Last edited:

The Arduino Code works fine without modification and without problems.

Now let me come to the C Code issue.

You can see the screenshots showing the working in Arduino and 2nd screenshot showing that there is a difference in sent butes for IsFingerPresent command (C Code) compared to Arduino Code.

The same Command_Packet_GetPackeytBytes() function is used for all the commands. So, there can't be any bug in that function.

See the attached PDFs. It shows Serial Terminal Output for Arduino Code and mikroC PRO PIC32 Code.

Also check the youtube video. It shows C Code toggling Sensor's Cmos LED.

In mikroC PRO PIC32 Code

Code:
FPS_GT511C3_IsPressFinger

returned true 5 times and also

Code:
FPS_GT511C3_CaptureFinger

executed 5 times but returned flase.


And here is the complete latest mikroC PRO PIC32 Code.


Code C - [expand]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
#define bool unsigned char
#define uint8_t unsigned char
 
#define TRUE 1
#define FALSE 0
 
unsigned char resp[20];
unsigned char gfirstbyte = 0;
bool gdone = FALSE;
unsigned int gIndex = 1, gCounter = 0;
 
bool UseSerialDebug;
 
//Command_Packet represents the 12 byte command that we send to the finger print scanner
 
struct Cmd_Packet {
    struct Cmds {
        enum Cmds_Enum {
              NotSet              = 0x00,                // Default value for enum. Scanner will return error if sent this.
              Open                = 0x01,                // Open Initialization
              Close               = 0x02,                // Close Termination
              UsbInternalCheck    = 0x03,                // UsbInternalCheck Check if the connected USB device is valid
              ChangeEBaudRate     = 0x04,                // ChangeBaudrate Change UART baud rate
              SetIAPMode          = 0x05,                // SetIAPMode Enter IAP Mode In this mode, FW Upgrade is available
              CmosLed             = 0x12,                // CmosLed Control CMOS LED
              GetEnrollCount      = 0x20,                // Get enrolled fingerprint count
              CheckEnrolled       = 0x21,                // Check whether the specified ID is already enrolled
              EnrollStart         = 0x22,                // Start an enrollment
              Enroll1             = 0x23,                // Make 1st template for an enrollment
              Enroll2             = 0x24,                // Make 2nd template for an enrollment
              Enroll3             = 0x25,                // Make 3rd template for an enrollment, merge three templates into one template, save merged template to the database
              IsPressFinger       = 0x26,                // Check if a finger is placed on the sensor
              DeleteID            = 0x40,                // Delete the fingerprint with the specified ID
              DeleteAll           = 0x41,                // Delete all fingerprints from the database
              Verify1_1           = 0x50,                // Verification of the capture fingerprint image with the specified ID
              Identify1_N         = 0x51,                // Identification of the capture fingerprint image with the database
              VerifyTemplate1_1   = 0x52,                // Verification of a fingerprint template with the specified ID
              IdentifyTemplate1_N = 0x53,                // Identification of a fingerprint template with the database
              CaptureFinger       = 0x60,                // Capture a fingerprint image(256x256) from the sensor
              MakeTemplate        = 0x61,                // Make template for transmission
              GetImage            = 0x62,                // Download the captured fingerprint image(256x256)
              GetRawImage         = 0x63,                // Capture & Download raw fingerprint image(320x240)
              GetTemplate         = 0x70,                // Download the template of the specified ID
              SetTemplate         = 0x71,                // Upload the template of the specified ID
              GetDatabaseStart    = 0x72,                // Start database download, obsolete
              GetDatabaseEnd      = 0x73,                // End database download, obsolete
              UpgradeFirmware     = 0x80,                // Not supported
              UpgradeISOCDImage   = 0x81,                // Not supported
              Ack                 = 0x30,                // Acknowledge.
              Nack                = 0x31                 // Non-acknowledge
         }Command;
    }Commands;
 
    unsigned char Parameter[4];                                                                // Parameter 4 bytes, changes meaning depending on command
 
    unsigned char COMMAND_START_CODE_1;        // Static byte to mark the beginning of a command packet        -        never changes
    unsigned char COMMAND_START_CODE_2;        // Static byte to mark the beginning of a command packet        -        never changes
    unsigned char COMMAND_DEVICE_ID_1;         // Device ID Byte 1 (lesser byte)                                                        -        theoretically never changes
    unsigned char COMMAND_DEVICE_ID_2;         // Device ID Byte 2 (greater byte)                                                        -        theoretically never changes
    unsigned char command[2];                  // Command 2 bytes
}Command_packet;
 
struct Resp_Packet {
    struct ErrCodes {
       enum Errs_Enum {
          NO_ERROR                    = 0x0000,        // Default value. no error
          NACK_TIMEOUT                = 0x1001,        // Obsolete, capture timeout
          NACK_INVALID_BAUDRATE       = 0x1002,        // Obsolete, Invalid serial baud rate
          NACK_INVALID_POS            = 0x1003,        // The specified ID is not between 0~199
          NACK_IS_NOT_USED            = 0x1004,        // The specified ID is not used
          NACK_IS_ALREADY_USED        = 0x1005,        // The specified ID is already used
          NACK_COMM_ERR               = 0x1006,        // Communication Error
          NACK_VERIFY_FAILED          = 0x1007,        // 1:1 Verification Failure
          NACK_IDENTIFY_FAILED        = 0x1008,        // 1:N Identification Failure
          NACK_DB_IS_FULL             = 0x1009,        // The database is full
          NACK_DB_IS_EMPTY            = 0x100A,        // The database is empty
          NACK_TURN_ERR               = 0x100B,        // Obsolete, Invalid order of the enrollment (The order was not as: EnrollStart -> Enroll1 -> Enroll2 -> Enroll3)
          NACK_BAD_FINGER             = 0x100C,        // Too bad fingerprint
          NACK_ENROLL_FAILED          = 0x100D,        // Enrollment Failure
          NACK_IS_NOT_SUPPORTED       = 0x100E,        // The specified command is not supported
          NACK_DEV_ERR                = 0x100F,        // Device Error, especially if Crypto-Chip is trouble
          NACK_CAPTURE_CANCELED       = 0x1010,        // Obsolete, The capturing is canceled
          NACK_INVALID_PARAM          = 0x1011,        // Invalid parameter
          NACK_FINGER_IS_NOT_PRESSED  = 0x1012,        // Finger is not pressed
          INVALID                     = 0XFFFF         // Used when parsing fails
       }Error, e;
 
 
    }ErrorCodes;
    
    //Response_Packet(unsigned char* buffer, bool UseSerialDebug);
    unsigned char RawBytes[13];
    unsigned char ParameterBytes[4];
    unsigned char ResponseBytes[2];
    bool ACK;
    unsigned char COMMAND_START_CODE_1;        // Static byte to mark the beginning of a command packet        -        never changes
    unsigned char COMMAND_START_CODE_2;        // Static byte to mark the beginning of a command packet        -        never changes
    unsigned char COMMAND_DEVICE_ID_1;        // Device ID Byte 1 (lesser byte)                                                        -        theoretically never changes
    unsigned char COMMAND_DEVICE_ID_2;        // Device ID Byte 2 (greater byte)                                                        -        theoretically never changes
 
}Response_Packet;
 
unsigned char* Command_Packet_GetPacketBytes();                                                        // returns the bytes to be transmitted
void Command_Packet_ParameterFromInt(unsigned int i);
unsigned int Command_Packet_CalculateChecksum();                                                // Checksum is calculated using byte addition
unsigned char Command_Packet_GetHighByte(unsigned int w);
unsigned char Command_Packet_GetLowByte(unsigned int w);
 
unsigned int Response_Packet_ErrorCodes_ParseFromBytes(unsigned char high, unsigned char low);
void Response_Packet_Response_Packet(unsigned char* buffer, bool UseSerialDebug);
 
int Response_Packet_IntFromParameter();
bool Response_Packet_CheckParsing(unsigned char b, unsigned char propervalue, unsigned char alternatevalue, char* varname, bool UseSerialDebug);
unsigned int Response_Packet_CalculateChecksum(unsigned char* buffer, int length);
unsigned char Response_Packet_GetHighByte(unsigned int w);
unsigned char Response_Packet_GetLowByte(unsigned int w);
 
//Initialises the device and gets ready for commands
void FPS_GT511C3_Open();
 
// Does not actually do anything (according to the datasheet)
// I implemented open, so had to do closed too... lol
void FPS_GT511C3_Close();
 
// Turns on or off the LED backlight
// LED must be on to see fingerprints
// Parameter: true turns on the backlight, false turns it off
// Returns: True if successful, false if not
bool FPS_GT511C3_SetLED(bool on);
 
// Changes the baud rate of the connection
// Parameter: 9600 - 115200
// Returns: True if success, false if invalid baud
// NOTE: Untested (don't have a logic level changer and a voltage divider is too slow)
bool FPS_GT511C3_ChangeBaudRate(unsigned int baud);
 
// Gets the number of enrolled fingerprints
// Return: The total number of enrolled fingerprints
unsigned int FPS_GT511C3_GetEnrollCount();
 
// checks to see if the ID number is in use or not
// Parameter: 0-199
// Return: True if the ID number is enrolled, false if not
bool FPS_GT511C3_CheckEnrolled(unsigned int id);
 
// Starts the Enrollment Process
// Parameter: 0-199
// Return:
//        0 - ACK
//        1 - Database is full
//        2 - Invalid Position
//        3 - Position(ID) is already used
unsigned int FPS_GT511C3_EnrollStart(unsigned int id);
 
// Gets the first scan of an enrollment
// Return:
//        0 - ACK
//        1 - Enroll Failed
//        2 - Bad finger
//        3 - ID in use
unsigned int FPS_GT511C3_Enroll1();
 
// Gets the Second scan of an enrollment
// Return:
//        0 - ACK
//        1 - Enroll Failed
//        2 - Bad finger
//        3 - ID in use
unsigned int FPS_GT511C3_Enroll2();
 
// Gets the Third scan of an enrollment
// Finishes Enrollment
// Return:
//        0 - ACK
//        1 - Enroll Failed
//        2 - Bad finger
//        3 - ID in use
unsigned int FPS_GT511C3_Enroll3();
 
// Checks to see if a finger is pressed on the FPS
// Return: true if finger pressed, false if not
bool FPS_GT511C3_IsPressFinger();
 
// Deletes the specified ID (enrollment) from the database
// Returns: true if successful, false if position invalid
bool FPS_GT511C3_DeleteID(unsigned int ID);
 
// Deletes all IDs (enrollments) from the database
// Returns: true if successful, false if db is empty
bool FPS_GT511C3_DeleteAll();
 
// Checks the currently pressed finger against a specific ID
// Parameter: 0-199 (id number to be checked)
// Returns:
//        0 - Verified OK (the correct finger)
//        1 - Invalid Position
//        2 - ID is not in use
//        3 - Verified FALSE (not the correct finger)
unsigned int FPS_GT511C3_Verify1_1(unsigned int id);
 
// Checks the currently pressed finger against all enrolled fingerprints
// Returns:
//        0-199: Verified against the specified ID (found, and here is the ID number)
//        200: Failed to find the fingerprint in the database
unsigned int FPS_GT511C3_Identify1_N();
 
// Captures the currently pressed finger into onboard ram
// Parameter: true for high quality image(slower), false for low quality image (faster)
// Generally, use high quality for enrollment, and low quality for verification/identification
// Returns: True if ok, false if no finger pressed
bool FPS_GT511C3_CaptureFinger(bool highquality);
 
//-= Not implemented commands =-
 
// Gets an image that is 258x202 (52116 bytes) and returns it in 407 Data_Packets
// Use StartDataDownload, and then GetNextDataPacket until done
// Returns: True (device confirming download starting)
// Not implemented due to memory restrictions on the arduino
// may revisit this if I find a need for it
//bool GetImage();
 
// Gets an image that is qvga 160x120 (19200 bytes) and returns it in 150 Data_Packets
// Use StartDataDownload, and then GetNextDataPacket until done
// Returns: True (device confirming download starting)
// Not implemented due to memory restrictions on the arduino
// may revisit this if I find a need for it
//bool GetRawImage();
 
// Gets a template from the fps (498 bytes) in 4 Data_Packets
// Use StartDataDownload, and then GetNextDataPacket until done
// Parameter: 0-199 ID number
// Returns:
//        0 - ACK Download starting
//        1 - Invalid position
//        2 - ID not used (no template to download
// Not implemented due to memory restrictions on the arduino
// may revisit this if I find a need for it
//int GetTemplate(int id);
 
// Uploads a template to the fps
// Parameter: the template (498 bytes)
// Parameter: the ID number to upload
// Parameter: Check for duplicate fingerprints already on fps
// Returns:
//        0-199 - ID duplicated
//        200 - Uploaded ok (no duplicate if enabled)
//        201 - Invalid position
//        202 - Communications error
//        203 - Device error
// Not implemented due to memory restrictions on the arduino
// may revisit this if I find a need for it
//int SetTemplate(byte* tmplt, int id, bool duplicateCheck);
 
// Commands that are not implemented (and why)
// VerifyTemplate1_1 - Couldn't find a good reason to implement this on an arduino
// IdentifyTemplate1_N - Couldn't find a good reason to implement this on an arduino
// MakeTemplate - Couldn't find a good reason to implement this on an arduino
// UsbInternalCheck - not implemented - Not valid config for arduino
// GetDatabaseStart - historical command, no longer supported
// GetDatabaseEnd - historical command, no longer supported
// UpgradeFirmware - Data Sheet says not supported
// UpgradeISOCDImage - Data Sheet says not supported
// SetIAPMode - for upgrading firmware (which is not supported)
// Ack and Nack        are listed as a commands for some unknown reason... not implemented
 
void FPS_GT511C3_serialPrintHex(unsigned char data_);
void FPS_GT511C3_SendToSerial(unsigned char data[], int length);
 
// resets the Data_Packet class, and gets ready to download
// Not implemented due to memory restrictions on the arduino
// may revisit this if I find a need for it
//void StartDataDownload();
 
// Returns the next data packet
// Not implemented due to memory restrictions on the arduino
// may revisit this if I find a need for it
//Data_Packet GetNextDataPacket();
 
void SendCommand(unsigned char cmd[], int length);
void GetResponse();
 
void ResetVars() {
    gfirstbyte = 0;
    gdone = FALSE;
    gIndex = 1;
}
 
unsigned char* Command_Packet_GetPacketBytes() {
    unsigned char Packetbytes[12];
    unsigned int cmd, checksum;
    // update command before calculating checksum (important!)
    cmd = Command_packet.Commands.Command;
    Command_Packet.command[0] = Command_Packet_GetLowByte(cmd);
    Command_Packet.command[1] = Command_Packet_GetHighByte(cmd);
 
    checksum = Command_Packet_CalculateChecksum();
 
    Packetbytes[0] = Command_Packet.COMMAND_START_CODE_1;
    packetbytes[1] = Command_Packet.COMMAND_START_CODE_2;
    packetbytes[2] = Command_Packet.COMMAND_DEVICE_ID_1;
    packetbytes[3] = Command_Packet.COMMAND_DEVICE_ID_2;
    packetbytes[4] = Command_Packet.Parameter[0];
    packetbytes[5] = Command_Packet.Parameter[1];
    packetbytes[6] = Command_Packet.Parameter[2];
    packetbytes[7] = Command_Packet.Parameter[3];
    packetbytes[8] = Command_Packet.command[0];
    packetbytes[9] = Command_Packet.command[1];
    packetbytes[10] = Command_Packet_GetLowByte(checksum);
    packetbytes[11] = Command_Packet_GetHighByte(checksum);
    
    return Packetbytes;
}
 
// Converts the int to bytes and puts them into the paramter array
void Command_Packet_ParameterFromInt(unsigned int i) {
    Command_Packet.Parameter[0] = (i & 0x000000ff);
    Command_Packet.Parameter[1] = (i & 0x0000ff00) >> 8;
    Command_Packet.Parameter[2] = (i & 0x00ff0000) >> 16;
    Command_Packet.Parameter[3] = (i & 0xff000000) >> 24;
}
 
// Returns the high byte from a word
unsigned char Command_Packet_GetHighByte(unsigned int w) {
    return (unsigned char)(w >> 8) & 0x00FF;
}
 
// Returns the low byte from a word
unsigned char Command_Packet_GetLowByte(unsigned int w) {
    return (unsigned char)w & 0x00FF;
}
 
unsigned int Command_Packet_CalculateChecksum() {
    unsigned int w = 0;
 
    w += Command_Packet.COMMAND_START_CODE_1;
    w += Command_Packet.COMMAND_START_CODE_2;
    w += Command_Packet.COMMAND_DEVICE_ID_1;
    w += Command_Packet.COMMAND_DEVICE_ID_2;
    w += Command_Packet.Parameter[0];
    w += Command_Packet.Parameter[1];
    w += Command_Packet.Parameter[2];
    w += Command_Packet.Parameter[3];
    w += Command_Packet.command[0];
    w += Command_Packet.command[1];
 
    return w;
}
 
// Gets an int from the parameter bytes
unsigned int Response_Packet_IntFromParameter() {
    unsigned int retval = 0;
 
    retval = (retval << 8) + Response_Packet.ParameterBytes[3];
    retval = (retval << 8) + Response_Packet.ParameterBytes[2];
    retval = (retval << 8) + Response_Packet.ParameterBytes[1];
    retval = (retval << 8) + Response_Packet.ParameterBytes[0];
 
    return retval;
}
 
// calculates the checksum from the bytes in the Packet
//unsigned int Response_Packet_CalculateChecksum(unsigned char buffer[], int length) {
unsigned int Response_Packet_CalculateChecksum(unsigned char buffer[], int length) {
    unsigned int checksum = 0;
    unsigned int i = 0;
 
    for(i = 1; i < length + 1; i++) {
        checksum += buffer[i];
    }
 
    return checksum;
}
 
// Returns the high byte from a word
unsigned char Response_Packet_GetHighByte(unsigned int w) {
    return (unsigned char)(w>>8)&0x00FF;
}
 
// Returns the low byte from a word
unsigned char Response_Packet_GetLowByte(unsigned int w) {
    return (unsigned char)w&0x00FF;
}
 
// parses bytes into one of the possible errors from the finger print scanner
//Response_Packet::ErrorCodes::Errors_Enum Response_Packet_ErrorCodes_ParseFromBytes(unsigned char high, unsigned char low)
unsigned int Response_Packet_ErrorCodes_ParseFromBytes(unsigned char high, unsigned char low) {
    Response_Packet.ErrorCodes.e = INVALID;
 
    if (high == 0x00)
    {
    }
    // grw 01/03/15 - replaced if clause with else clause for any non-zero high byte
    // if (high == 0x01)
    // {
    else {
        switch(low) {
            case 0x00: Response_Packet.ErrorCodes.e = NO_ERROR; break;
            case 0x01: Response_Packet.ErrorCodes.e = NACK_TIMEOUT; break;
            case 0x02: Response_Packet.ErrorCodes.e = NACK_INVALID_BAUDRATE; break;
            case 0x03: Response_Packet.ErrorCodes.e = NACK_INVALID_POS; break;
            case 0x04: Response_Packet.ErrorCodes.e = NACK_IS_NOT_USED; break;
            case 0x05: Response_Packet.ErrorCodes.e = NACK_IS_ALREADY_USED; break;
            case 0x06: Response_Packet.ErrorCodes.e = NACK_COMM_ERR; break;
            case 0x07: Response_Packet.ErrorCodes.e = NACK_VERIFY_FAILED; break;
            case 0x08: Response_Packet.ErrorCodes.e = NACK_IDENTIFY_FAILED; break;
            case 0x09: Response_Packet.ErrorCodes.e = NACK_DB_IS_FULL; break;
            case 0x0A: Response_Packet.ErrorCodes.e = NACK_DB_IS_EMPTY; break;
            case 0x0B: Response_Packet.ErrorCodes.e = NACK_TURN_ERR; break;
            case 0x0C: Response_Packet.ErrorCodes.e = NACK_BAD_FINGER; break;
            case 0x0D: Response_Packet.ErrorCodes.e = NACK_ENROLL_FAILED; break;
            case 0x0E: Response_Packet.ErrorCodes.e = NACK_IS_NOT_SUPPORTED; break;
            case 0x0F: Response_Packet.ErrorCodes.e = NACK_DEV_ERR; break;
            case 0x10: Response_Packet.ErrorCodes.e = NACK_CAPTURE_CANCELED; break;
            case 0x11: Response_Packet.ErrorCodes.e = NACK_INVALID_PARAM; break;
            case 0x12: Response_Packet.ErrorCodes.e = NACK_FINGER_IS_NOT_PRESSED; break;
        };
    }
 
    return Response_Packet.ErrorCodes.e;
}
 
// checks to see if the byte is the proper value, and logs it to the serial channel if not
bool Response_Packet_CheckParsing(unsigned char b, unsigned char propervalue, unsigned char alternatevalue, char* varname, bool UseSerialDebug) {
    bool retval;
    char str[22];
 
    retval = (b != propervalue) && (b != alternatevalue);
 
    if((UseSerialDebug) && (retval)) {
        UART5_Write_Text("\r\n");
        UART5_Write_Text("Response_Packet parsing error \r\n");
        UART5_Write_Text(varname);
        UART5_Write_Text(" ");
        ByteToHex(propervalue, str);
        Ltrim(str);
        Rtrim(str);
        UART5_Write_Text(str);
        UART5_Write_Text(" || ");
        ByteToHex(alternatevalue, str);
        Ltrim(str);
        Rtrim(str);
        UART5_Write_Text(str);
        UART5_Write_Text(" != ");
        ByteToHex(b, str);
        Ltrim(str);
        Rtrim(str);
        UART5_Write_Text(str);
    }
    
    return retval;
}
 
void Response_Packet_Response_Packet(unsigned char* buffer, bool UseSerialDebug) {
 
    unsigned int checksum, i;
    unsigned char checksum_low;
    unsigned char checksum_high;
 
    Response_Packet_CheckParsing(buffer[1], Response_Packet.COMMAND_START_CODE_1, Response_Packet.COMMAND_START_CODE_1, "COMMAND_START_CODE_1", UseSerialDebug);
    Response_Packet_CheckParsing(buffer[2], Response_Packet.COMMAND_START_CODE_2, Response_Packet.COMMAND_START_CODE_2, "COMMAND_START_CODE_2", UseSerialDebug);
    Response_Packet_CheckParsing(buffer[3], Response_Packet.COMMAND_DEVICE_ID_1, Response_Packet.COMMAND_DEVICE_ID_1, "COMMAND_DEVICE_ID_1", UseSerialDebug);
    Response_Packet_CheckParsing(buffer[4], Response_Packet.COMMAND_DEVICE_ID_2, Response_Packet.COMMAND_DEVICE_ID_2, "COMMAND_DEVICE_ID_2", UseSerialDebug);
    Response_Packet_CheckParsing(buffer[9], 0x30, 0x31, "AckNak_LOW", UseSerialDebug);
    if(buffer[9] == 0x30)Response_Packet.ACK = TRUE; else Response_Packet.ACK = FALSE;
    Response_Packet_CheckParsing(buffer[10], 0x00, 0x00, "AckNak_HIGH", UseSerialDebug);
 
    checksum = Response_Packet_CalculateChecksum(buffer, 10);
    checksum_low = Response_Packet_GetLowByte(checksum);
    checksum_high = Response_Packet_GetHighByte(checksum);
    Response_Packet_CheckParsing(buffer[11], checksum_low, checksum_low, "Checksum_LOW", UseSerialDebug);
    Response_Packet_CheckParsing(buffer[12], checksum_high, checksum_high, "Checksum_HIGH", UseSerialDebug);
 
    Response_Packet.ErrorCodes.Error = Response_Packet_ErrorCodes_ParseFromBytes(buffer[6], buffer[5]);
 
    Response_Packet.ParameterBytes[0] = buffer[5];
    Response_Packet.ParameterBytes[1] = buffer[6];
    Response_Packet.ParameterBytes[2] = buffer[7];
    Response_Packet.ParameterBytes[3] = buffer[8];
    Response_Packet.ResponseBytes[0] = buffer[9];
    Response_Packet.ResponseBytes[1] = buffer[10];
 
    for(i = 1; i < 13; i++) {
        Response_Packet.RawBytes[i-1] = buffer[i];
    }
}
 
/*
void Response_Packet_Response_Packet(unsigned char* buffer, bool UseSerialDebug) {
 
    unsigned int checksum, i;
    unsigned char checksum_low;
    unsigned char checksum_high;
 
    Response_Packet_CheckParsing(buffer[0], Response_Packet.COMMAND_START_CODE_1, Response_Packet.COMMAND_START_CODE_1, "COMMAND_START_CODE_1", UseSerialDebug);
    Response_Packet_CheckParsing(buffer[1], Response_Packet.COMMAND_START_CODE_2, Response_Packet.COMMAND_START_CODE_2, "COMMAND_START_CODE_2", UseSerialDebug);
    Response_Packet_CheckParsing(buffer[2], Response_Packet.COMMAND_DEVICE_ID_1, Response_Packet.COMMAND_DEVICE_ID_1, "COMMAND_DEVICE_ID_1", UseSerialDebug);
    Response_Packet_CheckParsing(buffer[3], Response_Packet.COMMAND_DEVICE_ID_2, Response_Packet.COMMAND_DEVICE_ID_2, "COMMAND_DEVICE_ID_2", UseSerialDebug);
    Response_Packet_CheckParsing(buffer[8], 0x30, 0x31, "AckNak_LOW", UseSerialDebug);
    if(buffer[8] == 0x30)Response_Packet.ACK = TRUE; else Response_Packet.ACK = FALSE;
    Response_Packet_CheckParsing(buffer[9], 0x00, 0x00, "AckNak_HIGH", UseSerialDebug);
 
    checksum = Response_Packet_CalculateChecksum(buffer, 10);
    checksum_low = Response_Packet_GetLowByte(checksum);
    checksum_high = Response_Packet_GetHighByte(checksum);
    Response_Packet_CheckParsing(buffer[10], checksum_low, checksum_low, "Checksum_LOW", UseSerialDebug);
    Response_Packet_CheckParsing(buffer[11], checksum_high, checksum_high, "Checksum_HIGH", UseSerialDebug);
 
    Response_Packet.ErrorCodes.Error = Response_Packet_ErrorCodes_ParseFromBytes(buffer[5], buffer[4]);
 
    Response_Packet.ParameterBytes[0] = buffer[4];
    Response_Packet.ParameterBytes[1] = buffer[5];
    Response_Packet.ParameterBytes[2] = buffer[6];
    Response_Packet.ParameterBytes[3] = buffer[7];
    Response_Packet.ResponseBytes[0] = buffer[8];
    Response_Packet.ResponseBytes[1] = buffer[9];
 
    for(i = 0; i < 12; i++) {
        Response_Packet.RawBytes[i] = buffer[i];
    }
}
*/
 
void FPS_GT511C3_SendCommand(unsigned char cmd[], int length) {
    unsigned int i;
    unsigned char str[22];
 
    for(i = 0; i < length; i++) {
         UART2_Write(cmd[i]);
    }
 
    if(UseSerialDebug) {
        UART5_Write_Text("FPS - SEND: ");
        for(i = 0; i < length; i++) {
           ByteToHex(cmd[i], str);
           Ltrim(str);
           Rtrim(str);
           strcat(str, " ");
           UART5_Write_Text(str);
        }
 
        UART5_Write_Text("\r\n");
    }
}
 
void FPS_GT511C3_PrintResponseBytes(unsigned char response[], unsigned int length) {
     unsigned int i;
     unsigned char str[22];
     
     for(i = 0; i < length; i++) {
         ByteToHex(response[i], str);
         Ltrim(str);
         Rtrim(str);
         strcat(str, " ");
         UART5_Write_Text(str);
     }
}
 
// sends a byte to the serial debugger in the hex format we want EX "0F"
void FPS_GT511C3_serialPrintHex(unsigned char data_) {
    char tmp[22];
    IntToHex(data_, tmp);
    Ltrim(tmp);
    Rtrim(tmp);
    UART5_Write_Text(tmp);
}
 
// sends the bye aray to the serial debugger in our hex format EX: "00 AF FF 10 00 13"
void FPS_GT511C3_SendToSerial(unsigned char data_[], int length) {
    bool first = TRUE;
    unsigned int i;
 
    UART5_Write_Text(""");
 
    for(i = 0; i < length; i++) {
       if(first)first = FALSE;
       else UART5_Write_Text(" ");
       FPS_GT511C3_serialPrintHex(data_[i]);
    }
 
    UART5_Write_Text(""");
}
 
// Gets the response to the command from the software serial channel (and waits for it)
void FPS_GT511C3_GetResponse() {
    /*
    unsigned char firstbyte = 0;
    bool done = FALSE;
    unsigned char resp[12];
    unsigned int i;
 
    while(done == FALSE) {
       firstbyte = (unsigned char)UART2_Read();
 
       if(firstbyte == Response_Packet.COMMAND_START_CODE_1) {
            done = TRUE;
       }
    }
 
    resp[0] = firstbyte;
 
    for(i = 1; i < 12; i++) {
          resp[i] = (unsigned char)UART2_Read();
    }
    */
    Delay_ms(500);
    Response_Packet_Response_Packet(resp, UseSerialDebug);
 
    if(UseSerialDebug) {
        UART5_Write_Text("FPS - RECV: ");
        FPS_GT511C3_PrintResponseBytes(Response_Packet.Raw  Bytes, 12);
        UART5_Write_Text("\r\n\r\n");
    }
}
 
bool FPS_GT511C3_ChangeBaudRate(int baud) {
    unsigned char* Packetbytes;
    bool retval;
    
    if((baud == 9600) || (baud == 19200) || (baud == 38400) || (baud == 57600) || (baud == 115200)) {
        if(UseSerialDebug)UART5_Write_Text("FPS - ChangeBaudRate\r\n");
        Command_Packet.Commands.Command = Open;
        Command_Packet_ParameterFromInt(baud);
        Packetbytes = Command_Packet_GetPacketBytes();
        FPS_GT511C3_SendCommand(Packetbytes, 12);
        FPS_GT511C3_GetResponse();
        ResetVars();
        retval = Response_Packet.ACK;
        
        if(retval) {
            UART2_Init(baud);
            Delay_ms(200);
        }
 
        return retval;
    }
    
    return FALSE;
}
 
void FPS_GT511C3_Open() {
    unsigned char* Packetbytes;
    
    if(UseSerialDebug)UART5_Write_Text("FPS - Open\r\n");
    Command_Packet.Commands.Command = Open;
    Command_Packet.Parameter[0] = 0x00;
    Command_Packet.Parameter[1] = 0x00;
    Command_Packet.Parameter[2] = 0x00;
    Command_Packet.Parameter[3] = 0x00;
    Packetbytes = Command_Packet_GetPacketBytes();
    memset(resp, '\0', sizeof(resp));
    FPS_GT511C3_SendCommand(Packetbytes, 12);
    FPS_GT511C3_GetResponse();
    //PrintResponseBytes(resp);
    ResetVars();
}
 
// Turns on or off the LED backlight
// Parameter: true turns on the backlight, false turns it off
// Returns: True if successful, false if not
bool FPS_GT511C3_SetLED(bool on) {
    unsigned char* Packetbytes;
    bool retval;
    
    Command_Packet.Commands.Command = CmosLed;
    
    if(on) {
       if(UseSerialDebug)UART5_Write_Text("FPS - LED on\r\n");
       Command_Packet.Parameter[0] = 0x01;
    }
    else {
       if(UseSerialDebug)UART5_Write_Text("FPS - LED off\r\n");
       Command_Packet.Parameter[0] = 0x00;
    }
    
    Command_Packet.Parameter[1] = 0x00;
    Command_Packet.Parameter[2] = 0x00;
    Command_Packet.Parameter[3] = 0x00;
    Packetbytes = Command_Packet_GetPacketBytes();
    memset(resp, '\0', sizeof(resp));
    FPS_GT511C3_SendCommand(Packetbytes, 12);
    FPS_GT511C3_GetResponse();
    ResetVars();
    retval = TRUE;
    if(Response_Packet.ACK == FALSE)retval = FALSE;
    
    return retval;
}
 
// Gets the number of enrolled fingerprints
// Return: The total number of enrolled fingerprints
unsigned int FPS_GT511C3_GetEnrollCount() {
    unsigned char* Packetbytes;
    unsigned int retval;
    
    if(UseSerialDebug)UART5_Write_Text("FPS - GetEnrolledCount\r\n");
    Command_Packet.Commands.Command = GetEnrollCount;
    Command_Packet.Parameter[0] = 0x00;
    Command_Packet.Parameter[1] = 0x00;
    Command_Packet.Parameter[2] = 0x00;
    Command_Packet.Parameter[3] = 0x00;
    Packetbytes = Command_Packet_GetPacketBytes();
    memset(resp, '\0', sizeof(resp));
    FPS_GT511C3_SendCommand(Packetbytes, 12);
    FPS_GT511C3_GetResponse();
    ResetVars();
 
    retval = Response_Packet_IntFromParameter();
    return retval;
}
 
// checks to see if the ID number is in use or not
// Parameter: 0-199
// Return: True if the ID number is enrolled, false if not
bool FPS_GT511C3_CheckEnrolled(unsigned int id) {
    unsigned char* Packetbytes;
    bool retval;
    
    if(UseSerialDebug)UART5_Write_Text("FPS - CheckEnrolled\r\n");
    Command_Packet.Commands.Command = CheckEnrolled;
    Command_Packet_ParameterFromInt(id);
    Packetbytes = Command_Packet_GetPacketBytes();
    memset(resp, '\0', sizeof(resp));
    FPS_GT511C3_SendCommand(Packetbytes, 12);
    FPS_GT511C3_GetResponse();
    ResetVars();
    retval = FALSE;
    retval = Response_Packet.ACK;
    
    return retval;
}
 
// Starts the Enrollment Process
// Parameter: 0-199
// Return:
//        0 - ACK
//        1 - Database is full
//        2 - Invalid Position
//        3 - Position(ID) is already used
unsigned int FPS_GT511C3_EnrollStart(unsigned int id) {
    unsigned char* Packetbytes;
    unsigned int retval;
    
    if(UseSerialDebug)UART5_Write_Text("FPS - EnrollStart\r\n");
    Command_Packet.Commands.Command = EnrollStart;
    Command_Packet_ParameterFromInt(id);
    Packetbytes = Command_Packet_GetPacketBytes();
    memset(resp, '\0', sizeof(resp));
    FPS_GT511C3_SendCommand(Packetbytes, 12);
    FPS_GT511C3_GetResponse();
    ResetVars();
    retval = 0;
 
    if(Response_Packet.ACK == FALSE)
    {
         if(Response_Packet.ErrorCodes.Error == NACK_DB_IS_FULL)retval = 1;
         if(Response_Packet.ErrorCodes.Error == NACK_INVALID_POS)retval = 2;
         if(Response_Packet.ErrorCodes.Error == NACK_IS_ALREADY_USED)retval = 3;
    }
 
    return retval;
}
 
// Gets the first scan of an enrollment
// Return:
//        0 - ACK
//        1 - Enroll Failed
//        2 - Bad finger
//        3 - ID in use
unsigned int FPS_GT511C3_Enroll1() {
    unsigned char* Packetbytes;
    unsigned int retval;
 
    if(UseSerialDebug)UART5_Write_Text("FPS - Enroll1\r\n");
    Command_Packet.Commands.Command = Enroll1;
    Packetbytes = Command_Packet_GetPacketBytes();
    memset(resp, '\0', sizeof(resp));
    FPS_GT511C3_SendCommand(Packetbytes, 12);
    FPS_GT511C3_GetResponse();
    ResetVars();
    retval = Response_Packet_IntFromParameter();
    
    if(retval < 200) retval = 3; else retval = 0;
 
    if(Response_Packet.ACK == FALSE)
    {
        if(Response_Packet.ErrorCodes.Error == NACK_ENROLL_FAILED)retval = 1;
        if(Response_Packet.ErrorCodes.Error == NACK_BAD_FINGER)retval = 2;
    }
 
 
    if(Response_Packet.ACK) return 0; else return retval;
}
 
// Gets the Second scan of an enrollment
// Return:
//        0 - ACK
//        1 - Enroll Failed
//        2 - Bad finger
//        3 - ID in use
unsigned int FPS_GT511C3_Enroll2() {
    unsigned char* Packetbytes;
    unsigned int retval;
 
    if(UseSerialDebug)UART5_Write_Text("FPS - Enroll1\r\n");
    Command_Packet.Commands.Command = Enroll2;
    Packetbytes = Command_Packet_GetPacketBytes();
    memset(resp, '\0', sizeof(resp));
    FPS_GT511C3_SendCommand(Packetbytes, 12);
    FPS_GT511C3_GetResponse();
    ResetVars();
    retval = Response_Packet_IntFromParameter();
 
    if(retval < 200) retval = 3; else retval = 0;
 
    if(Response_Packet.ACK == FALSE)
    {
        if(Response_Packet.ErrorCodes.Error == NACK_ENROLL_FAILED)retval = 1;
        if(Response_Packet.ErrorCodes.Error == NACK_BAD_FINGER)retval = 2;
    }
 
 
    if(Response_Packet.ACK) return 0; else return retval;
}
 
// Gets the Third scan of an enrollment
// Finishes Enrollment
// Return:
//        0 - ACK
//        1 - Enroll Failed
//        2 - Bad finger
//        3 - ID in use
unsigned int FPS_GT511C3_Enroll3() {
    unsigned char* Packetbytes;
    unsigned int retval;
 
    if(UseSerialDebug)UART5_Write_Text("FPS - Enroll1\r\n");
    Command_Packet.Commands.Command = Enroll3;
    Packetbytes = Command_Packet_GetPacketBytes();
    memset(resp, '\0', sizeof(resp));
    FPS_GT511C3_SendCommand(Packetbytes, 12);
    FPS_GT511C3_GetResponse();
    ResetVars();
    retval = Response_Packet_IntFromParameter();
 
    if(retval < 200) retval = 3; else retval = 0;
 
    if(Response_Packet.ACK == FALSE)
    {
        if(Response_Packet.ErrorCodes.Error == NACK_ENROLL_FAILED)retval = 1;
        if(Response_Packet.ErrorCodes.Error == NACK_BAD_FINGER)retval = 2;
    }
 
 
    if(Response_Packet.ACK) return 0; else return retval;
}
 
// Checks to see if a finger is pressed on the FPS
// Return: true if finger pressed, false if not
bool FPS_GT511C3_IsPressFinger() {
    unsigned char* Packetbytes;
    bool retval;
    unsigned int pval;
    
    if(UseSerialDebug)UART5_Write_Text("FPS - IsPressFinger\r\n");
    Command_Packet.Commands.Command = IsPressFinger;
    Packetbytes = Command_Packet_GetPacketBytes();
    memset(resp, '\0', sizeof(resp));
    FPS_GT511C3_SendCommand(Packetbytes, 12);
    FPS_GT511C3_GetResponse();
    ResetVars();
    retval = FALSE;
    pval = Response_Packet.ParameterBytes[0];
    pval += Response_Packet.ParameterBytes[1];
    pval += Response_Packet.ParameterBytes[2];
    pval += Response_Packet.ParameterBytes[3];
    
    if(pval == 0)retval = TRUE;
 
    return retval;
}
 
// Deletes the specified ID (enrollment) from the database
// Parameter: 0-199 (id number to be deleted)
// Returns: true if successful, false if position invalid
bool FPS_GT511C3_DeleteID(int id) {
    unsigned char* Packetbytes;
    bool retval;
 
    if(UseSerialDebug)UART5_Write_Text("FPS - DeleteID\r\n");
    Command_Packet.Commands.Command = DeleteID;
    Command_Packet_ParameterFromInt(id);
    Packetbytes = Command_Packet_GetPacketBytes();
    memset(resp, '\0', sizeof(resp));
    FPS_GT511C3_SendCommand(Packetbytes, 12);
    FPS_GT511C3_GetResponse();
    ResetVars();
    retval = Response_Packet.ACK;
 
    return retval;
}
 
// Deletes all IDs (enrollments) from the database
// Returns: true if successful, false if db is empty
bool FPS_GT511C3_DeleteAll() {
    unsigned char* Packetbytes;
    bool retval;
    
    if(UseSerialDebug)UART5_Write_Text("FPS - DeleteAll\r\n");
    Command_Packet.Commands.Command = DeleteAll;
    Packetbytes = Command_Packet_GetPacketBytes();
    memset(resp, '\0', sizeof(resp));
    FPS_GT511C3_SendCommand(Packetbytes, 12);
    FPS_GT511C3_GetResponse();
    ResetVars();
    retval = Response_Packet.ACK;
 
    return retval;
}
 
// Checks the currently pressed finger against a specific ID
// Parameter: 0-199 (id number to be checked)
// Returns:
//        0 - Verified OK (the correct finger)
//        1 - Invalid Position
//        2 - ID is not in use
//        3 - Verified FALSE (not the correct finger)
unsigned int FPS_GT511C3_Verify1_1(int id) {
    unsigned char* Packetbytes;
    unsigned int retval;
    
    if(UseSerialDebug)UART5_Write_Text("FPS - Verify1_1\r\n");
    Command_Packet.Commands.Command = Verify1_1;
    Command_Packet_ParameterFromInt(id);
    Packetbytes = Command_Packet_GetPacketBytes();
    memset(resp, '\0', sizeof(resp));
    FPS_GT511C3_SendCommand(Packetbytes, 12);
    FPS_GT511C3_GetResponse();
    ResetVars();
    retval = 0;
    
 
    if(Response_Packet.ACK == FALSE)
    {
          retval = 3; // grw 01/03/15 - set default value of not verified before assignment
          
          if (Response_Packet.ErrorCodes.Error == NACK_INVALID_POS)retval = 1;
          if (Response_Packet.ErrorCodes.Error == NACK_IS_NOT_USED) retval = 2;
          if (Response_Packet.ErrorCodes.Error == NACK_VERIFY_FAILED) retval = 3;
    }
 
 
    return retval;
}
 
// Checks the currently pressed finger against all enrolled fingerprints
// Returns:
//        0-199: Verified against the specified ID (found, and here is the ID number)
//        200: Failed to find the fingerprint in the database
unsigned int FPS_GT511C3_Identify1_N() {
    unsigned char* Packetbytes;
    unsigned int retval;
    
    if(UseSerialDebug)UART5_Write_Text("FPS - Identify1_N\r\n");
    Command_Packet.Commands.Command = Identify1_N;
    Packetbytes = Command_Packet_GetPacketBytes();
    memset(resp, '\0', sizeof(resp));
    FPS_GT511C3_SendCommand(Packetbytes, 12);
    FPS_GT511C3_GetResponse();
    ResetVars();
    retval = Response_Packet_IntFromParameter();
    
    if(retval > 200) retval = 200;
 
    return retval;
}
 
// Captures the currently pressed finger into onboard ram use this prior to other commands
// Parameter: true for high quality image(slower), false for low quality image (faster)
// Generally, use high quality for enrollment, and low quality for verification/identification
// Returns: True if ok, false if no finger pressed
bool FPS_GT511C3_CaptureFinger(bool highquality) {
 
    unsigned char *Packetbytes;
    bool retval;
 
    if(UseSerialDebug)UART5_Write_Text("FPS - CaptureFinger\r\n");
    Command_Packet.Commands.Command = CaptureFinger;
    if(highquality) {
        Command_Packet_ParameterFromInt(1);
    }
    else {
        Command_Packet_ParameterFromInt(0);
    }
    
    Packetbytes = Command_Packet_GetPacketBytes();
    memset(resp, '\0', sizeof(resp));
    FPS_GT511C3_SendCommand(Packetbytes, 12);
    FPS_GT511C3_GetResponse();
    ResetVars();
    retval = Response_Packet.ACK;
 
    return retval;
}
 
void Enroll() {
     // Enroll test
    unsigned char str[17];
    // find open enroll id
    static int enrollid = 0;
    bool bret;
    unsigned int iret;
    bool usedid = TRUE;
    
    while(usedid == TRUE) {
        usedid = FPS_GT511C3_CheckEnrolled(enrollid);
        if(usedid == TRUE)enrollid++;
    }
    
    IntToStr(enrollid, str);
    Ltrim(str);
    Rtrim(str);
    strcat(str, "\r\n");
    UART5_Write_Text(str);
 
    FPS_GT511C3_EnrollStart(enrollid);
 
    // enroll
    UART5_Write_Text("Press finger to Enroll #");
    IntToStr(enrollid, str);
    Ltrim(str);
    Rtrim(str);
    strcat(str, "\r\n");
    UART5_Write_Text(str);
    while(FPS_GT511C3_IsPressFinger() == FALSE);//Delay_ms(200);
    bret = FPS_GT511C3_CaptureFinger(TRUE);
    iret = 0;
    
    if(bret != FALSE) {
        UART5_Write_Text("Remove finger\r\n");
        FPS_GT511C3_Enroll1();
        while(FPS_GT511C3_IsPressFinger() == TRUE);//Delay_ms(100);
        UART5_Write_Text("Press same finger again\r\n");
        while(FPS_GT511C3_IsPressFinger() == FALSE);//Delay_ms(100);
        bret = FPS_GT511C3_CaptureFinger(TRUE);
        
        if(bret != FALSE)
        {
                UART5_Write_Text("Remove finger\r\n");
                FPS_GT511C3_Enroll2();
                while(FPS_GT511C3_IsPressFinger() == TRUE);//Delay_ms(200);
                UART5_Write_Text("Press same finger yet again\r\n");
                while(FPS_GT511C3_IsPressFinger() == FALSE);//Delay_ms(200);
                bret = FPS_GT511C3_CaptureFinger(TRUE);
                
                if(bret != FALSE) {
                    UART5_Write_Text("Remove finger\r\n");
                    
                    iret = FPS_GT511C3_Enroll3();
                    if(iret == 0) {
                        UART5_Write_Text("Enrolling Successfull\r\n");
                    }
                    else {
                        UART5_Write_Text("Enrolling Failed with error code:");
                        IntToStr(iret, str);
                        Ltrim(str);
                        Rtrim(str);
                        strcat(str, "\r\n");
                        UART5_Write_Text(str);
                    }
                }
                else UART5_Write_Text("Failed to capture third finger\r\n");
        }
        else UART5_Write_Text("Failed to capture second finger\r\n");
    }
    else UART5_Write_Text("Failed to capture first finger\r\n");
}
 
void UART2() iv IVT_UART_2 ilevel 2 ics ICS_AUTO {
    
    if(gdone = TRUE) {
       resp[gIndex++] = UART2_Read();
    }
    else if(gdone == FALSE) {
       gfirstbyte = UART2_Read();
       
       if(gfirstbyte == Response_Packet.COMMAND_START_CODE_1) {
            resp[0] = gfirstbyte;
            gIndex = 1;
            gdone = TRUE;
       }
    }
    
    U2RXIF_bit = 0;
}
 
void main() {
 
    AD1PCFG = 0xFFFF;
    JTAGEN_bit = 0;
    
    TRISB = 0x00000000;
 
    Command_Packet.COMMAND_START_CODE_1 = 0x55;
    Command_Packet.COMMAND_START_CODE_2 = 0xAA;
    Command_Packet.COMMAND_DEVICE_ID_1 = 0x01;
    Command_Packet.COMMAND_DEVICE_ID_2 = 0x00;
    
    Response_Packet.COMMAND_START_CODE_1 = 0x55;
    Response_Packet.COMMAND_START_CODE_2 = 0xAA;
    Response_Packet.COMMAND_DEVICE_ID_1 = 0x01;
    Response_Packet.COMMAND_DEVICE_ID_2 = 0x00;
    
    UART5_Init(9600);
    Delay_ms(200);
    UART2_Init(9600);
    Delay_ms(200);
    
    U2IP0_bit = 0;                     // Set UART2 interrupt
    U2IP1_bit = 1;                     // Set interrupt priorities
    U2IP2_bit = 1;                     // Set UART2 interrupt to level 6
 
    U2RXIE_bit = 1;
    U2RXIF_bit = 0;
    EnableInterrupts();       // Enable all interrupts
    
    UseSerialDebug = TRUE;
    
    Delay_ms(3000);
    
    FPS_GT511C3_Open();
    Delay_ms(200);
    FPS_GT511C3_SetLED(1);
    Delay_ms(200);
    FPS_GT511C3_DeleteAll();
    
    while(1) {
    
          Delay_ms(1000);
          Enroll();
          //FPS_GT511C3_SetLED(1);
          //Delay_ms(2000);
          //FPS_GT511C3_SetLED(0);
    }
}




The changes made are like this.

This is the original C++ Code.


Code C - [expand]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// creates and parses a response packet from the finger print scanner
Response_Packet::Response_Packet(byte* buffer, bool UseSerialDebug)
{
    CheckParsing(buffer[0], COMMAND_START_CODE_1, COMMAND_START_CODE_1, "COMMAND_START_CODE_1", UseSerialDebug);
    CheckParsing(buffer[1], COMMAND_START_CODE_2, COMMAND_START_CODE_2, "COMMAND_START_CODE_2", UseSerialDebug);
    CheckParsing(buffer[2], COMMAND_DEVICE_ID_1, COMMAND_DEVICE_ID_1, "COMMAND_DEVICE_ID_1", UseSerialDebug);
    CheckParsing(buffer[3], COMMAND_DEVICE_ID_2, COMMAND_DEVICE_ID_2, "COMMAND_DEVICE_ID_2", UseSerialDebug);
    CheckParsing(buffer[8], 0x30, 0x31, "AckNak_LOW", UseSerialDebug);
    if (buffer[8] == 0x30) ACK = true; else ACK = false;
    CheckParsing(buffer[9], 0x00, 0x00, "AckNak_HIGH", UseSerialDebug);
 
    word checksum = CalculateChecksum(buffer, 10);
    byte checksum_low = GetLowByte(checksum);
    byte checksum_high = GetHighByte(checksum);
    CheckParsing(buffer[10], checksum_low, checksum_low, "Checksum_LOW", UseSerialDebug);
    CheckParsing(buffer[11], checksum_high, checksum_high, "Checksum_HIGH", UseSerialDebug);
    
    Error = ErrorCodes::ParseFromBytes(buffer[5], buffer[4]);
 
    ParameterBytes[0] = buffer[4];
    ParameterBytes[1] = buffer[5];
    ParameterBytes[2] = buffer[6];
    ParameterBytes[3] = buffer[7];
    ResponseBytes[0]=buffer[8];
    ResponseBytes[1]=buffer[9];
    for (int i=0; i < 12; i++)
    {
        RawBytes[i]=buffer[i];
    }
}



This is the modified C function.


Code C - [expand]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
void Response_Packet_Response_Packet(unsigned char* buffer, bool UseSerialDebug) {
 
    unsigned int checksum, i;
    unsigned char checksum_low;
    unsigned char checksum_high;
 
    Response_Packet_CheckParsing(buffer[1], Response_Packet.COMMAND_START_CODE_1, Response_Packet.COMMAND_START_CODE_1, "COMMAND_START_CODE_1", UseSerialDebug);
    Response_Packet_CheckParsing(buffer[2], Response_Packet.COMMAND_START_CODE_2, Response_Packet.COMMAND_START_CODE_2, "COMMAND_START_CODE_2", UseSerialDebug);
    Response_Packet_CheckParsing(buffer[3], Response_Packet.COMMAND_DEVICE_ID_1, Response_Packet.COMMAND_DEVICE_ID_1, "COMMAND_DEVICE_ID_1", UseSerialDebug);
    Response_Packet_CheckParsing(buffer[4], Response_Packet.COMMAND_DEVICE_ID_2, Response_Packet.COMMAND_DEVICE_ID_2, "COMMAND_DEVICE_ID_2", UseSerialDebug);
    Response_Packet_CheckParsing(buffer[9], 0x30, 0x31, "AckNak_LOW", UseSerialDebug);
    if(buffer[9] == 0x30)Response_Packet.ACK = TRUE; else Response_Packet.ACK = FALSE;
    Response_Packet_CheckParsing(buffer[10], 0x00, 0x00, "AckNak_HIGH", UseSerialDebug);
 
    checksum = Response_Packet_CalculateChecksum(buffer, 10);
    checksum_low = Response_Packet_GetLowByte(checksum);
    checksum_high = Response_Packet_GetHighByte(checksum);
    Response_Packet_CheckParsing(buffer[11], checksum_low, checksum_low, "Checksum_LOW", UseSerialDebug);
    Response_Packet_CheckParsing(buffer[12], checksum_high, checksum_high, "Checksum_HIGH", UseSerialDebug);
 
    Response_Packet.ErrorCodes.Error = Response_Packet_ErrorCodes_ParseFromBytes(buffer[6], buffer[5]);
 
    Response_Packet.ParameterBytes[0] = buffer[5];
    Response_Packet.ParameterBytes[1] = buffer[6];
    Response_Packet.ParameterBytes[2] = buffer[7];
    Response_Packet.ParameterBytes[3] = buffer[8];
    Response_Packet.ResponseBytes[0] = buffer[9];
    Response_Packet.ResponseBytes[1] = buffer[10];
 
    for(i = 1; i < 13; i++) {
        Response_Packet.RawBytes[i-1] = buffer[i];
    }
}



Another changes is to this struct.


Code C - [expand]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
struct Resp_Packet {
    struct ErrCodes {
       enum Errs_Enum {
          NO_ERROR                    = 0x0000,        // Default value. no error
          NACK_TIMEOUT                = 0x1001,        // Obsolete, capture timeout
          NACK_INVALID_BAUDRATE       = 0x1002,        // Obsolete, Invalid serial baud rate
          NACK_INVALID_POS            = 0x1003,        // The specified ID is not between 0~199
          NACK_IS_NOT_USED            = 0x1004,        // The specified ID is not used
          NACK_IS_ALREADY_USED        = 0x1005,        // The specified ID is already used
          NACK_COMM_ERR               = 0x1006,        // Communication Error
          NACK_VERIFY_FAILED          = 0x1007,        // 1:1 Verification Failure
          NACK_IDENTIFY_FAILED        = 0x1008,        // 1:N Identification Failure
          NACK_DB_IS_FULL             = 0x1009,        // The database is full
          NACK_DB_IS_EMPTY            = 0x100A,        // The database is empty
          NACK_TURN_ERR               = 0x100B,        // Obsolete, Invalid order of the enrollment (The order was not as: EnrollStart -> Enroll1 -> Enroll2 -> Enroll3)
          NACK_BAD_FINGER             = 0x100C,        // Too bad fingerprint
          NACK_ENROLL_FAILED          = 0x100D,        // Enrollment Failure
          NACK_IS_NOT_SUPPORTED       = 0x100E,        // The specified command is not supported
          NACK_DEV_ERR                = 0x100F,        // Device Error, especially if Crypto-Chip is trouble
          NACK_CAPTURE_CANCELED       = 0x1010,        // Obsolete, The capturing is canceled
          NACK_INVALID_PARAM          = 0x1011,        // Invalid parameter
          NACK_FINGER_IS_NOT_PRESSED  = 0x1012,        // Finger is not pressed
          INVALID                     = 0XFFFF         // Used when parsing fails
       }Error, e;
 
 
    }ErrorCodes;
    
    //Response_Packet(unsigned char* buffer, bool UseSerialDebug);
    unsigned char RawBytes[12];
    unsigned char ParameterBytes[4];
    unsigned char ResponseBytes[2];
    bool ACK;
    unsigned char COMMAND_START_CODE_1;        // Static byte to mark the beginning of a command packet        -        never changes
    unsigned char COMMAND_START_CODE_2;        // Static byte to mark the beginning of a command packet        -        never changes
    unsigned char COMMAND_DEVICE_ID_1;        // Device ID Byte 1 (lesser byte)                                                        -        theoretically never changes
    unsigned char COMMAND_DEVICE_ID_2;        // Device ID Byte 2 (greater byte)                                                        -        theoretically never changes
 
}Response_Packet;



The changes in the struct is


Code C - [expand]
1
unsigned char RawBytes[13];



Yet another change is


Code C - [expand]
1
2
3
4
5
6
7
8
9
10
11
12
// calculates the checksum from the bytes in the Packet
//unsigned int Response_Packet_CalculateChecksum(unsigned char buffer[], int length) {
unsigned int Response_Packet_CalculateChecksum(unsigned char buffer[], int length) {
    unsigned int checksum = 0;
    unsigned int i = 0;
 
    for(i = 0; i < length; i++) {
        checksum += buffer[i];
    }
 
    return checksum;
}



above function changed to


Code C - [expand]
1
2
3
4
5
6
7
8
9
10
11
12
// calculates the checksum from the bytes in the Packet
//unsigned int Response_Packet_CalculateChecksum(unsigned char buffer[], int length) {
unsigned int Response_Packet_CalculateChecksum(unsigned char buffer[], int length) {
    unsigned int checksum = 0;
    unsigned int i = 0;
 
    for(i = 1; i < length + 1; i++) {
        checksum += buffer[i];
    }
 
    return checksum;
}




Now it is printing IsPressFinger but it is not reading the finger. What is the problem ?

 

Attachments

  • Arduino FPS GT-511C3 1.png
    Arduino FPS GT-511C3 1.png
    174.8 KB · Views: 81
  • Arduino FPS GT-511C3.png
    Arduino FPS GT-511C3.png
    182.5 KB · Views: 79
  • Arduino Response.pdf
    9.3 KB · Views: 43
  • doesn't match.png
    doesn't match.png
    66.6 KB · Views: 79
  • Fingerprint_Scanner-TTL-master.rar
    12.9 KB · Views: 88
  • mikroC PRO PIC32 C Code Response.pdf
    14.6 KB · Views: 96
Last edited:

I fixed the code and now it is working fine. See the attached PDF. It shows the response. I will post the complete C Code soon.
 

Attachments

  • mikroC PRO PIC32 Code Working.pdf
    23.9 KB · Views: 125

Here is the Complete mikroC PRO PIC32 project. See the response PDF posted in post # . Before showing "Enrolling is successful" message it shows "Response_Packet_Parsing _Error" messages. After displaying "Enrolling is Successful" it shows "Check Enrolled" and "EnrollStart" messages and then shows "Press finger to Enroll #1". So, previous ID #0 is enrolled and it has incremented the counter to 1.

So, enrolling was successful but I don't know why the error message even though the sent bytes and response bytes are correct.

Last two bytes of the Sent bytes and Response bytes are the checksum bytes. There are total 12 bytes in each. The sum of first 10 bytes is the checksum.

I have fixed the issue with the UART2 Interrupt code and now the received bytes are not 1 element shifted and so I have reverted the modifies functions to the original functions.

So, there is no modified code. The same code as Arduino Library is used except I am using Hardware Serial ISR to receive the response and Arduino Library uses Software UART for FPS.
 

Attachments

  • GT511C3.rar
    262.2 KB · Views: 50
Last edited:

I have fixed all issues. There were two issues.

1. It was giving "Response_Packet_Parsing_Error.
2. The sensor was not working well with PIC32 compared to the working with Arduino.

I fixed the first issue by using a proper delay of 1200 ms in the
Code:
Respone_Packet_GetRespone()
function.

I fixed the second issue in hardware. In Arduino I was powering the Sensor from 5V and in PIC32 (EasyPIC Fusion v7 development board) I was powering it from 3.3V. The datasheet of the sensor module mentions that it works from 3.3V - 6V. I powered the sensor module from 5V in PIC32 board and it worked fine without problems.

Don't power the sensor module from 3.3V and bang your head. Use 5V to power it and if you are using it with Arduino or 5V MCUs then you have to drop the MCU Tx pin voltage to 3.3V to feed it to Rx of Sensor module.

I am attaching the latest and final project files and the response I got with and without debug as PDF files.

- - - Updated - - -

This is the fingerprint sensor module I have used.

https://www.rhydolabz.com/index.php?main_page=product_info&products_id=1216
 

Attachments

  • GT511C3 With Debug.rar
    35 KB · Views: 43
  • GT511C3 Without Debug.rar
    35.1 KB · Views: 41
  • Response Showing Working of GT511C3 With Debug.pdf
    10.6 KB · Views: 107
  • Response Showing Working of GT511C3 Without Debug.pdf
    3.5 KB · Views: 119
Last edited:
Good that managed it.

I didn't previously notice that this is a PIC32 project. An alternative way to port the Arduino C++ code would be to use Microchip C32 or XC32 which natively supports C++.
 
Yes, I thought about using XC32++ but I need to use TFT+Touchscreen, FAT32 microSD Card, MP3 Player (for voice messages like - "enrolling", "attendance registered", etc...), Buzzer, DS1307 (for date and time of attendance) and mikroE has libraries for all of these and it is easier for me to use use mikroC PRO PIC32 because I have much experience with mikroC PRO PIC. If everything works fine with mikroC PRO PIC32 project then later I will try to implement it in XC32++ code. For that I have to make TFT+Touchscreen Library. In my mikroC PRO PIC32 project I am also providing USB Device function so that the .csv file of attendance on th microSD Card can be opened on PC using USB connectivity. For this mikroE has USB Device Library and I have used it.

Another thing is mikroE has VisualTFT software for creating the GUI for TFT and it generates the required code. So, it is very easier for me to use mikroC PRO PIC32.

But once I make XC32++ TFT, FAT32, Libraries then I will surely implement it in XC32++ code.

I have to complete this project in one month and that is another reason for using mikroC PRO PIC32. I am using the below mentioned libraries with it.

FAT32
USB Device
RTC
TFT_8_Bit

and ofcourse the FPS_GT511C3 C Library.

Another reason for not using XC32++ now is that it is a problem creating the GUI for TFT. I have to make it from scratch or I have to port the VisualTFT generated mikroC PRO PIC32 TFT+Touchscreen Code to XC32++.
 
I do not believe that you have to re-write the functions into C++ as (according to the XC32 User Guide) the compiler handles both C and C++ variants and will link them together. (You can also mix in assembler files to be called by and to call C/C++ functions.)
There may well be other porting issues, but I don't think C vs C++ is one of them.
Susan
 

Made a small change

In the
Code:
FPS_GT511C3_GetResponse()

there was a nasty
Code:
Delay_ms(1200)

I replaced it with below code.


Code C - [expand]
1
while(gIndex != 12);



so that unless 12 response bytes aren't received it sits there in the loop.

Also I removed

Code:
ResetVars();

function call from all FPS_GT511C3_xxx() functions and put it inside

Code:
FPS_GT511C3_GetResponse()

function.

Now the enrolling is smooth.
 

Attachments

  • GT511C3.rar
    34.6 KB · Views: 47

Status
Not open for further replies.

Similar threads

Part and Inventory Search

Welcome to EDABoard.com

Sponsor

Back
Top