IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

C Discussion :

Programmation lecteur RC522


Sujet :

C

  1. #1
    Candidat au Club
    Homme Profil pro
    Étudiant
    Inscrit en
    Mai 2012
    Messages
    5
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Mai 2012
    Messages : 5
    Points : 4
    Points
    4
    Par défaut Programmation lecteur RC522
    Bonjour,

    je suis étudiant ingénieur en systèmes embarqués et mon projet consiste en la réalisation d'un lecteur de badge RFID. J'ai acheté un lecteur RC522 que j'ai connecté à mon arduino ( en attendant de recevoir la véritable carte de projet MBED) via le port SPI. J'ai trouvé le code sur internet que j'ai modifié un peu par moi même et tout fonctionne parfaitement ! Le lecteur reconnait le badge et la carte Mifare et emet un bip de reconnaissance grâce à un buzzer.
    Voila la datasheet du RC522: http://www.nxp.com/documents/data_sheet/MFRC522.pdf

    Ainsi que le code:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    /*
     * File Name : RFID.pde
     * Creator : Dr.Leong (WWW.B2CQSHOP.COM)
     * Create Date: 2011.09.19
     * Modified by :
     * Modify Date:
     * Chinese comments translated using Google Translate by
     * Description : Mifare1 -> find cards - > Anti-collision - > Select Card - > reader interface
     */
    // the sensor communicates using SPI, so include the library:
    #include <SPI.h>
    #include<Servo.h>
     
    #define	uchar	unsigned char
    #define	uint	unsigned int
     
    // Maximum length of the array
    #define MAX_LEN 16
     
    /////////////////////////////////////////////////////////////////////
    //set the pin
    /////////////////////////////////////////////////////////////////////
    const int chipSelectPin = 10;
    const int NRSTPD = 5;
     
    //MF522 command word
    #define PCD_IDLE              0x00               //NO action; cancel the current command
    #define PCD_AUTHENT           0x0E               // authentication key
    #define PCD_RECEIVE           0x08               // receive data
    #define PCD_TRANSMIT          0x04               // Transmit Data
    #define PCD_TRANSCEIVE        0x0C               // Send and receive data
    #define PCD_RESETPHASE        0x0F               // Reset
    #define PCD_CALCCRC           0x03               // CRC calculation
     
    //Mifare_One card command word
    #define PICC_REQIDL           0x26               // find the antenna area does not enter hibernation
    #define PICC_REQALL           0x52               // find all the cards antenna area
    #define PICC_ANTICOLL         0x93               // anti-collision
    #define PICC_SElECTTAG        0x93               // election card
    #define PICC_AUTHENT1A        0x60               // authentication key A
    #define PICC_AUTHENT1B        0x61               // authentication key B
    #define PICC_READ             0x30               // Read Block
    #define PICC_WRITE            0xA0               // write block
    #define PICC_DECREMENT        0xC0               // debit?
    #define PICC_INCREMENT        0xC1               // recharge?
    #define PICC_RESTORE          0xC2               // transfer block data to the buffer
    #define PICC_TRANSFER         0xB0               // save the data in the buffer
    #define PICC_HALT             0x50               // Sleep
     
     
    //和MF522 communication error code is returned when
    #define MI_OK                 0
    #define MI_NOTAGERR           1
    #define MI_ERR                2
     
     
    //------------------MFRC522 register---------------
    //Page 0:Command and Status
    #define     Reserved00            0x00
    #define     CommandReg            0x01
    #define     CommIEnReg            0x02
    #define     DivlEnReg             0x03
    #define     CommIrqReg            0x04
    #define     DivIrqReg             0x05
    #define     ErrorReg              0x06
    #define     Status1Reg            0x07
    #define     Status2Reg            0x08
    #define     FIFODataReg           0x09
    #define     FIFOLevelReg          0x0A
    #define     WaterLevelReg         0x0B
    #define     ControlReg            0x0C
    #define     BitFramingReg         0x0D
    #define     CollReg               0x0E
    #define     Reserved01            0x0F
    //Page 1:Command
    #define     Reserved10            0x10
    #define     ModeReg               0x11
    #define     TxModeReg             0x12
    #define     RxModeReg             0x13
    #define     TxControlReg          0x14
    #define     TxAutoReg             0x15
    #define     TxSelReg              0x16
    #define     RxSelReg              0x17
    #define     RxThresholdReg        0x18
    #define     DemodReg              0x19
    #define     Reserved11            0x1A
    #define     Reserved12            0x1B
    #define     MifareReg             0x1C
    #define     Reserved13            0x1D
    #define     Reserved14            0x1E
    #define     SerialSpeedReg        0x1F
    //Page 2:CFG
    #define     Reserved20            0x20
    #define     CRCResultRegM         0x21
    #define     CRCResultRegL         0x22
    #define     Reserved21            0x23
    #define     ModWidthReg           0x24
    #define     Reserved22            0x25
    #define     RFCfgReg              0x26
    #define     GsNReg                0x27
    #define     CWGsPReg	          0x28
    #define     ModGsPReg             0x29
    #define     TModeReg              0x2A
    #define     TPrescalerReg         0x2B
    #define     TReloadRegH           0x2C
    #define     TReloadRegL           0x2D
    #define     TCounterValueRegH     0x2E
    #define     TCounterValueRegL     0x2F
    //Page 3:TestRegister
    #define     Reserved30            0x30
    #define     TestSel1Reg           0x31
    #define     TestSel2Reg           0x32
    #define     TestPinEnReg          0x33
    #define     TestPinValueReg       0x34
    #define     TestBusReg            0x35
    #define     AutoTestReg           0x36
    #define     VersionReg            0x37
    #define     AnalogTestReg         0x38
    #define     TestDAC1Reg           0x39
    #define     TestDAC2Reg           0x3A
    #define     TestADCReg            0x3B
    #define     Reserved31            0x3C
    #define     Reserved32            0x3D
    #define     Reserved33            0x3E
    #define     Reserved34			  0x3F
    //-----------------------------------------------
    Servo myServo;
    //4 bytes card serial number , the first 5 bytes for the checksum byte
    uchar serNum[5];
     
    uchar  writeData[16]={0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 100};  // Initialize 100 dollars
    uchar  moneyConsume = 18 ;  // spending 18 yuan
    uchar  moneyAdd = 10 ;  // recharge 10 yuan
    // Sector A password , 16 sectors , each sector password 6Byte
    uchar sectorKeyA[16][16] = {{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
    {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
    //{0x19, 0x84, 0x07, 0x15, 0x76, 0x14},
    {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
    };
    uchar sectorNewKeyA[16][16] = {{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF},
    {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xff,0x07,0x80,0x69, 0x19,0x84,0x07,0x15,0x76,0x14},
    //you can set another ket , such as  " 0x19, 0x84, 0x07, 0x15, 0x76, 0x14 "
    //{0x19, 0x84, 0x07, 0x15, 0x76, 0x14, 0xff,0x07,0x80,0x69, 0x19,0x84,0x07,0x15,0x76,0x14},
    // but when loop, please set the  sectorKeyA, the same key, so that RFID module can read the card
    {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xff,0x07,0x80,0x69, 0x19,0x33,0x07,0x15,0x34,0x14},
    };
     
    void setup() {
        myServo.attach(9);
        Serial.begin(9600);                       // RFID reader SOUT pin connected to Serial RX pin at 2400bps
        Serial.println("Ready");
     
        // start the SPI library:
        SPI.begin();
     
        pinMode(chipSelectPin,OUTPUT);             // Set digital pin 10 as OUTPUT to connect it to the RFID /ENABLE pin
        digitalWrite(chipSelectPin, LOW);          // Activate the RFID reader
        pinMode(NRSTPD,OUTPUT);               // Set digital pin 10 , Not Reset and Power-down
        digitalWrite(NRSTPD, HIGH);
     
        MFRC522_Init();
    }
     
    void loop()
    {
        uchar i,tmp;
        uchar status;
        uchar str[MAX_LEN];
        uchar RC_size;
        uchar blockAddr;	// select the operating block addresses 0 to 63
     
     
        // Find the card , back card type
        status = MFRC522_Request(PICC_REQIDL, str);	// trouve la carte
        /*if (status == MI_OK)
         * {
         * Serial.println("Find out a card ");
         * Serial.print(str[0],BIN);
         * Serial.print(" , ");
         * Serial.print(str[1],BIN);
         * Serial.println(" ");
         * }*/
        status = MFRC522_Anticoll(str);   // lit le numéro de série de la carte // Anti-collision, return card serial number 4 bytes
        memcpy(serNum, str, 5);   // copie des 5 octets de str vers serNum
        if (status == MI_OK)
        {
     
            /*Serial.println("The card's number is  : ");
             * Serial.print(serNum[0]);     // ajouter, BIN pour avoir en binaire
             * Serial.print(" , ");
             * Serial.print(serNum[1]);
             * Serial.print(" , ");
             * Serial.print(serNum[2]);
             * Serial.print(" , ");
             * Serial.print(serNum[3]);
             * Serial.print(" , ");
             * Serial.print(serNum[4]);
             * Serial.println(" ");*/
        }
        if (serNum[0]==111 && serNum[1]==173 && serNum[2]==35 && serNum[3]==29 && serNum[4]==252 )
        {
            Serial.println(" Bonjour Sebastien ");
            Serial.println(" Vous pouvez entrer ");
            tone (8, 400, 400);
            delay (500);
            myServo.write(180);
            delay (4000);
            myServo.write(0);
        }
        if (serNum[0]==132 && serNum[1]==210 && serNum[2]==114 && serNum[3]==26 && serNum[4]==62 )
        {
            Serial.println(" Bonjour Monsieur !");
            Serial.println(" Tu peux aussi entrer ");
            tone (8, 400, 400);
            delay (500);
            myServo.write(180);
            delay (4000);
            myServo.write(0);
     
        }
    }
     
     
     
     
     
    /*
     * Function Name : Write_MFRC5200
     * Description: MFRC522 of a register to write a byte of data
     * Input Parameters : addr - register address ; val - the value to be written
     * Return value: None
     */
     
    // page 11 -> MSB=BLPS
    // 1=read ; 0=write
    // LSB=0
    void Write_MFRC522(uchar addr, uchar val)
    {
        digitalWrite(chipSelectPin, LOW); //actif
     
        // Addresse au Format :0XXXXXX0
        addr=addr<<1;  // on souhaite un 0 en BLMS, on décale donc addr de 1 bit vers la gauche pour ne perdre aucune informations (p11)
        addr=addr&0x7E;  //afin d'avoir BLPS=0 pour écrire
        SPI.transfer(addr);  // ou sinon addr=(addr<<1)&0x7E
        SPI.transfer(val);  // ecriture de la valeur
        digitalWrite(chipSelectPin, HIGH); //inactif
    }
     
     
    /*
     * Function Name : Read_MFRC522
     * Description : From a certain MFRC522 read a byte of data register
     * Input Parameters : addr - register address
     * Return value : Returns a byte of data read from the
     */
    uchar Read_MFRC522(uchar addr)
    {
        uchar val;
     
        digitalWrite(chipSelectPin, LOW);  // actif
     
        // Addresse au Format : 1XXXXXX0 afin de pouvoir lire
        addr=addr<<1;  // on souhaite un 0 en BLMS, on décale donc addr de 1 bit vers la gauche pour ne perdre aucune informations (p11)
        addr=addr|0x80;  //afin d'avoir BLPS=1 pour lire
        SPI.transfer(addr); // ou sinon SPI.transfer(((addr<<1)&0x7E) | 0x80);
        val =SPI.transfer(0x00);  // envoit du BLPS p10
     
        digitalWrite(chipSelectPin, HIGH);   //inactif
     
        return val;
    }
     
    /*
     * Function Name : SetBitMask
     * Description: Set RC522 register bit
     * Input parameters : reg - register address ; mask - set value
     * Return value: None
     */
    void SetBitMask(uchar reg, uchar mask)    // a voir
    {
        uchar tmp;
        tmp = Read_MFRC522(reg);
        Write_MFRC522(reg, tmp | mask);  // set bit mask
    }
     
     
    /*
     * Function Name : ClearBitMask
     * Description : clear RC522 register bit
     * Input parameters : reg - register address ; mask - clear bit value
     * Return value: None
     */
    void ClearBitMask(uchar reg, uchar mask)  // a voir
    {
        uchar tmp;
        tmp = Read_MFRC522(reg);
        Write_MFRC522(reg, tmp & (~mask));  // clear bit mask
    }
     
     
    /*
     * Function Name : AntennaOn
     * Description : Open antennas, each time you start or shut down the natural barrier between the transmitter should be at least 1ms interval
     * Input: None
     * Return value: None
     */
    void AntennaOn(void)
    {
        uchar temp;
     
        temp = Read_MFRC522(TxControlReg);
        if (!(temp & 0x03))
        {
            SetBitMask(TxControlReg, 0x03);
        }
    }
     
     
    /*
     * Function Name : AntennaOff
     * Description : Close antennas, each time you start or shut down the natural barrier between the transmitter should be at least 1ms interval
     * Input: None
     * Return value: None
     * /
     */
    void AntennaOff(void)
    {
        ClearBitMask(TxControlReg, 0x03);
    }
     
     
    /*
     * Function Name : ResetMFRC522
     * Description : Reset RC522
     * Input: None
     * Return value: None
     */
    void MFRC522_Reset(void)
    {
        Write_MFRC522(CommandReg, PCD_RESETPHASE);
        //CommandReg 0x01   starts and stops command execution
    }
     
     
    /*
     * Function Name : InitMFRC522
     * Description : Initialize RC522
     * Input: None
     * Return value: None
     */
    void MFRC522_Init(void)
    {
        digitalWrite(NRSTPD,HIGH);
     
        MFRC522_Reset();
     
        //Timer: TPrescaler*TreloadVal/6.78MHz = 24ms
        Write_MFRC522(TModeReg, 0x8D);		//Tauto=1; f(Timer) = 6.78MHz/TPreScaler   p53
        Write_MFRC522(TPrescalerReg, 0x3E);	//TModeReg[3..0] + TPrescalerReg
        Write_MFRC522(TReloadRegL, 30);
        Write_MFRC522(TReloadRegH, 0);
     
        Write_MFRC522(TxAutoReg, 0x40);		//100%ASK
        Write_MFRC522(ModeReg, 0x3D);		//CRC初始值0x6363	???
     
        //ClearBitMask(Status2Reg, 0x08);		//MFCrypto1On=0
        //Write_MFRC522(RxSelReg, 0x86);		//RxWait = RxSelReg[5..0]
        //Write_MFRC522(RFCfgReg, 0x7F);   		//RxGain = 48dB
     
        AntennaOn();		//打开天线
    }
     
     
    /*
     * Function Name : MFRC522_Request
     * Description : Find cards , read the card type number
     * Input parameters : reqMode - find cards way
     * TagType - Return Card Type
     * 0x4400 = Mifare_UltraLight
     * 0x0400 = Mifare_One (S50)
     * 0x0200 = Mifare_One (S70)
     * 0x0800 = Mifare_Pro (X)
     * 0x4403 = Mifare_DESFire
     * Return value: the successful return MI_OK
     */
    uchar MFRC522_Request(uchar reqMode, uchar *TagType)   // trouve la carte et identifie le numéro du type de carte
    {
        uchar status;
        uint backBits;			// received data bits
     
        Write_MFRC522(BitFramingReg, 0x07);		//TxLastBists = BitFramingReg[2..0]	???
     
        TagType[0] = reqMode;
        status = MFRC522_ToCard(PCD_TRANSCEIVE, TagType, 1, TagType, &backBits);
     
        if ((status != MI_OK) || (backBits != 0x10))
        {
            status = MI_ERR;
        }
     
        return status;
    }
     
     
    /*
     * Function Name : MFRC522_ToCard
     * Description : RC522 and ISO14443 card communication
     * Input Parameters : command - MF522 command word,
     * SendData - RC522 sent to the card via the data
     * SendLen - length of data sent
     * BackData - received the card returns data,
     * BackLen - return data bit length
     * Return value: the successful return MI_OK
     */
    uchar MFRC522_ToCard(uchar command, uchar *sendData, uchar sendLen, uchar *backData, uint *backLen)
    {
        uchar status = MI_ERR;
        uchar irqEn = 0x00;
        uchar waitIRq = 0x00;
        uchar lastBits;
        uchar n;
        uint i;
     
        switch (command)
        {
            case PCD_AUTHENT:		// certification cards close   if command=PCD_AUTHENT   0x0E               // authentication key
            {
                irqEn = 0x12;
                waitIRq = 0x10;
                break;
            }
            case PCD_TRANSCEIVE:	 // transmit FIFO data    if command=PCD_TRANSCEIVE   0x0C               // Send and receive data
            {
                irqEn = 0x77;
                waitIRq = 0x30;
                break;
            }
            default:
                break;
        }
     
        Write_MFRC522(CommIEnReg, irqEn|0x80);	// enable interrupt request
        ClearBitMask(CommIrqReg, 0x80);			// clear all interrupt request bit
        SetBitMask(FIFOLevelReg, 0x80);			// FlushBuffer = 1, FIFO initialization
     
        Write_MFRC522(CommandReg, PCD_IDLE);	// NO action; cancel the current command ? ? ?
     
        // Write data to the FIFO
        for (i=0; i<sendLen; i++)
        {
            Write_MFRC522(FIFODataReg, sendData[i]);
        }
     
        // Execute the command
        Write_MFRC522(CommandReg, command);
        if (command == PCD_TRANSCEIVE)
        {
            SetBitMask(BitFramingReg, 0x80);		//StartSend=1,transmission of data starts
        }
     
        // Wait for completion of receiving data
        i = 2000; // i according to the clock frequency adjustment , the operator M1 card maximum waiting time 25ms???
        do
        {
            //CommIrqReg[7..0]
            //Set1 TxIRq RxIRq IdleIRq HiAlerIRq LoAlertIRq ErrIRq TimerIRq
            n = Read_MFRC522(CommIrqReg);
            i--;
        }
        while ((i!=0) && !(n&0x01) && !(n&waitIRq));
     
        ClearBitMask(BitFramingReg, 0x80);			//StartSend=0
     
        if (i != 0)
        {
            if(!(Read_MFRC522(ErrorReg) & 0x1B))	//BufferOvfl Collerr CRCErr ProtecolErr
            {
                status = MI_OK;
                if (n & irqEn & 0x01)
                {
                    status = MI_NOTAGERR;			//??
                }
     
                if (command == PCD_TRANSCEIVE)
                {
                    n = Read_MFRC522(FIFOLevelReg);
                    lastBits = Read_MFRC522(ControlReg) & 0x07;
                    if (lastBits)
                    {
                        *backLen = (n-1)*8 + lastBits;
                    }
                    else
                    {
                        *backLen = n*8;
                    }
     
                    if (n == 0)
                    {
                        n = 1;
                    }
                    if (n > MAX_LEN)
                    {
                        n = MAX_LEN;
                    }
     
                    // Read the received data in FIFO
                    for (i=0; i<n; i++)
                    {
                        backData[i] = Read_MFRC522(FIFODataReg);
                    }
                }
            }
            else
            {
                status = MI_ERR;
            }
     
        }
     
        //SetBitMask(ControlReg,0x80);           //timer stops
        //Write_MFRC522(CommandReg, PCD_IDLE);
     
        return status;
    }
     
     
    /*
     * Function Name : MFRC522_Anticoll
     * Description : Anti- collision detection , reading selected card serial number card
     * Input parameters : serNum - returns 4 bytes card serial number , the first 5 bytes for the checksum byte
     * Return value: the successful return MI_OK
     */
    uchar MFRC522_Anticoll(uchar *serNum)
    {
        uchar status;
        uchar i;
        uchar serNumCheck=0;
        uint unLen;
     
     
        //ClearBitMask(Status2Reg, 0x08);		//TempSensclear
        //ClearBitMask(CollReg,0x80);			//ValuesAfterColl
        Write_MFRC522(BitFramingReg, 0x00);		//TxLastBists = BitFramingReg[2..0]
     
        serNum[0] = PICC_ANTICOLL;
        serNum[1] = 0x20;
        status = MFRC522_ToCard(PCD_TRANSCEIVE, serNum, 2, serNum, &unLen);
     
        if (status == MI_OK)
        {
            // Check Card Serial Number
            for (i=0; i<4; i++)
            {
                serNumCheck ^= serNum[i];
            }
            if (serNumCheck != serNum[i])
            {
                status = MI_ERR;
            }
        }
     
        //SetBitMask(CollReg, 0x80);		//ValuesAfterColl=1
     
        return status;
    }
     
     
    /*
     * Function Name : CalulateCRC
     * Description: CRC calculation with MF522
     * Input parameters : pIndata - To read the CRC data , len - the data length , pOutData - CRC calculation results
     * Return value: None
     */
    void CalulateCRC(uchar *pIndata, uchar len, uchar *pOutData)
    {
        uchar i, n;
     
        ClearBitMask(DivIrqReg, 0x04);			//CRCIrq = 0
        SetBitMask(FIFOLevelReg, 0x80);			//清FIFO指针
        //Write_MFRC522(CommandReg, PCD_IDLE);
     
        // Write data to the FIFO
        for (i=0; i<len; i++)
        {
            Write_MFRC522(FIFODataReg, *(pIndata+i));
        }
        Write_MFRC522(CommandReg, PCD_CALCCRC);
     
        // Read the CRC calculation result
        i = 0xFF;
        do
        {
            n = Read_MFRC522(DivIrqReg);
            i--;
        }
        while ((i!=0) && !(n&0x04));			//CRCIrq = 1
     
        // Read the CRC calculation result
        pOutData[0] = Read_MFRC522(CRCResultRegL);
        pOutData[1] = Read_MFRC522(CRCResultRegM);
    }
     
     
    /*
     * Function Name : MFRC522_SelectTag
     * Description: election card , read the card memory capacity
     * Input parameters : serNum - Incoming card serial number
     * Return value: the successful return of card capacity
     */
    uchar MFRC522_SelectTag(uchar *serNum)
    {
        uchar i;
        uchar status;
        uchar size;
        uint recvBits;
        uchar buffer[9];
     
        //ClearBitMask(Status2Reg, 0x08);			//MFCrypto1On=0
     
        buffer[0] = PICC_SElECTTAG;
        buffer[1] = 0x70;
        for (i=0; i<5; i++)
        {
            buffer[i+2] = *(serNum+i);
        }
        CalulateCRC(buffer, 7, &buffer[7]);		//??
        status = MFRC522_ToCard(PCD_TRANSCEIVE, buffer, 9, buffer, &recvBits);
     
        if ((status == MI_OK) && (recvBits == 0x18))
        {
            size = buffer[0];
        }
        else
        {
            size = 0;
        }
     
        return size;
    }
     
     
    /*
     * Function Name : MFRC522_Auth
     * Description : Verify card password
     * Input parameters : authMode - Password Authentication Mode
     * 0x60 = A key authentication
     * 0x61 = B key authentication
     * BlockAddr - block address
     * Sectorkey - Sector password
     * serNum - card serial number, 4-byte
     * Return value: the successful return MI_OK
     */
    uchar MFRC522_Auth(uchar authMode, uchar BlockAddr, uchar *Sectorkey, uchar *serNum)
    {
        uchar status;
        uint recvBits;
        uchar i;
        uchar buff[12];
     
        // Validate instruction block address + sector + password + card serial number
        buff[0] = authMode;
        buff[1] = BlockAddr;
        for (i=0; i<6; i++)
        {
            buff[i+2] = *(Sectorkey+i);
        }
        for (i=0; i<4; i++)
        {
            buff[i+8] = *(serNum+i);
        }
        status = MFRC522_ToCard(PCD_AUTHENT, buff, 12, buff, &recvBits);
     
        if ((status != MI_OK) || (!(Read_MFRC522(Status2Reg) & 0x08)))
        {
            status = MI_ERR;
        }
     
        return status;
    }
     
     
    /*
     * Function Name : MFRC522_Read
     * Description : Read block data
     * Input parameters : blockAddr - block address ; recvData - read block data
     * Return value: the successful return MI_OK
     */
    uchar MFRC522_Read(uchar blockAddr, uchar *recvData)
    {
        uchar status;
        uint unLen;
     
        recvData[0] = PICC_READ;
        recvData[1] = blockAddr;
        CalulateCRC(recvData,2, &recvData[2]);
        status = MFRC522_ToCard(PCD_TRANSCEIVE, recvData, 4, recvData, &unLen);
     
        if ((status != MI_OK) || (unLen != 0x90))
        {
            status = MI_ERR;
        }
     
        return status;
    }
     
     
    /*
     * Function Name : MFRC522_Write
     * Description : Write block data
     * Input parameters : blockAddr - block address ; writeData - to 16-byte data block write
     * Return value: the successful return MI_OK
     */
    uchar MFRC522_Write(uchar blockAddr, uchar *writeData)
    {
        uchar status;
        uint recvBits;
        uchar i;
        uchar buff[18];
     
        buff[0] = PICC_WRITE;
        buff[1] = blockAddr;
        CalulateCRC(buff, 2, &buff[2]);
        status = MFRC522_ToCard(PCD_TRANSCEIVE, buff, 4, buff, &recvBits);
     
        if ((status != MI_OK) || (recvBits != 4) || ((buff[0] & 0x0F) != 0x0A))
        {
            status = MI_ERR;
        }
     
        if (status == MI_OK)
        {
            for (i=0; i<16; i++)		//向FIFO写16Byte数据
            {
                buff[i] = *(writeData+i);
            }
            CalulateCRC(buff, 16, &buff[16]);
            status = MFRC522_ToCard(PCD_TRANSCEIVE, buff, 18, buff, &recvBits);
     
            if ((status != MI_OK) || (recvBits != 4) || ((buff[0] & 0x0F) != 0x0A))
            {
                status = MI_ERR;
            }
        }
     
        return status;
    }
     
     
    /*
     * Function Name : MFRC522_Halt
     * Description : Command card into hibernation
     * Input: None
     * Return value: None
     */
    void MFRC522_Halt(void)
    {
        uchar status;
        uint unLen;
        uchar buff[4];
     
        buff[0] = PICC_HALT;
        buff[1] = 0;
        CalulateCRC(buff, 2, &buff[2]);
     
        status = MFRC522_ToCard(PCD_TRANSCEIVE, buff, 4, buff,&unLen);
    }
    Cependant le code utilisé me parait relativement compliqué et j'ai beaucoup de mal à le comprendre d'ou l'objet de mon post. Après quelques bonnes heures passés dessus, j'ai compris l'intégralité de quelques fonctions notamment
    " Write_MFRC522" et "Read_MFRC522" ainsi que certains bouts de code par ci par la.
    J'ai pas mal étudié la datasheet du lecteur RC522 et par exemple, je ne comprend pas la fonction

    "MFRC522_ToCard", je sais qu'elle identifie la norme ISO14443 et qu'elle l'applique sur le badge, enfin c'est ce que j'ai compris... Mais concrètement dans cette fonction qu'est ce qu'il se passe ?

    En espérant avoir quelques réponses ou des éléments de réponses qui pourront me faire avancer, je vous remercie d'avance

  2. #2
    Modérateur

    Avatar de Bktero
    Homme Profil pro
    Développeur en systèmes embarqués
    Inscrit en
    Juin 2009
    Messages
    4 481
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 36
    Localisation : France, Loire Atlantique (Pays de la Loire)

    Informations professionnelles :
    Activité : Développeur en systèmes embarqués

    Informations forums :
    Inscription : Juin 2009
    Messages : 4 481
    Points : 13 679
    Points
    13 679
    Billets dans le blog
    1
    Par défaut
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    /*
     * Function Name : MFRC522_ToCard
     * Description : RC522 and ISO14443 card communication
     * Input Parameters : command - MF522 command word,
     * SendData - RC522 sent to the card via the data
     * SendLen - length of data sent
     * BackData - received the card returns data,
     * BackLen - return data bit length
     * Return value: the successful return MI_OK
     */
    uchar MFRC522_ToCard(uchar command, uchar *sendData, uchar sendLen, uchar *backData, uint *backLen)
    {
        uchar status = MI_ERR;
        uchar irqEn = 0x00;
        uchar waitIRq = 0x00;
        uchar lastBits;
        uchar n;
        uint i;
     
        switch (command)
        {
            case PCD_AUTHENT:		// certification cards close   if command=PCD_AUTHENT   0x0E               // authentication key
            {
                irqEn = 0x12;
                waitIRq = 0x10;
                break;
            }
            case PCD_TRANSCEIVE:	 // transmit FIFO data    if command=PCD_TRANSCEIVE   0x0C               // Send and receive data
            {
                irqEn = 0x77;
                waitIRq = 0x30;
                break;
            }
            default:
                break;
        }
     
        Write_MFRC522(CommIEnReg, irqEn|0x80);	// enable interrupt request
        ClearBitMask(CommIrqReg, 0x80);			// clear all interrupt request bit
        SetBitMask(FIFOLevelReg, 0x80);			// FlushBuffer = 1, FIFO initialization
     
        Write_MFRC522(CommandReg, PCD_IDLE);	// NO action; cancel the current command ? ? ?
     
        // Write data to the FIFO
        for (i=0; i<sendLen; i++)
        {
            Write_MFRC522(FIFODataReg, sendData[i]);
        }
     
        // Execute the command
        Write_MFRC522(CommandReg, command);
        if (command == PCD_TRANSCEIVE)
        {
            SetBitMask(BitFramingReg, 0x80);		//StartSend=1,transmission of data starts
        }
     
        // Wait for completion of receiving data
        i = 2000; // i according to the clock frequency adjustment , the operator M1 card maximum waiting time 25ms???
        do
        {
            //CommIrqReg[7..0]
            //Set1 TxIRq RxIRq IdleIRq HiAlerIRq LoAlertIRq ErrIRq TimerIRq
            n = Read_MFRC522(CommIrqReg);
            i--;
        }
        while ((i!=0) && !(n&0x01) && !(n&waitIRq));
     
        ClearBitMask(BitFramingReg, 0x80);			//StartSend=0
     
        if (i != 0)
        {
            if(!(Read_MFRC522(ErrorReg) & 0x1B))	//BufferOvfl Collerr CRCErr ProtecolErr
            {
                status = MI_OK;
                if (n & irqEn & 0x01)
                {
                    status = MI_NOTAGERR;			//??
                }
     
                if (command == PCD_TRANSCEIVE)
                {
                    n = Read_MFRC522(FIFOLevelReg);
                    lastBits = Read_MFRC522(ControlReg) & 0x07;
                    if (lastBits)
                    {
                        *backLen = (n-1)*8 + lastBits;
                    }
                    else
                    {
                        *backLen = n*8;
                    }
     
                    if (n == 0)
                    {
                        n = 1;
                    }
                    if (n > MAX_LEN)
                    {
                        n = MAX_LEN;
                    }
     
                    // Read the received data in FIFO
                    for (i=0; i<n; i++)
                    {
                        backData[i] = Read_MFRC522(FIFODataReg);
                    }
                }
            }
            else
            {
                status = MI_ERR;
            }
     
        }
     
        //SetBitMask(ControlReg,0x80);           //timer stops
        //Write_MFRC522(CommandReg, PCD_IDLE);
     
        return status;
    }
    Cette fonction ne me parait pas bien sorcière. Elle est très procédurière, comme souvent quand on utilise des modules physiques externes, mais il n'y a rien qui soit bien compliqué d'un point de vue code pur. Grosso modo :
    • Tu as une commande, d'où le switch au début pour savoir quoi faire.
    • Tu as des données à envoyer d'où une boucle (for) pour envoyer chacun des bytes.
    • Tu as des données qui sont reçues en retour d'où une boucle (do / while) de lecture.
    • La dernière partie est un peu plus compliqué à comprendre quand on ne connait pas le protocole utilisé. Il y a un test pour savoir s'il a eu une erreur ou pas. Il y a une nouvelle boucle pour le cas de TRANSCEIVE.

    Pour comprendre les détails, il te faut lire la datasheet et comprendre la datasheet. C'est le fonctionnement de ton module qui est traduit ici.

  3. #3
    Candidat au Club
    Homme Profil pro
    Étudiant
    Inscrit en
    Mai 2012
    Messages
    5
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Mai 2012
    Messages : 5
    Points : 4
    Points
    4
    Par défaut
    merci Bktero ! C'est vrai que cette fonction est au final plus simple qu'elle en avait l'air...
    Je ne m'étais pas assez attardé sur la datasheet :p
    Merci

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Programmation lecteur RC522
    Par sebastien536 dans le forum Embarqué
    Réponses: 1
    Dernier message: 07/03/2014, 17h46
  2. programmation Lecteur mp3
    Par dr971 dans le forum C
    Réponses: 3
    Dernier message: 11/05/2007, 10h31
  3. Programmer un lecteur mp3
    Par OjBarbare dans le forum MFC
    Réponses: 3
    Dernier message: 17/02/2003, 19h45

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo