目录
一、问题汇总:
1.无法寻卡
2.寻卡不稳定
二、修改设备树
三、驱动程序
四、测试程序
1.rc522_ap.c
2.rc522_app.h
3.rc522_test.c
4.Makefile
前言:
CSDN上大部分对于RC522的文章都是正点的,虽然文章写的挺详细,两块板子也挺相近的,但是对于我们使用100ask_imx6ull pro的用户来说还是有很多地方不适配的,小问题特别多。
翻烂了整个CSDN和百问网的论坛,终于成功使用100ask_imx6ull pro开发板成功使用RC522模块读取到了卡号。这是参考的文章(有代码):imx6ull_pro和rc522使用spi通讯一直找不到卡,发送MI_ERR消息 - 嵌入式Linux开发 - 嵌入式开发问答社区
一、问题汇总:
1.无法寻卡
由于spi-controller会自动对ecspi1下的cs_gpio拉高或者拉低,可能在spi_sync的数据发送过程中有bug, 所以不能使用spi_controller提供的片选引脚,不然的话,spi_sync会操控这个引脚但是用户却不知道是拉高还是拉低。
所以应该找一个可以使用的gpio当作片选引脚,然后再在读写函数中控制它,需要将片选引脚改为了普通gpio让用户控制cs_gpio,在spi_sync前拉低电平,之后拉高电平。
2.寻卡不稳定
SPI时钟频率过快,会导致寻卡很不稳定,大部分时间寻不到卡,偶尔才能寻到卡。
解决办法就是降低SPI的时钟频率,这样就不会寻不到卡了。
二、修改设备树
修改设备树,主要针对上面两个问题:
1.使用别的gpio当作片选引脚
2.修改SPI的时钟频率
三、驱动程序
/** Simple synchronous userspace interface to SPI devices** Copyright (C) 2006 SWAPP* Andrea Paterniani <a.paterniani@swapp-eng.it>* Copyright (C) 2007 David Brownell (simplification, cleanup)** This program is free software; you can redistribute it and/or modify* it under the terms of the GNU General Public License as published by* the Free Software Foundation; either version 2 of the License, or* (at your option) any later version.** This program is distributed in the hope that it will be useful,* but WITHOUT ANY WARRANTY; without even the implied warranty of* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the* GNU General Public License for more details.*/#include <linux/init.h>
#include <linux/module.h>
#include <linux/ioctl.h>
#include <linux/fs.h>
#include <linux/device.h>
#include <linux/err.h>
#include <linux/list.h>
#include <linux/errno.h>
#include <linux/mutex.h>
#include <linux/slab.h>
#include <linux/compat.h>
#include <linux/of.h>
#include <linux/of_device.h>
#include <linux/acpi.h>#include <linux/spi/spi.h>
#include <linux/spi/spidev.h>#include <linux/uaccess.h>
#include <linux/gpio/consumer.h>
#include <linux/delay.h>
#include <linux/of_gpio.h>
/*-------------------------------------------------------------------------*/static struct spi_device *rc522_spi_device;
static struct device *rc522_device;
static int major;
static struct gpio_desc *rst_gpio;
static struct gpio_desc *cs_gpio;//static struct device_node *rc522_node;static unsigned char read_one_reg(unsigned char reg);
static void write_one_reg(unsigned char reg, unsigned char value);static void rc522_reset_disable(void)
{gpiod_set_value(rst_gpio, 1);
}static void rc522_reset_enable(void)
{gpiod_set_value(rst_gpio, 0);
}static int rc522_drv_open(struct inode *inode, struct file *file)
{printk("%s %s line %d\n", __FILE__, __FUNCTION__, __LINE__);rc522_reset_disable();udelay(1);rc522_reset_enable();udelay(1);rc522_reset_disable();udelay(1);return 0;
}static ssize_t rc522_drv_read(struct file *file, char __user *buf, size_t size, loff_t *offset)
{int ret = 0;unsigned char ker_buf[2];memset(ker_buf, 0, sizeof(ker_buf) / sizeof(ker_buf[0]));ret = copy_from_user(&ker_buf[0], buf, 1);if(ret < 0){printk("copy_from_user err!\n");return -1;}ker_buf[1] = read_one_reg(ker_buf[0]);ret = copy_to_user((void *)buf, &ker_buf[1], 1);if(ret < 0){printk("copy_to_user err!\n");return -1;}return 0;
}static ssize_t rc522_drv_write(struct file *file, const char __user *buf, size_t size, loff_t *offset)
{int ret = 0;unsigned char ker_buf[2];memset(ker_buf, 0, sizeof(ker_buf) / sizeof(ker_buf[0]));ret = copy_from_user(ker_buf, buf, 2);if(ret < 0){printk("copy_from_user err!\n");return -1;}write_one_reg(ker_buf[0], ker_buf[1]);return 0;
}static int rc522_drv_close(struct inode *inode, struct file *file)
{printk("%s %s line %d\n", __FILE__, __FUNCTION__, __LINE__);rc522_reset_enable();gpiod_put(rst_gpio);gpiod_put(cs_gpio);return 0;
}static const struct file_operations spidev_fops = {.owner = THIS_MODULE,/* REVISIT switch to aio primitives, so that userspace* gets more complete API coverage. It'll simplify things* too, except for the locking.*/.open = rc522_drv_open,.read = rc522_drv_read,.write = rc522_drv_write,.release = rc522_drv_close,
};
int value;static int spi_read_regs(unsigned char reg, unsigned char *buf, int len)
{int ret = 0;unsigned char txdata[len];struct spi_message message;struct spi_transfer *transfer;/* 片选使能 */gpiod_set_value(cs_gpio, 0);/* 申请并初始化 spi_transfer */transfer = kzalloc(sizeof(struct spi_transfer), GFP_KERNEL);/* 将读寄存器地址修改为正确的格式 addr = ((reg << 1) & 0x7E) | 0x80 */txdata[0] = ((reg << 1) & 0x7E) | 0x80;transfer->tx_buf = txdata;transfer->len = 1;/* 初始化 spi_message */spi_message_init(&message);/* 将 spi_transger 加入 spi_message 的尾部 */spi_message_add_tail(transfer, &message);/* 开启 spi_sync 传输地址 */ret = spi_sync(rc522_spi_device, &message);if(ret < 0){printk("spi_sync err!\n");return -1;}/* 读该寄存器的数据 */txdata[0] = 0xff;transfer->rx_buf = buf;transfer->len = len;/* 初始化 spi_message */spi_message_init(&message);/* 将 spi_transger 加入 spi_message 的尾部 */spi_message_add_tail(transfer, &message);/* 开启 spi_sync 接收数据 */ret = spi_sync(rc522_spi_device, &message);if(ret < 0){printk("spi_sync err!\n");return -1;}/*释放 spi_transfer */kfree(transfer);/* 片选失能 */gpiod_set_value(cs_gpio, 1);return ret;
}static int spi_write_regs(unsigned char reg, unsigned char *buf, int len)
{int ret = 0;unsigned char txdata[len];struct spi_message message;struct spi_transfer *transfer;/* 片选使能 */gpiod_set_value(cs_gpio, 0);/* 申请并初始化 spi_transfer */transfer = kzalloc(sizeof(struct spi_transfer), GFP_KERNEL);/* 将写寄存器地址修改为正确的格式 addr = ((reg << 1) & 0x7E)*/txdata[0] = (reg << 1) & 0x7E;transfer->tx_buf = txdata;transfer->len = 1;/* 初始化 spi_message */spi_message_init(&message);/* 将 spi_transger 加入 spi_message 的尾部 */spi_message_add_tail(transfer, &message);/* 开启 spi_sync 传输地址 */ret = spi_sync(rc522_spi_device, &message);if(ret < 0){printk("spi_sync err!\n");return -1;}/* 写该寄存器的数据 */transfer->tx_buf = buf;transfer->len = len;/* 初始化 spi_message */spi_message_init(&message);/* 将 spi_transger 加入 spi_message 的尾部 */spi_message_add_tail(transfer, &message);/* 开启 spi_sync 传输写该寄存器的数据 */ret = spi_sync(rc522_spi_device, &message); if(ret < 0){printk("spi_sync err!\n");return -1;}/*释放 spi_transfer */kfree(transfer);/* 片选失能 */gpiod_set_value(cs_gpio, 1);return ret;
}/* 读一个地址的一个字节的数据*/
static unsigned char read_one_reg(unsigned char reg)
{unsigned char buf = 0;spi_read_regs(reg, &buf, 1); return buf;
}/* 写一个地址的一个字节的数据*/
static void write_one_reg(unsigned char reg, unsigned char value)
{unsigned char buf = value;spi_write_regs(reg, &buf, 1);
}/* rc522 初始化 */
static void rc522_init(void)
{int ret;rc522_reset_disable();udelay(10);ret = gpiod_direction_output(cs_gpio, 1);if(ret < 0){printk("gpio_direction_output err!\n");}udelay(10);
}
/*-------------------------------------------------------------------------*//* The main reason to have this class is to make mdev/udev create the* /dev/spidevB.C character device nodes exposing our userspace API.* It also simplifies memory management.*/static struct class *rc522_class;/*-------------------------------------------------------------------------*/static int spidev_probe(struct spi_device *spi)
{int ret = 0;printk("%s %s line %d\n", __FILE__, __FUNCTION__, __LINE__);/* 1. 记录spi设备 */rc522_spi_device = spi;/* 2. 注册spi字符设备 */major = register_chrdev(0, "100ask_rc522", &spidev_fops);if(major < 0){printk("register_chrdev err!\n");return -1;}rc522_class = class_create(THIS_MODULE, "100ask_rc522_class");if(rc522_class == NULL){printk("class_create err!\n");return -1;}rc522_device = device_create(rc522_class, NULL, MKDEV(major, 0), NULL, "100ask_rc522");if(rc522_device == NULL){printk("device_create err!\n");return -1;}/* 获取cs_gpio */cs_gpio = gpiod_get(&spi->dev, "cs", 0);if(cs_gpio == NULL){printk("gpiod_get cs_gpio err!\n");return -1;}/* 获取rst_gpio */rst_gpio = gpiod_get(&spi->dev, "rst", 0);if(rst_gpio == NULL){printk("gpiod_get rst_gpio err!\n");return -1;}/* spi 模式0 */spi->mode = SPI_MODE_0;/* 启动 spi */spi_setup(spi);/* 记录 spi device 返回给数据传输函数 */rc522_spi_device = spi;rc522_init();return ret;/*rst_node = of_find_node_by_path("/rc522_rst_gpio");if(rst_node == NULL){printk("of_find_node_by_path err!\n");return -1;}rst_gpio = of_get_named_gpio(rst_node, "rst-gpio", 0);if(rst_gpio < 0){printk("of_get_named_gpio err!\n");return -1;}ret = gpio_direction_output(rst_gpio, 1);if(ret < 0){printk("gpiod_direction_output err!\n");return -1;}cs_node = of_find_node_by_path("/rc522_cs_gpio");if(cs_node == NULL){printk("of_find_node_by_path err!\n");return -1;}cs_gpio = of_get_named_gpio(cs_node, "cs-gpio", 0);if(cs_gpio < 0){printk("of_get_named_gpio err!\n");return -1;}ret = gpio_direction_output(cs_gpio, 1);if(ret < 0){printk("gpiod_direction_output err!\n");return -1;}*//*rc522_node = of_find_node_by_path("/soc/aips-bus@02000000/spba-bus@02000000/ecspi@02008000");if(rc522_node == NULL){//printk("of_find_node_by_path err!\n");//return -1;}cs_gpio = of_get_named_gpio(rc522_node, "cs-gpios", 0);if(cs_gpio < 0){//printk("of_get_named_gpio_flags err!\n");//return -1;}gpio_direction_output(cs_gpio, 1);*/
}static int spidev_remove(struct spi_device *spi)
{printk("%s %s line %d\n", __FILE__, __FUNCTION__, __LINE__);/* 释放 rst_gpio, cs_gpio */gpiod_put(rst_gpio);gpiod_put(cs_gpio);/* 卸载spi字符设备 */device_destroy(rc522_class, MKDEV(major, 0));class_destroy(rc522_class);unregister_chrdev(major, "100ask_rc522");return 0;
}static const struct of_device_id rc522_of_match[] = {{ .compatible = "100ask,rc522" },{},
};static const struct spi_device_id rc522_id[] = {{"100ask,rc522", 0},{}
};static struct spi_driver rc522_spi_driver = {.driver = {.name = "100ask_spi_rc522_drv",.of_match_table = of_match_ptr(rc522_of_match),},.probe = spidev_probe,.remove = spidev_remove,.id_table = rc522_id,/* NOTE: suspend/resume methods are not necessary here.* We don't do anything except pass the requests to/from* the underlying controller. The refrigerator handles* most issues; the controller driver handles the rest.*/
};/*-------------------------------------------------------------------------*/static int __init rc522_spi_init(void)
{int status;printk("%s %s line %d\n", __FILE__, __FUNCTION__, __LINE__);status = spi_register_driver(&rc522_spi_driver);if (status < 0) printk("spi_register_driver err!\n");elseprintk("spi_register_driver sucess!\n");return status;
}static void __exit rc522_spi_exit(void)
{printk("%s %s line %d\n", __FILE__, __FUNCTION__, __LINE__);spi_unregister_driver(&rc522_spi_driver);
}module_init(rc522_spi_init);
module_exit(rc522_spi_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("JunCxue");
四、测试程序
1.rc522_ap.c
#include <stdlib.h> /* using sleep() */
#include <fcntl.h> /* using file operation */
#include <sys/ioctl.h> /* using ioctl() */
#include <asm/ioctls.h>
#include <unistd.h> //sleep write read close
// #include <stdint.h>
#include <stdio.h>
#include <string.h>
#include "rc522_app.h"
#include <pthread.h>
#include <semaphore.h>#define ReadFlag 1
#define WriteFlag 0int fd = 0;//文件句柄/*** @brief 读RC522寄存器* @param ucAddress,寄存器地址* @retval 寄存器的当前值*/
uint8_t ReadRawRC( uint8_t Address )
{uint8_t buf[1]; buf[0] = Address; read(fd,buf,1); return buf[0];
}/*** @brief 写RC522寄存器* @param ucAddress,寄存器地址* @param ucValue,写入寄存器的值* @retval 无*/
void WriteRawRC( uint8_t Address, uint8_t Value )
{ uint8_t buf[2]; buf[0] = Address;buf[1] = Value;write(fd,buf,2);
}/*** @brief 对RC522寄存器置位* @param ucReg,寄存器地址* @param ucMask,置位值* @retval 无*/
void SetBitMask ( uint8_t ucReg, uint8_t ucMask )
{uint8_t ucTemp;ucTemp = ReadRawRC ( ucReg );WriteRawRC ( ucReg, ucTemp | ucMask ); // set bit mask
}/*** @brief 对RC522寄存器清位* @param ucReg,寄存器地址* @param ucMask,清位值* @retval 无*/
void ClearBitMask ( uint8_t ucReg, uint8_t ucMask )
{uint8_t ucTemp;ucTemp = ReadRawRC ( ucReg );WriteRawRC ( ucReg, ucTemp & ( ~ ucMask) ); // clear bit mask
}/*** @brief 开启天线 * @param 无* @retval 无*/
void PcdAntennaOn ( void )
{uint8_t uc;uc = ReadRawRC ( TxControlReg );if ( ! ( uc & 0x03 ) )SetBitMask(TxControlReg, 0x03);
}/*** @brief 关闭天线* @param 无* @retval 无*/
void PcdAntennaOff ( void )
{ClearBitMask ( TxControlReg, 0x03 );
}/*** @brief 复位RC522 * @param 无* @retval 0:复位成功 */
int PcdReset(void)
{fd = open("/dev/100ask_rc522",O_RDWR);if(fd < 0){printf("open rc522_drv error %d\n",fd);return fd;}WriteRawRC ( CommandReg, 0x0f );while ( ReadRawRC ( CommandReg ) & 0x10 );//定义发送和接收常用模式 和Mifare卡通讯,CRC初始值0x6363WriteRawRC ( ModeReg, 0x3D ); WriteRawRC ( TReloadRegL, 30 ); //16位定时器低位 WriteRawRC ( TReloadRegH, 0 ); //16位定时器高位 WriteRawRC ( TModeReg, 0x8D ); //定义内部定时器的设置 WriteRawRC ( TPrescalerReg, 0x3E ); //设置定时器分频系数 WriteRawRC ( TxAutoReg, 0x40 ); //调制发送信号为100%ASK return 0;
}/*** @brief 设置RC522的工作方式* @param ucType,工作方式* @retval 无*/
void M500PcdConfigISOType ( uint8_t ucType )
{if ( ucType == 'A') //ISO14443_A{ClearBitMask ( Status2Reg, 0x08 ); WriteRawRC ( ModeReg, 0x3D ); //3F WriteRawRC ( RxSelReg, 0x86 ); //84 WriteRawRC( RFCfgReg, 0x7F ); //4F WriteRawRC( TReloadRegL, 30 ); WriteRawRC ( TReloadRegH, 0 ); WriteRawRC ( TModeReg, 0x8D ); WriteRawRC ( TPrescalerReg, 0x3E ); usleep(10000); PcdAntennaOn ();//开天线 }
}/*** @brief 通过RC522和ISO14443卡通讯* @param ucCommand,RC522命令字* @param pInData,通过RC522发送到卡片的数据* @param ucInLenByte,发送数据的字节长度* @param pOutData,接收到的卡片返回数据* @param pOutLenBit,返回数据的位长度* @retval 状态值= MI_OK,成功*/
char PcdComMF522 ( uint8_t ucCommand,uint8_t * pInData, uint8_t ucInLenByte, uint8_t * pOutData,uint32_t * pOutLenBit )
{char cStatus = MI_ERR;uint8_t ucIrqEn = 0x00;uint8_t ucWaitFor = 0x00;uint8_t ucLastBits;uint8_t ucN;uint32_t ul;switch ( ucCommand ){case PCD_AUTHENT: //Mifare认证ucIrqEn = 0x12; //允许错误中断请求ErrIEn 允许空闲中断IdleIEnucWaitFor = 0x10; //认证寻卡等待时候 查询空闲中断标志位break;case PCD_TRANSCEIVE: //接收发送 发送接收ucIrqEn = 0x77; //允许TxIEn RxIEn IdleIEn LoAlertIEn ErrIEn TimerIEnucWaitFor = 0x30; //寻卡等待时候 查询接收中断标志位与 空闲中断标志位break;default:break; }//IRqInv置位管脚IRQ与Status1Reg的IRq位的值相反 WriteRawRC ( ComIEnReg, ucIrqEn | 0x80 );//Set1该位清零时,CommIRqReg的屏蔽位清零ClearBitMask ( ComIrqReg, 0x80 ); //写空闲命令WriteRawRC ( CommandReg, PCD_IDLE ); //置位FlushBuffer清除内部FIFO的读和写指针以及ErrReg的BufferOvfl标志位被清除SetBitMask ( FIFOLevelReg, 0x80 ); for ( ul = 0; ul < ucInLenByte; ul ++ )WriteRawRC ( FIFODataReg, pInData [ ul ] ); //写数据进FIFOdataWriteRawRC ( CommandReg, ucCommand ); //写命令if ( ucCommand == PCD_TRANSCEIVE )//StartSend置位启动数据发送 该位与收发命令使用时才有效SetBitMask(BitFramingReg,0x80); ul = 1000; //根据时钟频率调整,操作M1卡最大等待时间25msdo //认证 与寻卡等待时间 {ucN = ReadRawRC ( ComIrqReg ); //查询事件中断ul --;} while ( ( ul != 0 ) && ( ! ( ucN & 0x01 ) ) && ( ! ( ucN & ucWaitFor ) ) ); ClearBitMask ( BitFramingReg, 0x80 ); //清理允许StartSend位if ( ul != 0 ){//读错误标志寄存器BufferOfI CollErr ParityErr ProtocolErrif ( ! ( ReadRawRC ( ErrorReg ) & 0x1B ) ) {cStatus = MI_OK;if ( ucN & ucIrqEn & 0x01 ) //是否发生定时器中断cStatus = MI_NOTAGERR; if ( ucCommand == PCD_TRANSCEIVE ){//读FIFO中保存的字节数ucN = ReadRawRC ( FIFOLevelReg ); //最后接收到得字节的有效位数ucLastBits = ReadRawRC ( ControlReg ) & 0x07; if ( ucLastBits )//N个字节数减去1(最后一个字节)+最后一位的位数 读取到的数据总位数* pOutLenBit = ( ucN - 1 ) * 8 + ucLastBits; else* pOutLenBit = ucN * 8; //最后接收到的字节整个字节有效if ( ucN == 0 ) ucN = 1; if ( ucN > MAXRLEN )ucN = MAXRLEN; for ( ul = 0; ul < ucN; ul ++ )pOutData [ ul ] = ReadRawRC ( FIFODataReg ); } } elsecStatus = MI_ERR; }SetBitMask ( ControlReg, 0x80 ); // stop timer nowWriteRawRC ( CommandReg, PCD_IDLE ); return cStatus;
}/*** @brief 寻卡* @param ucReq_code,寻卡方式 = 0x52,寻感应区内所有符合14443A标准的卡;寻卡方式= 0x26,寻未进入休眠状态的卡* @param pTagType,卡片类型代码= 0x4400,Mifare_UltraLight= 0x0400,Mifare_One(S50)= 0x0200,Mifare_One(S70)= 0x0800,Mifare_Pro(X))= 0x4403,Mifare_DESFire* @retval 状态值= MI_OK,成功*/
char PcdRequest ( uint8_t ucReq_code, uint8_t * pTagType )
{char cStatus; uint8_t ucComMF522Buf [ MAXRLEN ]; uint32_t ulLen;//清理指示MIFARECyptol单元接通以及所有卡的数据通信被加密的情况ClearBitMask ( Status2Reg, 0x08 );//发送的最后一个字节的 七位WriteRawRC ( BitFramingReg, 0x07 );//ClearBitMask ( TxControlReg, 0x03 ); //TX1,TX2管脚的输出信号传递经发送调制的13.56的能量载波信号//usleep(10000); //SetBitMask ( TxControlReg, 0x03 ); ucComMF522Buf [ 0 ] = ucReq_code; //存入 卡片命令字cStatus = PcdComMF522 ( PCD_TRANSCEIVE, ucComMF522Buf,1, ucComMF522Buf,& ulLen ); //寻卡 if ( ( cStatus == MI_OK ) && ( ulLen == 0x10 ) ) //寻卡成功返回卡类型 { * pTagType = ucComMF522Buf [ 0 ];* ( pTagType + 1 ) = ucComMF522Buf [ 1 ];}elsecStatus = MI_ERR;return cStatus;
}/*** @brief 防冲撞* @param pSnr,卡片序列号,4字节* @retval 状态值= MI_OK,成功*/
char PcdAnticoll ( uint8_t * pSnr )
{char cStatus;uint8_t uc, ucSnr_check = 0;uint8_t ucComMF522Buf [ MAXRLEN ]; uint32_t ulLen;//清MFCryptol On位 只有成功执行MFAuthent命令后,该位才能置位ClearBitMask ( Status2Reg, 0x08 );//清理寄存器 停止收发WriteRawRC ( BitFramingReg, 0x00); //清ValuesAfterColl所有接收的位在冲突后被清除ClearBitMask ( CollReg, 0x80 ); ucComMF522Buf [ 0 ] = 0x93; //卡片防冲突命令ucComMF522Buf [ 1 ] = 0x20;cStatus = PcdComMF522 ( PCD_TRANSCEIVE, ucComMF522Buf,2, ucComMF522Buf,& ulLen); //与卡片通信if ( cStatus == MI_OK) //通信成功{for ( uc = 0; uc < 4; uc ++ ){* ( pSnr + uc ) = ucComMF522Buf [ uc ]; //读出UIDucSnr_check ^= ucComMF522Buf [ uc ];}if ( ucSnr_check != ucComMF522Buf [ uc ] )cStatus = MI_ERR; }SetBitMask ( CollReg, 0x80 );return cStatus;
}/*** @brief 用RC522计算CRC16* @param pIndata,计算CRC16的数组* @param ucLen,计算CRC16的数组字节长度* @param pOutData,存放计算结果存放的首地址* @retval 无*/
void CalulateCRC ( uint8_t * pIndata, uint8_t ucLen, uint8_t * pOutData )
{uint8_t uc, ucN;ClearBitMask(DivIrqReg,0x04);WriteRawRC(CommandReg,PCD_IDLE);SetBitMask(FIFOLevelReg,0x80);for ( uc = 0; uc < ucLen; uc ++)WriteRawRC ( FIFODataReg, * ( pIndata + uc ) ); WriteRawRC ( CommandReg, PCD_CALCCRC );uc = 0xFF;do {ucN = ReadRawRC ( DivIrqReg );uc --;} while ( ( uc != 0 ) && ! ( ucN & 0x04 ) );pOutData [ 0 ] = ReadRawRC ( CRCResultRegL );pOutData [ 1 ] = ReadRawRC ( CRCResultRegM );
}/*** @brief 选定卡片* @param pSnr,卡片序列号,4字节* @retval 状态值= MI_OK,成功*/
char PcdSelect ( uint8_t * pSnr )
{char ucN;uint8_t uc;uint8_t ucComMF522Buf [ MAXRLEN ]; uint32_t ulLen;ucComMF522Buf [ 0 ] = PICC_ANTICOLL1;ucComMF522Buf [ 1 ] = 0x70;ucComMF522Buf [ 6 ] = 0;for ( uc = 0; uc < 4; uc ++ ){ucComMF522Buf [ uc + 2 ] = * ( pSnr + uc );ucComMF522Buf [ 6 ] ^= * ( pSnr + uc );}CalulateCRC ( ucComMF522Buf, 7, & ucComMF522Buf [ 7 ] );ClearBitMask ( Status2Reg, 0x08 );ucN = PcdComMF522 ( PCD_TRANSCEIVE,ucComMF522Buf,9,ucComMF522Buf, & ulLen );if ( ( ucN == MI_OK ) && ( ulLen == 0x18 ) )ucN = MI_OK; elseucN = MI_ERR; return ucN;
}
/*** @brief 验证卡片密码* @param ucAuth_mode,密码验证模式= 0x60,验证A密钥,密码验证模式= 0x61,验证B密钥* @param uint8_t ucAddr,块地址* @param pKey,密码 * @param pSnr,卡片序列号,4字节* @retval 状态值= MI_OK,成功*/
char PcdAuthState ( uint8_t ucAuth_mode, uint8_t ucAddr, uint8_t * pKey,uint8_t * pSnr )
{char cStatus;uint8_t uc, ucComMF522Buf [ MAXRLEN ];uint32_t ulLen;ucComMF522Buf [ 0 ] = ucAuth_mode;ucComMF522Buf [ 1 ] = ucAddr;for ( uc = 0; uc < 6; uc ++ )ucComMF522Buf [ uc + 2 ] = * ( pKey + uc ); for ( uc = 0; uc < 6; uc ++ )ucComMF522Buf [ uc + 8 ] = * ( pSnr + uc ); cStatus = PcdComMF522 ( PCD_AUTHENT,ucComMF522Buf, 12,ucComMF522Buf,& ulLen );if ( ( cStatus != MI_OK ) || ( ! ( ReadRawRC ( Status2Reg ) & 0x08 ) ) )cStatus = MI_ERR; return cStatus;
}/*** @brief 写数据到M1卡一块* @param uint8_t ucAddr,块地址* @param pData,写入的数据,16字节* @retval 状态值= MI_OK,成功*/
char PcdWrite ( uint8_t ucAddr, uint8_t * pData )
{char cStatus;uint8_t uc, ucComMF522Buf [ MAXRLEN ];uint32_t ulLen;ucComMF522Buf [ 0 ] = PICC_WRITE;ucComMF522Buf [ 1 ] = ucAddr;CalulateCRC ( ucComMF522Buf, 2, & ucComMF522Buf [ 2 ] );cStatus = PcdComMF522 ( PCD_TRANSCEIVE,ucComMF522Buf,4, ucComMF522Buf,& ulLen );if ( ( cStatus != MI_OK ) || ( ulLen != 4 ) || ( ( ucComMF522Buf [ 0 ] & 0x0F ) != 0x0A ) )cStatus = MI_ERR; if ( cStatus == MI_OK ){//memcpy(ucComMF522Buf, pData, 16);for ( uc = 0; uc < 16; uc ++ )ucComMF522Buf [ uc ] = * ( pData + uc ); CalulateCRC ( ucComMF522Buf, 16, & ucComMF522Buf [ 16 ] );cStatus = PcdComMF522 ( PCD_TRANSCEIVE,ucComMF522Buf, 18, ucComMF522Buf,& ulLen );if ( ( cStatus != MI_OK ) || ( ulLen != 4 ) || ( ( ucComMF522Buf [ 0 ] & 0x0F ) != 0x0A ) )cStatus = MI_ERR; } return cStatus;
}
/*** @brief 读取M1卡一块数据* @param ucAddr,块地址* @param pData,读出的数据,16字节* @retval 状态值= MI_OK,成功*/
char PcdRead ( uint8_t ucAddr, uint8_t * pData )
{char cStatus;uint8_t uc, ucComMF522Buf [ MAXRLEN ]; uint32_t ulLen;ucComMF522Buf [ 0 ] = PICC_READ;ucComMF522Buf [ 1 ] = ucAddr;CalulateCRC ( ucComMF522Buf, 2, & ucComMF522Buf [ 2 ] );cStatus = PcdComMF522 ( PCD_TRANSCEIVE,ucComMF522Buf,4, ucComMF522Buf,& ulLen );if ( ( cStatus == MI_OK ) && ( ulLen == 0x90 ) ){for ( uc = 0; uc < 16; uc ++ )* ( pData + uc ) = ucComMF522Buf [ uc ]; }elsecStatus = MI_ERR; return cStatus;
}/*** @brief 命令卡片进入休眠状态* @param 无* @retval 状态值= MI_OK,成功*/
char PcdHalt( void )
{uint8_t ucComMF522Buf [ MAXRLEN ]; uint32_t ulLen;ucComMF522Buf [ 0 ] = PICC_HALT;ucComMF522Buf [ 1 ] = 0;CalulateCRC ( ucComMF522Buf, 2, & ucComMF522Buf [ 2 ] );PcdComMF522 ( PCD_TRANSCEIVE,ucComMF522Buf,4, ucComMF522Buf, & ulLen );return MI_OK;
}
void IC_CMT ( uint8_t * UID,uint8_t * KEY,uint8_t RW,uint8_t * Dat )
{uint8_t ucArray_ID [ 4 ] = { 0 }; //先后存放IC卡的类型和UID(IC卡序列号)PcdRequest ( 0x52, ucArray_ID ); //寻卡PcdAnticoll ( ucArray_ID ); //防冲撞PcdSelect ( UID ); //选定卡PcdAuthState ( 0x60, 0x10, KEY, UID );//校验if ( RW ) //读写选择,1是读,0是写PcdRead ( 0x10, Dat );else PcdWrite ( 0x10, Dat );PcdHalt ();
}void IC_Read_Or_Write(uint8_t flag, unsigned char *WriteData, uint8_t *readValue)
{uint8_t KeyValue[]={0xFF ,0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; // 卡A密钥// u8 status = 0;char cStr [ 30 ];uint8_t ucArray_ID [ 4 ]; /*先后存放IC卡的类型和UID(IC卡序列号)*/ uint8_t ucStatusReturn; /*返回状态*/ /*寻卡*/if ( ( ucStatusReturn = PcdRequest ( PICC_REQIDL, ucArray_ID ) ) != MI_OK ) {/*若失败再次寻卡*/ucStatusReturn = PcdRequest ( PICC_REQIDL, ucArray_ID );//printf("ucStatusReturn: %d\n", ucStatusReturn);} if ( ucStatusReturn == MI_OK ){/*防冲撞(当有多张卡进入读写器操作范围时,防冲突机制会从其中选择一张进行操作)*/if ( PcdAnticoll ( ucArray_ID ) == MI_OK ) {printf("select card\n");PcdSelect(ucArray_ID); // 选卡 ucStatusReturn = PcdAuthState( PICC_AUTHENT1A, 0x11, KeyValue, ucArray_ID );//校验密码if(ucStatusReturn == MI_OK)printf("compare password\n"); if (flag == WriteFlag)PcdWrite(0x11, WriteData);if (PcdRead(0x11, readValue) != MI_OK){printf("read err!\r\n");}else{sprintf ( cStr, "The Card ID is: %02X%02X%02X%02X",ucArray_ID [0], ucArray_ID [1], ucArray_ID [2],ucArray_ID [3] );printf ( "%s\r\n",cStr ); //打印卡片ID printf ("readValue: %s\r\n",readValue);PcdHalt();}} }
}static unsigned char mode = 0; /* write : mode = 0, read : mode = 1*/
static pthread_cond_t mode_cond = PTHREAD_COND_INITIALIZER;
static pthread_mutex_t mode_mutex = PTHREAD_MUTEX_INITIALIZER;#if 0
static void *IC_Select_Thread_Func(void *arg)
{ unsigned char write_value = 100;unsigned char read_value;char cStr[30];while(1){ unsigned char ucStatusReturn; /*返回状态*/ unsigned char KeyValue[]={0xFF ,0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; // 卡A密钥unsigned char ucArray_ID [ 4 ]; /*先后存放IC卡的类型和UID(IC卡序列号)*/ ucStatusReturn = PcdRequest(PICC_REQIDL, ucArray_ID);if(ucStatusReturn == MI_OK){/*防冲撞(当有多张卡进入读写器操作范围时,防冲突机制会从其中选择一张进行操作)*/ucStatusReturn = PcdAnticoll(ucArray_ID);if (ucStatusReturn == MI_OK) {printf("select card!\n");/* 操作选中的卡 */PcdSelect(ucArray_ID);/* 校验密码 */ucStatusReturn = PcdAuthState( PICC_AUTHENT1A, 0x11, KeyValue, ucArray_ID );if(ucStatusReturn == MI_OK){/* 读卡 : mode = 1, 写卡 : mode = 1*/mode = 1;}if(mode){if(PcdRead(0x11, &read_value) != MI_OK)printf("read err!\n");else{sprintf ( cStr, "The Card ID is: %02X%02X%02X%02X",ucArray_ID [0], ucArray_ID [1], ucArray_ID [2],ucArray_ID [3] );printf ( "%s\r\n",cStr ); //打印卡片ID printf ("readValue: %d\r\n",read_value);PcdHalt();}}else{ucStatusReturn = PcdWrite(0x11, &write_value);if(ucStatusReturn == MI_OK)printf("write sucess!\n");elseprintf("write err!\n");} }}elseucStatusReturn = PcdRequest(PICC_REQIDL, ucArray_ID);sleep(1);}
}
#endif#if 0
void my_test(void)
{pthread_t IC_Select_Thread;int ret;ret = pthread_create(&IC_Select_Thread, NULL, IC_Select_Thread_Func, NULL);if(ret != 0)printf("pthread_create IC_Select_Thread err!\n");
}
#endifvoid test(void)
{uint8_t readdata[30] = { 0 };uint32_t times = 0;/*RC522模块所需外设的初始化配置*/// rc522_init (); // printk ( "WF-RC522 Test\n" );// PcdReset ();// /*设置工作方式*/// M500PcdConfigISOType ( 'A' );while (1){IC_Read_Or_Write(ReadFlag, NULL, readdata);// printf("%s %s %d\r\n", __FILE__, __FUNCTION__, __LINE__);// printf("main func read is %s\r\n", readdata);times++;if (times >= 100000)memset (readdata, 0, sizeof(readdata));}
}
2.rc522_app.h
#ifndef _RC522_H
#define _RC522_H#include <stdint.h>/*
//MF522命令字
*/
#define PCD_IDLE 0x00 //取消当前命令
#define PCD_AUTHENT 0x0E //验证密钥
#define PCD_RECEIVE 0x08 //接收数据
#define PCD_TRANSMIT 0x04 //发送数据
#define PCD_TRANSCEIVE 0x0C //发送并接收数据
#define PCD_RESETPHASE 0x0F //复位
#define PCD_CALCCRC 0x03 //CRC计算/*
//Mifare_One卡片命令字
*/
#define PICC_REQIDL 0x26 //寻天线区内未进入休眠状态
#define PICC_REQALL 0x52 //寻天线区内全部卡
#define PICC_ANTICOLL1 0x93 //防冲撞
#define PICC_ANTICOLL2 0x95 //防冲撞
#define PICC_AUTHENT1A 0x60 //验证A密钥
#define PICC_AUTHENT1B 0x61 //验证B密钥
#define PICC_READ 0x30 //读块
#define PICC_WRITE 0xA0 //写块
#define PICC_DECREMENT 0xC0 //扣款
#define PICC_INCREMENT 0xC1 //充值
#define PICC_RESTORE 0xC2 //调块数据到缓冲区
#define PICC_TRANSFER 0xB0 //保存缓冲区中数据
#define PICC_HALT 0x50 //休眠/*
//MF522 FIFO长度定义
*/
#define DEF_FIFO_LENGTH 64 //FIFO size=64byte
#define MAXRLEN 18/*
//MF522寄存器定义
/
// PAGE 0
*/#define RFU00 0x00
#define CommandReg 0x01
#define ComIEnReg 0x02
#define DivlEnReg 0x03
#define ComIrqReg 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 RFU0F 0x0F
/*PAGE 1*/
#define RFU10 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 RFU1A 0x1A
#define RFU1B 0x1B
#define MifareReg 0x1C
#define RFU1D 0x1D
#define RFU1E 0x1E
#define SerialSpeedReg 0x1F
/*PAGE 2*/
#define RFU20 0x20
#define CRCResultRegM 0x21
#define CRCResultRegL 0x22
#define RFU23 0x23
#define ModWidthReg 0x24
#define RFU25 0x25
#define RFCfgReg 0x26
#define GsNReg 0x27
#define CWGsCfgReg 0x28
#define ModGsCfgReg 0x29
#define TModeReg 0x2A
#define TPrescalerReg 0x2B
#define TReloadRegH 0x2C
#define TReloadRegL 0x2D
#define TCounterValueRegH 0x2E
#define TCounterValueRegL 0x2F
/*PAGE 3 */
#define RFU30 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 RFU3C 0x3C
#define RFU3D 0x3D
#define RFU3E 0x3E
#define RFU3F 0x3F/*
//和MF522通讯时返回的错误代码
*/
#define MI_OK 0x26
#define MI_NOTAGERR 0xcc
#define MI_ERR 0xbb
void test(void);#endif
3.rc522_test.c
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <asm/ioctls.h>
#include <unistd.h>
#include <stdint.h>
#include "rc522_app.h"int main(int argc, const char * argv [ ])
{int ret = -1;uint8_t buf[2];ret = PcdReset();if(ret != 0){printf("rc522 rst error %d \n",ret);return 0;}M500PcdConfigISOType ( 'A' );test();while(1){}
}
4.Makefile
# 1. 使用不同的开发板内核时, 一定要修改KERN_DIR
# 2. KERN_DIR中的内核要事先配置、编译, 为了能编译内核, 要先设置下列环境变量:
# 2.1 ARCH, 比如: export ARCH=arm64
# 2.2 CROSS_COMPILE, 比如: export CROSS_COMPILE=aarch64-linux-gnu-
# 2.3 PATH, 比如: export PATH=$PATH:/home/book/100ask_roc-rk3399-pc/ToolChain-6.3.1/gcc-linaro-6.3.1-2017.05-x86_64_aarch64-linux-gnu/bin
# 注意: 不同的开发板不同的编译器上述3个环境变量不一定相同,
# 请参考各开发板的高级用户使用手册KERN_DIR = /home/book/100ask_imx6ull-sdk/Linux-4.9.88 # 板子所用内核源码的目录Target=rc522_test
objects=rc522_test.c rc522_app.c
all:$(objects)make -C $(KERN_DIR) M=`pwd` modules $(CROSS_COMPILE)gcc -o $(Target) $^ -lpthread
clean:make -C $(KERN_DIR) M=`pwd` modules cleanrm -rf modules.order $(Target)# 参考内核源码drivers/char/ipmi/Makefile
# 要想把a.c, b.c编译成ab.ko, 可以这样指定:
# ab-y := a.o b.o
# obj-m += ab.oobj-m += rc522_spidrv.o
再次感谢那位大佬的文章,我向他提问,他也非常耐心的回答我的问题,非常感谢。