RFID RC522 Reading card wiringPi

1.7k views Asked by At

i am using raspberyy pi 3 , RFID RC522. I want to read a card using wiringPi. I am trying this codes;

#include<stdio.h>
#include<conio.h>
#include<wiringPi.h>
#include<wiringPiSPI.h>

int main()
{
    int chan = 1;
    int speed = 1000000;

    if (wiringPiSPISetup(chan, speed) == -1)
    {
        printf("Could not initialise SPI\n");
        return;
    }
    printf("When ready hit enter.\n");
    (void) getchar(); // remove the CR
    unsigned char buff[100];

    while (1)
    {
        int ret = wiringPiSPIDataRW(chan, buff, 4);
        printf("%d %s \n", ret, buff);

    }
}

when I try this, it turns always '4'. How can read I don't understand.

1

There are 1 answers

0
LPs On

You are sending uninitialized data to your slave SPI device.

unsigned char buff[100];

while (1)
{
    int ret = wiringPiSPIDataRW(chan, buff, 4);
    printf("%d %s \n", ret, buff);

}

buffer content is indeterminate.

Looking at the library doc

int wiringPiSPIDataRW (int channel, unsigned char *data, int len);

This performs a simultaneous write/read transaction over the selected SPI bus. Data that was in your buffer is overwritten by data returned from the SPI bus.

It means you should init your buffer with message to send. This data will be lost because of slave reply will be returned into the same buffer.

Looking at this example you should do sometning like:

 unsigned char buff[100] = {0};

 // Following bytes must be set according to your slave SPI device docs.
 buffer[0] = ??; 
 buffer[1] = ??;
 buffer[2] = ??;
 buffer[3] = ??;
 wiringPiSPIDataRW(chan, buffer, 4);